diff --git a/config/redirects b/config/redirects index a02dfd519..f1008e6f8 100644 --- a/config/redirects +++ b/config/redirects @@ -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/ diff --git a/source/connect/connection-options.txt b/source/connect/connection-options.txt index 0f111900e..948957437 100644 --- a/source/connect/connection-options.txt +++ b/source/connect/connection-options.txt @@ -91,9 +91,9 @@ string, see :manual:`Connection Strings ` 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 sets an infinite socket timeout when establishing a socket. * - **directConnection** - boolean @@ -255,8 +255,9 @@ string, see :manual:`Connection Strings ` 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 sets an + infinite socket timeout when establishing a socket. * - **srvMaxHosts** - non-negative integer @@ -343,6 +344,114 @@ string, see :manual:`Connection Strings ` 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 + ` 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: , + socketTimeoutMS: + }); + +To see all the available settings, see the +`MongoClientOptions <{+api+}/interfaces/MongoClientOptions.html>`__ +API Documentation. + +To specify ``maxTimeMS``, pass in the ``maxTimeMS`` method as an option with a timeout +specification to an operation that returns a ``Cursor``: + +.. code-block:: javascript + + const Cursor = collection.distinct('my-key', { maxTimeMS: 50 }); + +Close Sockets After Connection +------------------------------ + +If you experience unexpected network behavior or if a MongoDB process +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 +` 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 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 ---------------------- diff --git a/source/connect/connection-options/connection-pools.txt b/source/connect/connection-options/connection-pools.txt index 2050239bf..97fa3533a 100644 --- a/source/connect/connection-options/connection-pools.txt +++ b/source/connect/connection-options/connection-pools.txt @@ -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+}. \ No newline at end of file +are created by {+driver-short+}. + +.. _node-faq-connection-pool: + +Connection Pool Overview +------------------------- + +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 ` 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(""); + +``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: , + }); \ No newline at end of file diff --git a/source/connect/connection-troubleshooting.txt b/source/connect/connection-troubleshooting.txt index 04f10c5c6..e81ace34a 100644 --- a/source/connect/connection-troubleshooting.txt +++ b/source/connect/connection-troubleshooting.txt @@ -25,8 +25,6 @@ using the {+driver-long+} to connect to a MongoDB deployment. This page addresses only connection issues. If you encounter any other issues with MongoDB or the driver, visit the following resources: - - The :ref:`Frequently Asked Questions (FAQ) ` for the - {+driver-short+} - The :ref:`Issues & Help ` page, which has information about reporting bugs, contributing to the driver, and finding more resources @@ -34,7 +32,7 @@ using the {+driver-long+} to connect to a MongoDB deployment. questions, discussions, or general technical support Connection Error -~~~~~~~~~~~~~~~~ +---------------- The following error message indicates that the driver cannot connect to a server on the specified hostname or port. Multiple situations can generate this error @@ -52,7 +50,7 @@ issue. .. _node-troubleshooting-connection-string-port: Check Your Connection String ----------------------------- +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Verify that the hostname and port number in the connection string are both accurate. The default port value for a MongoDB instance is @@ -61,7 +59,7 @@ accurate. The default port value for a MongoDB instance is .. _node-troubleshooting-connection-firewall: Configure Your Firewall ------------------------ +~~~~~~~~~~~~~~~~~~~~~~~ Verify that the ports your MongoDB deployment listens on are not blocked by a firewall on the same network. MongoDB uses port ``27017`` by default. To learn @@ -74,7 +72,7 @@ more about the default ports MongoDB uses and how to change them, see used by your MongoDB deployment. ECONNREFUSED Error -~~~~~~~~~~~~~~~~~~ +------------------ If the connection is refused when the driver attempts to connect to the MongoDB instance, it generates this error message: @@ -88,7 +86,7 @@ The following sections describe actions you can take to potentially resolve the issue. Ensure MongoDB and Your Client Use the Same Protocol ----------------------------------------------------- +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In Node.js v17 and later, the DNS resolver uses ``IPv6`` by default when both the client and host support both. For example, if MongoDB uses IPv4 and your @@ -111,7 +109,7 @@ specifying ``family: 4`` as an }); ECONNRESET Error -~~~~~~~~~~~~~~~~ +---------------- If the connection is reset when the driver calls ``client.connect()``, it generates this error message: @@ -124,7 +122,7 @@ generates this error message: The following section describes a method that may help resolve the issue. Control the Number of File Descriptors --------------------------------------- +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A file descriptor is a unique identifier associated with an open process. In most operating systems, each open connection from the driver is associated with a @@ -142,7 +140,7 @@ file descriptor limit in your operating system. Always be cautious when changing the configuration of your operating system. Authentication Error -~~~~~~~~~~~~~~~~~~~~ +-------------------- The {+driver-short+} can fail to connect to a MongoDB instance if the authorization is not configured correctly. If you are using ``SCRAM-SHA-256`` @@ -168,7 +166,7 @@ issue. .. _node-troubleshooting-connection-string-auth: Check Your Connection String ----------------------------- +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ An invalid connection string is the most common cause of authentication issues when attempting to connect to MongoDB using ``SCRAM-SHA-256``. @@ -202,7 +200,7 @@ This results in the following output: .. _node-troubleshooting-connection-admin: Verify the User Is in the Authentication Database -------------------------------------------------- +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ To successfully authenticate a connection by using a username and password with ``SCRAM-SHA-256``, the username must be defined in the authentication database. @@ -223,7 +221,7 @@ instance hosted on the local machine with the same code. A deployment on the same machine doesn't require any authorization to connect. Error Sending Message -~~~~~~~~~~~~~~~~~~~~~ +--------------------- When the driver fails to send a command after you make a request, it may display the following error message: @@ -237,7 +235,7 @@ The following sections describe actions you can take to potentially resolve the issue. Check the User Permissions --------------------------- +~~~~~~~~~~~~~~~~~~~~~~~~~~ Verify that you've accessed the MongoDB deployment with the correct user. The term "message" in the error can be a command sent by the driver. @@ -250,7 +248,7 @@ to a MongoDB deployment. For more information about how to configure RBAC in Mon see :manual:`Default MongoDB Port `. Configure Your Firewall ------------------------ +~~~~~~~~~~~~~~~~~~~~~~~ The firewall needs to have an open port for communicating with the MongoDB instance. For more information about configuring the firewall, see @@ -260,7 +258,7 @@ the Connection Error section. .. _node-troubleshooting-connection-number-connections: Check the Number of Connections -------------------------------- +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Each ``MongoClient`` instance supports a maximum number of concurrent open connections in its connection pool. You can configure the parameter ``maxPoolSize`` @@ -269,12 +267,12 @@ number of open connections equal to ``maxPoolSize``, the server waits until a connection becomes available. If this wait time exceeds the ``maxIdleTimeMS`` value, the driver responds with an error. -For more information about how connection pooling works, see -:ref:`How Does Connection Pooling Work in the Node Driver? ` -in the FAQ. +For more information about how connection pooling works, see the +:ref:`Connection Pool Overview ` +in the Connection Pools page. Too Many Open Connections -~~~~~~~~~~~~~~~~~~~~~~~~~ +------------------------- The driver creates the following error message when it attempts to open a connection, but it's reached the maximum number of connections: @@ -287,7 +285,7 @@ connection, but it's reached the maximum number of connections: The following section describes a method that may help resolve the issue. Check the Number of Connections -------------------------------- +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ To create more open connections, increase the value of ``maxPoolSize``. For more information about checking the number of connections, see @@ -295,7 +293,7 @@ information about checking the number of connections, see in the Error Sending Message section. Timeout Error -~~~~~~~~~~~~~ +------------- When the network is not able to deliver a request from the driver to the server quickly enough, it can time out. When this happens, you might receive an error message @@ -310,7 +308,7 @@ If you receive this error, try the following action to resolve the issue. Set connectTimeoutMS --------------------- +~~~~~~~~~~~~~~~~~~~~ The driver may hang when it's unable to establish a connection because it takes too long attempting to reach unreachable replica set nodes. You can limit the @@ -334,9 +332,73 @@ The following example sets ``connectTimeoutMS`` to 10000 milliseconds. }); Check the Number of Connections -------------------------------- +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The number of connections to the server may exceed ``maxPoolSize``. For more information about checking the number of connections, see :ref:`Check the Number of Connections ` in the Error Sending Message section. + +Client Disconnect While Running Operation +----------------------------------------- + +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. + +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:`keepAlive Connection Option + ` section in the Connection Options page. + +Connection String Errors for Replica Sets +----------------------------------------- + +The connection string passed to the driver must use exact hostnames for +the servers, as set in the :manual:`Replica Set Config `. +Given the following configuration settings for your replica set, in +order for the replica set discovery and :manual:`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" + } + ] + } \ No newline at end of file diff --git a/source/connect/mongoclient.txt b/source/connect/mongoclient.txt index ab63a2245..f1b27a261 100644 --- a/source/connect/mongoclient.txt +++ b/source/connect/mongoclient.txt @@ -119,7 +119,57 @@ verify that the connection is successful: Call the ``MongoClient.connect()`` method explicitly if you want to verify that the connection is successful. -To learn more about the {+stable-api+} feature, see the :ref:`{+stable-api+} page `. +To learn more about the {+stable-api+} feature, see the :ref:`{+stable-api+} page +`. + +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 another 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 ` + in the Server manual. +- Run the ``db.currentOp()`` MongoDB Shell command. To learn more, see the + :manual:`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 ` 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 ` 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:`Connection Pool Overview + ` section in the Connection Pools page. API Documentation ----------------- diff --git a/source/faq.txt b/source/faq.txt deleted file mode 100644 index 7467c93c3..000000000 --- a/source/faq.txt +++ /dev/null @@ -1,366 +0,0 @@ -.. _node-faq: - -=== -FAQ -=== - -.. 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 ` -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 ` 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(""); - -``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 - ` 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: , - socketTimeoutMS: - }); - -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: , - }); - -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 -` 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? ` 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 ` - in the Server manual. -- Run the ``db.currentOp()`` MongoDB Shell command. To learn more, see the - :manual:`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 ` 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 ` 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? ` 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 `. -Given the following configuration settings for your Replica Set, in -order for the Replica Set discovery and :manual:`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 ` -section.