Skip to content

Commit d052cfd

Browse files
committed
edits
1 parent b32add9 commit d052cfd

File tree

4 files changed

+198
-1
lines changed

4 files changed

+198
-1
lines changed
File renamed without changes.
File renamed without changes.

source/tutorial/commands.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,4 +151,5 @@ The output would then resemble:
151151
["ok"]=>
152152
float(1)
153153
}
154-
}
154+
}
155+
}

source/tutorial/server-selection.txt

Lines changed: 196 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,196 @@
1+
:orphan:
2+
3+
===============================
4+
Server Selection and Monitoring
5+
===============================
6+
7+
.. meta::
8+
:description: Understand how the MongoDB PHP Library selects and monitors servers, including connection string options for server selection and monitoring.
9+
10+
11+
.. contents:: On this page
12+
:local:
13+
:backlinks: none
14+
:depth: 2
15+
:class: singlecol
16+
17+
Server Selection and Monitoring
18+
-------------------------------
19+
20+
Before any operation can be executed, the |php-library| must first select a
21+
server from the topology (e.g. replica set, sharded cluster). Selecting a server
22+
requires an accurate view of the topology, so the extension regularly monitors
23+
the servers to which it is connected.
24+
25+
In most other drivers, server discovery and monitoring is handled by a
26+
background thread; however, the PHP driver is single-threaded and must therefore
27+
perform monitoring *between* operations initiated by the application.
28+
29+
Consider the following example application:
30+
31+
.. code-block:: php
32+
33+
<?php
34+
35+
/**
36+
* When constructing a Client, the library creates a MongoDB\Driver\Manager
37+
* object from the extension. In turn, the extension will either create a
38+
* libmongoc client object (and persist it according to the constructor
39+
* parameters) or re-use a previously persisted client.
40+
*
41+
* Assuming a new libmongoc client was created, the host name(s) in the
42+
* connection string must be resolved via DNS. Likewise, if the connection
43+
* string includes a mongodb+srv scheme, SRV/TXT records must be resolved.
44+
* Following DNS resolution, the driver should then have a list of one or
45+
* more hosts to which it can connect. This is referred to as the seed list.
46+
*
47+
* If a previously persisted client was re-used, no DNS resolution is needed
48+
* and there will likely already be connections and topology state associated
49+
* with the client.
50+
*
51+
* Drivers perform no further IO when constructing a client, so control is
52+
* returned the the PHP script.
53+
*/
54+
$client = new MongoDB\Client('mongodb://a.example.com:27017/?replicaSet=rs0');
55+
56+
/**
57+
* The library creates a MongoDB\Database object from the Client. This does
58+
* not entail any IO, as the Database and Collection objects only associate
59+
* a database or namespace with a Client object, respectively.
60+
*/
61+
$database = $client->test;
62+
63+
/**
64+
* The library creates an internal object for this operation and must select
65+
* a server to use for executing that operation.
66+
*
67+
* If this is the first operation on the underlying libmongoc client, it must
68+
* first discover the topology. It does so by establishing connections to any
69+
* host(s) in the seed list (this may entail TLS and OCSP verification) and
70+
* issuing "hello" commands.
71+
*
72+
* In the case of a replica set, connecting to a single host in the seed list
73+
* should allow the driver to discover all other members in the replica set.
74+
* In the case of a sharded cluster, the driver will start with an initial
75+
* seed list of mongos hosts and, if SRV polling is utilized, may discover
76+
* additional mongos hosts over time.
77+
*
78+
* If the topology was already initialized (i.e. this is not the first
79+
* operation on the client), the driver may still need to perform monitoring
80+
* (i.e. "hello" commands) and refresh its view of the topology. This process
81+
* may entail adding or removing hosts from the topology.
82+
*
83+
* Once the topology has been discovered and any necessary monitoring has
84+
* been performed, the driver may select a server according to the rules
85+
* outlined in the server selection specification (e.g. applying a read
86+
* preference, filtering hosts by latency).
87+
*/
88+
$database->command(['ping' => 1]);
89+
90+
Although the application consists of only a few lines of PHP, there is actually
91+
quite a lot going on behind the scenes! Interested readers can find this process
92+
discussed in greater detail in the following documents:
93+
94+
- `Single-threaded Mode <http://mongoc.org/libmongoc/current/connection-pooling.html#single-mode>`_ in the libmongoc documentation
95+
- `Server Discovery and Monitoring <https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.md>`_ specification
96+
- `Server Selection <https://github.com/mongodb/specifications/blob/master/source/server-selection/server-selection.md>`_ specification
97+
98+
Connection String Options
99+
-------------------------
100+
101+
There are several connection string options relevant to server selection and
102+
monitoring.
103+
104+
connectTimeoutMS
105+
~~~~~~~~~~~~~~~~
106+
107+
``connectTimeoutMS`` specifies the limit for both establishing a connection to
108+
a server *and* the socket timeout for server monitoring (``hello`` commands).
109+
This defaults to 10 seconds for single-threaded drivers such as PHP.
110+
111+
When a server times out during monitoring, it will not be re-checked until at
112+
least five seconds
113+
(`cooldownMS <https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-monitoring.md#cooldownms>`_)
114+
have elapsed. This timeout is intended to avoid having single-threaded drivers
115+
block for ``connectTimeoutMS`` on *each* subsequent scan after an error.
116+
117+
Applications can consider setting this option to slightly more than the greatest
118+
latency among servers in the cluster. For example, if the greatest ``ping`` time
119+
between the PHP application server and a database server is 200ms, it may be
120+
reasonable to specify a timeout of one second. This would allow ample time for
121+
establishing a connection and monitoring an accessible server, while also
122+
significantly reducing the time to detect an inaccessible server.
123+
124+
heartbeatFrequencyMS
125+
~~~~~~~~~~~~~~~~~~~~
126+
127+
``heartbeatFrequencyMS`` determines how often monitoring should occur. This
128+
defaults to 60 seconds for single-threaded drivers and can be set as low as
129+
500ms.
130+
131+
serverSelectionTimeoutMS
132+
~~~~~~~~~~~~~~~~~~~~~~~~
133+
134+
``serverSelectionTimeoutMS`` determines the maximum amount of time to spend in
135+
the server selection loop. This defaults to 30 seconds, but applications will
136+
typically fail sooner if ``serverSelectionTryOnce`` is ``true`` and a smaller
137+
``connectTimeoutMS`` value is in effect.
138+
139+
The original default was established at a time when replica set elections took
140+
much longer to complete. Applications can consider setting this option to
141+
slightly more than the expected completion time for an election. For example,
142+
:manual:`Replica Set Elections </core/replica-set-elections/>` states that
143+
elections will not typically exceed 12 seconds, so a 15-second timeout may be
144+
reasonable. Applications connecting to a sharded cluster may consider a smaller
145+
value still, since ``mongos`` insulates the driver from elections.
146+
147+
That said, ``serverSelectionTimeoutMS`` should generally not be set to a value
148+
smaller than ``connectTimeoutMS``.
149+
150+
serverSelectionTryOnce
151+
~~~~~~~~~~~~~~~~~~~~~~
152+
153+
``serverSelectionTryOnce`` determines whether the driver should give up after
154+
the first failed server selection attempt or continue waiting until
155+
``serverSelectionTimeoutMS`` is reached. PHP defaults to ``true``, which allows
156+
the driver to "fail fast" when a server cannot be selected (e.g. no primary
157+
during a failover).
158+
159+
The default behavior is generally desirable for a high-traffic web applications,
160+
as it means the worker process will not be blocked in a server selection loop
161+
and can instead return an error response and immediately go on to serve another
162+
request. Additionally, other driver features such as retryable reads and writes
163+
can still enable applications to avoid transient errors such as a failover.
164+
165+
That said, applications that prioritize resiliency over response time (and
166+
worker pool utilization) may want to specify ``false`` for
167+
``serverSelectionTryOnce``.
168+
169+
socketCheckIntervalMS
170+
~~~~~~~~~~~~~~~~~~~~~
171+
172+
``socketCheckIntervalMS`` determines how often a socket should be checked (using
173+
a ``ping`` command) if it has not been used recently. This defaults to 5 seconds
174+
and is intentionally lower than ``heartbeatFrequencyMS`` to better allow
175+
single-threaded drivers to recover dropped connections.
176+
177+
socketTimeoutMS
178+
~~~~~~~~~~~~~~~
179+
180+
``socketTimeoutMS`` determines the maximum amount of time to spend reading or
181+
writing to a socket. Since server monitoring uses ``connectTimeoutMS`` for its
182+
socket timeouts, ``socketTimeoutMS`` only applies to operations executed by the
183+
application.
184+
185+
``socketTimeoutMS`` defaults to 5 minutes; however, it's likely that a PHP web
186+
request would be terminated sooner due to
187+
`max_execution_time <https://www.php.net/manual/en/info.configuration.php#ini.max-execution-time>`_,
188+
which defaults to 30 seconds for web SAPIs. In a CLI environment, where
189+
``max_execution_time`` is unlimited by default, it is more likely that
190+
``socketTimeoutMS`` could be reached.
191+
192+
.. note::
193+
194+
``socketTimeoutMS`` is not directly related to server selection and
195+
monitoring; however, it is frequently associated with the other options and
196+
therefore bears mentioning.

0 commit comments

Comments
 (0)