-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathfaq.txt
369 lines (284 loc) · 14.9 KB
/
faq.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
.. _node-faq:
===
FAQ
===
.. meta::
:description: Find answers to frequently asked questions about the Node.js driver, including connection pooling, timeouts, and handling network behavior.
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
This page contains frequently asked questions and their corresponding answers.
.. tip::
If you can't find an answer to your problem on this page,
see the :ref:`node-issues-help` page for next steps and more
resources.
Why Am I Getting Errors While Connecting to MongoDB?
----------------------------------------------------
If you have trouble connecting to a MongoDB deployment, see
the :ref:`Connection Troubleshooting Guide <node-connection-troubleshooting>`
for possible solutions.
.. _node-faq-connection-pool:
How Does Connection Pooling Work in the Node Driver?
----------------------------------------------------
Every ``MongoClient`` instance has a built-in connection pool for each server
in your MongoDB topology. Connection pools open sockets on demand to
support concurrent requests to MongoDB in your application.
The maximum size of each connection pool is set by the ``maxPoolSize`` option, which
defaults to ``100``. If the number of in-use connections to a server reaches
the value of ``maxPoolSize``, the next request to that server will wait
until a connection becomes available.
In addition to the sockets needed to support your application's requests,
each ``MongoClient`` instance opens two more sockets per server
in your MongoDB topology for monitoring the server's state.
For example, a client connected to a three-node replica set opens six
monitoring sockets. If the application uses the default setting for
``maxPoolSize`` and only queries the primary (default) node, then
there can be at most ``106`` total connections in the connection pool. If the
application uses a :ref:`read preference <read-preference>` to query the
secondary nodes, those connection pools grow and there can be
``306`` total connections.
To support high numbers of concurrent MongoDB requests
within one process, you can increase ``maxPoolSize``.
Connection pools are rate-limited. The ``maxConnecting`` option
determines the number of connections that the pool can create in
parallel at any time. For example, if the value of ``maxConnecting`` is
``2``, the third request that attempts to concurrently check out a
connection succeeds only when one the following cases occurs:
- The connection pool finishes creating a connection and there are fewer
than ``maxPoolSize`` connections in the pool.
- An existing connection is checked back into the pool.
- The driver's ability to reuse existing connections improves due to
rate-limits on connection creation.
You can set the minimum number of concurrent connections to
each server with the ``minPoolSize`` option, which defaults to ``0``.
The driver initializes the connection pool with this number of sockets. If
sockets are closed, causing the total number
of sockets (both in use and idle) to drop below the minimum, more
sockets are opened until the minimum is reached.
You can set the maximum number of milliseconds that a connection can
remain idle in the pool by setting the ``maxIdleTimeMS`` option.
Once a connection has been idle for ``maxIdleTimeMS``, the connection
pool removes and replaces it. This option defaults to ``0`` (no limit).
The following default configuration for a ``MongoClient`` works for most
applications:
.. code-block:: js
const client = new MongoClient("<connection string>");
``MongoClient`` supports multiple concurrent requests. For each process,
create a client and reuse it for all operations in a process. This
practice is more efficient than creating a client for each request.
The driver does not limit the number of requests that
can wait for sockets to become available, and it is the application's
responsibility to limit the size of its pool to bound queuing
during a load spike. Requests wait for the amount of time specified in
the ``waitQueueTimeoutMS`` option, which defaults to ``0`` (no limit).
A request that waits more than the length of time defined by
``waitQueueTimeoutMS`` for a socket raises a connection error. Use this
option if it is more important to bound the duration of operations
during a load spike than it is to complete every operation.
When ``MongoClient.close()`` is called by any request, the driver
closes all idle sockets and closes all sockets that are in
use as they are returned to the pool. Calling ``MongoClient.close()``
closes only inactive sockets and does not directly terminate
any ongoing operations. The driver closes any in-use sockets only when
the associated operations complete. However, the ``MongoClient.close()``
method does close existing sessions and transactions, which might indirectly
affect the behavior of ongoing operations and open cursors.
What Is the Difference Between "connectTimeoutMS", "socketTimeoutMS" and "maxTimeMS"?
-------------------------------------------------------------------------------------
.. list-table::
:widths: 22 78
:header-rows: 1
* - Setting
- Description
* - **connectTimeoutMS**
- ``connectTimeoutMS`` is a :ref:`connection option
<node-connection-options>` that sets the time, in milliseconds,
for an individual connection from your connection pool to
establish a TCP connection to the {+mdb-server+} before
timing out. To modify the allowed time for
`MongoClient.connect <{+api+}/classes/MongoClient.html#connect>`__ to establish a
connection to a {+mdb-server+}, use the ``serverSelectionTimeoutMS`` option instead.
**Default:** 30000
* - **socketTimeoutMS**
- ``socketTimeoutMS`` specifies the amount of time the driver waits
for an inactive socket before closing it. The default value is to
never time out the socket. This option applies only to sockets that
have already been connected.
* - **maxTimeMS**
- `maxTimeMS <{+api+}/classes/FindCursor.html#maxTimeMS>`__
specifies the maximum amount of time that the server
waits for an operation to complete after it has reached the
server. If an operation runs over the specified time limit, it
returns a timeout error. You can pass ``maxTimeMS`` only to an
individual operation or to a cursor.
To specify the optional settings for your ``MongoClient``, declare one or
more available settings in the ``options`` object of the constructor as
follows:
.. code-block:: javascript
const client = new MongoClient(uri, {
connectTimeoutMS: <integer value>,
socketTimeoutMS: <integer value>
});
To see all the available settings, see the
`MongoClientOptions <{+api+}/interfaces/MongoClientOptions.html>`__
API Documentation.
To specify ``maxTimeMS``, chain the ``maxTimeMS()`` method with a
timeout specification to an operation that returns a ``Cursor``:
.. code-block:: javascript
const cursor = myColl.find({}).maxTimeMS(50);
What Happens to Running Operations if the Client Disconnects?
-------------------------------------------------------------
Starting in {+mdb-server+} version 4.2, the server terminates
running operations such as aggregations and find operations if the
client disconnects.
Other operations, such as write operations, continue to run on the
{+mdb-server+} even if the client disconnects. This behavior can cause data
inconsistencies if your application retries the operation after the
client disconnects.
How Can I Confirm That the Driver Closed Unusable Sockets?
----------------------------------------------------------
If you experience unexpected network behavior or if a MongoDB process
fails with an error, you may not receive confirmation that the
driver correctly closed the corresponding socket.
To make sure that the driver correctly closes the socket in these cases,
set the ``socketTimeoutMS`` option. When a MongoDB process times out, the driver
will close the socket. We recommend that you select a value
for ``socketTimeoutMS`` that is two to three times longer than the
expected duration of the slowest operation that your application executes.
How Can I Prevent Sockets From Timing Out Before They Become Active?
--------------------------------------------------------------------
Having a large connection pool does not always reduce reconnection
requests. Consider the following example:
An application has a connection pool size of 5 sockets and has the
``socketTimeoutMS`` option set to 5000 milliseconds. Operations occur,
on average, every 3000 milliseconds, and reconnection requests are
frequent. Each socket times out after 5000 milliseconds, which means
that all sockets must do something during those 5000 milliseconds to
avoid closing.
One message every 3000 milliseconds is not enough to keep the sockets
active, so several of the sockets will time out after 5000 milliseconds.
To avoid excessive socket timeouts, reduce the number of connections
that the driver can maintain in the connection pool by specifying the
``maxPoolSize`` option.
To specify the optional ``maxPoolSize`` setting for your ``MongoClient``, declare
it in the ``options`` object of the constructor as follows:
.. code-block:: javascript
const client = new MongoClient(uri, {
maxPoolSize: <integer value>,
});
What Does a Value of "0" Mean for "connectTimeoutMS" and "socketTimeoutMS"?
---------------------------------------------------------------------------
If you set the value of ``connectTimeoutMS`` or ``socketTimeoutMS`` to
``0``, your application will use the operating system's default socket
timeout value.
How Can I Prevent Long-Running Operations From Slowing Down the Server?
-----------------------------------------------------------------------
You can prevent long-running operations from slowing down the server by
specifying a timeout value. You can chain the ``maxTimeMS()`` method to
an operation that returns a ``Cursor`` to set a timeout on a specific action.
The following example shows how you can chain the ``maxTimeMS()`` method
to an operation that returns a ``Cursor``:
.. literalinclude:: /code-snippets/faq/maxTimeMS-example.js
:language: javascript
.. _node-faq-keepalive:
What Does the keepAlive Option Do?
----------------------------------
The ``keepAlive`` connection option specifies whether to enable
:wikipedia:`Transmission Control Protocol (TCP) keepalives
<Keepalive#TCP_keepalive>` on a TCP socket. If you enable keepalives,
the driver checks whether the connection is active by sending periodic pings
to your MongoDB deployment. This functionality only works if your
operating system supports the ``SO_KEEPALIVE`` socket option.
The ``keepAliveInitialDelay`` option specifies the number of
milliseconds that the driver waits before initiating a keepalive.
The 5.3 driver version release deprecated these options. Starting in
version 6.0 of the driver, the ``keepAlive`` option is permanently set
to ``true``, and the ``keepAliveInitialDelay`` is set to 300000
milliseconds (300 seconds).
.. warning::
If your firewall ignores or drops the keepalive messages, you might
not be able to identify dropped connections.
What Can I Do If I'm Experiencing Unexpected Network Behavior?
--------------------------------------------------------------
You might experience unexpected network behavior if the firewall between
your application and MongoDB is misconfigured. These firewalls can be
overly aggressive in their removal of connections, which can lead to
unexpected errors.
Confirm that your firewall exhibits the following behavior:
- The firewall sends a ``FIN`` packet when closing a connection,
informing the driver that the socket is closed.
- The firewall allows keepalive messages.
.. tip::
To learn more about keepalive messages, see the :ref:`What Does the
keepAlive Option Do? <node-faq-keepalive>` FAQ entry.
How Can I Prevent a Slow Operation From Delaying Other Operations?
------------------------------------------------------------------
When you use the same ``MongoClient`` instance to run multiple MongoDB
operations concurrently, a slow operation can cause delays to other
operations. Slow operations keep a connection to MongoDB occupied,
which can cause other operations to wait until an additional connection
becomes available.
If you suspect that slow MongoDB operations are causing delays, you
can check the performance of all in-progress operations by using the
following methods:
- Enable the database profiler on your deployment. To learn more, see
:manual:`Database Profiler </tutorial/manage-the-database-profiler/>`
in the Server manual.
- Run the ``db.currentOp()`` MongoDB Shell command. To learn more, see the
:manual:`db.currentOp() </reference/method/db.currentOp/>`
documentation in the Server manual.
- Enable connection pool monitoring. To learn more, see
:ref:`node-connection-pool-monitoring`.
After you determine which operations are causing delays, try to improve
the performance of these operations. Read the :website:`Best Practices
Guide for MongoDB Performance </basics/best-practices>` for possible solutions.
If you implement performance best practices but still
experience delays, you can modify your connection settings to increase
the size of the connection pool. A connection pool is the group of
connections to the server that the driver maintains at any time.
To specify the maximum size of a
connection pool, you can set the ``maxPoolSize`` option in the
:ref:`connection options <node-connection-options>` for your
``MongoClient`` instance. The default value
of ``maxPoolSize`` is ``100``. If the number of in-use connections to a
server reaches ``maxPoolSize``, the next operation sent to the server
pauses until a connection to the driver becomes available. The following
code sets ``maxPoolSize`` to ``150`` when creating a new ``MongoClient``:
.. code-block:: js
const client = new MongoClient(uri, { maxPoolSize: 150 });
.. tip::
To learn more about connection pooling, see the :ref:`How Does Connection
Pooling Work in the Node Driver? <node-faq-connection-pool>` FAQ entry.
How Can I Ensure my Connection String Is Valid for a Replica Set?
-----------------------------------------------------------------
The connection string passed to the driver must use exact hostnames for
the servers as set in the :manual:`Replica Set Config </reference/replica-configuration/>`.
Given the following configuration settings for your Replica Set, in
order for the Replica Set discovery and :manual:`failover
</reference/glossary/#term-failover>` to work, the driver must have access
to ``server1``, ``server2``, and ``server3``.
.. code-block:: JSON
{
"_id": "testSet",
"version": 1,
"protocolVersion": 1,
"members": [
{
"_id": 1,
"host": "server1:31000"
},
{
"_id": 2,
"host": "server2:31001"
},
{
"_id": 3,
"host": "server3:31002"
}
]
}
If you are unable to find the answer to your question here, try our forums and
support channels listed in the :doc:`Issues and Help <issues-and-help>`
section.