Skip to content

DOCSP-48388 break up faq #1048

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Mar 31, 2025
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions config/redirects
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ raw: ${prefix}/stable -> ${base}/current/
[*-master]: ${prefix}/${version}/fundamentals/versioned-api/ -> ${base}/${version}/fundamentals/stable-api/
[*-master]: ${prefix}/${version}/fundamentals/connection/lambda/ -> ${base}/${version}/fundamentals/connection/
[*-master]: ${prefix}/${version}/fundamentals/csfle -> ${base}/${version}/fundamentals/encrypt-fields/
[*-master]: ${prefix}/${version}/faq/ -> ${base}/${version}/

[*-v5.0]: ${prefix}/${version}/quick-start/connect-to-mongodb/ -> ${base}/${version}/quick-start/
[*-v5.0]: ${prefix}/${version}/quick-start/create-a-connection-string/ -> ${base}/${version}/quick-start/
Expand Down
117 changes: 113 additions & 4 deletions source/connect/connection-options.txt
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,9 @@ string, see :manual:`Connection Strings </reference/connection-string/>` in the
* - **connectTimeoutMS**
- non-negative integer
- ``30000``
- Specifies the amount of time, in milliseconds, to wait to establish a single TCP
- Specifies the amount of time in milliseconds to wait to establish a single TCP
socket connection to the server before raising an error. Specifying
``0`` disables the connection timeout.
``0`` means your application will use the operating system's default socket timeout value.

* - **directConnection**
- boolean
Expand Down Expand Up @@ -255,8 +255,9 @@ string, see :manual:`Connection Strings </reference/connection-string/>` in the
* - **socketTimeoutMS**
- non-negative integer
- ``0``
- Specifies the amount of time, in milliseconds, spent attempting to send or receive on a
socket before timing out. Specifying ``0`` means no timeout.
- Specifies the amount of time in milliseconds spent attempting to send or receive
on a socket before timing out. Specifying ``0`` means your application will use the
operating system's default socket timeout value.

* - **srvMaxHosts**
- non-negative integer
Expand Down Expand Up @@ -343,6 +344,114 @@ string, see :manual:`Connection Strings </reference/connection-string/>` in the
no compression, ``1`` signifies the fastest speed, and ``9`` signifies
the best compression. See :ref:`node-network-compression` for more information.

Connection Time Out Options
---------------------------

.. 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);

Close Sockets After Connection
------------------------------

If you experience unexpected network behavior or if a MongoDB process
fails with an error, you may not receive confirmation that the
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
fails with an error, you may not receive confirmation that the
fails with an error, you might 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.

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:

keepAlive Connection Option
---------------------------

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.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
to your MongoDB deployment. This functionality only works if your
operating system supports the ``SO_KEEPALIVE`` socket option.
to your MongoDB deployment. This functionality works only 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.

Additional Information
----------------------

Expand Down
113 changes: 112 additions & 1 deletion source/connect/connection-options/connection-pools.txt
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,115 @@ gets a connection from the pool, performs operations, and returns the connection
to the pool for reuse.

Connection pools help reduce application latency and the number of times new connections
are created by {+driver-short+}.
are created by {+driver-short+}.

.. _node-faq-connection-pool:

Connection Pool Overview
Comment on lines +34 to +35
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems out of scope for the ticket this PR applies to, but I think it would be worth creating a ticket to clean this page up a bit. This Connection Pool Overview section is very long and would probably benefit from being broken up into sections now that it's in its own page instead of an FAQ.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good idea, made a ticket here: https://jira.mongodb.org/browse/DOCSP-48683

-------------------------

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.

Avoid Socket Timeouts
---------------------

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>,
});
Loading
Loading