Skip to content

DOCSP-47031 Connection Pools #620

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 17 commits into from
Mar 5, 2025
1 change: 1 addition & 0 deletions source/connection.txt
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ Connection Guide
Connection Options </connection/connection-options>
MongoClient Settings </connection/mongoclientsettings>
Stable API </connection/stable-api>
Connection Pools </connection/connection-pools>
Network Compression </connection/network-compression>
JNDI Datasource </connection/jndi>
Connection Troubleshooting </connection/connection-troubleshooting>
Expand Down
165 changes: 165 additions & 0 deletions source/connection/connection-pools.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
.. _java-connection-pools:

================
Connection Pools
================

.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol

.. facet::
:name: genre
:values: reference

Overview
--------

In this guide, you can learn about how {+driver-short+} uses connection pools to manage
connections to a MongoDB deployment and how you can configure connection pool settings
in your application.

A connection pool is a cache of open database connections maintained by {+driver-short+}.
When your application requests a connection to MongoDB, {+driver-short+} seamlessly
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+}.

Create a Connection Pool
------------------------

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 MongoDB operations in your multi-threaded application.

The ``maxPoolSize`` option sets the maximum size of each connection pool, 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.

Each ``MongoClient`` instance opens two additional sockets per server in your MongoDB

Check failure on line 44 in source/connection/connection-pools.txt

View workflow job for this annotation

GitHub Actions / TDBX Vale rules

[vale] reported by reviewdog 🐶 [MongoDB.ConciseTerms] 'more' is preferred over 'additional'. Raw Output: {"message": "[MongoDB.ConciseTerms] 'more' is preferred over 'additional'.", "location": {"path": "source/connection/connection-pools.txt", "range": {"start": {"line": 44, "column": 41}}}, "severity": "ERROR"}
topology for monitoring the server's state.

Configure a Connection Pool
---------------------------

You can specify settings for your connection pool using either a connection
string or by passing a ``MongoClientSettings`` object to the
``MongoClients.create()`` method.

The following code creates a client with a maximum connection pool size of ``50``
by using either a :guilabel:`Connection String` or :guilabel:`MongoClientSettings`
object:
Copy link
Contributor

Choose a reason for hiding this comment

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

I haven't seen :guilabel: used before? I guess it just bold the text?

Anyway, would make these links to the Connection Options and MongoClient Settings pages.

Copy link
Collaborator Author

@lindseymoore lindseymoore Feb 24, 2025

Choose a reason for hiding this comment

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

@rachel-mack Thanks for the below comments! The links to these pages can be found in the tabs. Since the links are now in a more content relevant place in the tabs, I think leaving without a link here is appropriate.

guilabel can be used when referring to UI components on the page (such as the tabs) or in the Atlas UI. Here are a few examples I've seen:

Updated the copy to specifically mention the tabs.


.. tabs::

.. tab:: Connection String
:tabid: uri

.. code-block:: java

ConnectionString connectionString = "mongodb://<host>:<port>/?maxPoolSize=50"
MongoClient mongoClient = MongoClients.create(connectionString)

.. tab:: MongoClientSettings
:tabid: MongoClient

.. literalinclude:: /includes/fundamentals/code-snippets/ConnectionPool.java
:start-after: begin MongoSettings
:end-before: end MongoSettings
:language: java
:dedent:

Connection Pool Settings
~~~~~~~~~~~~~~~~~~~~~~~~

The following are connection string settings you can use to configure your
connection pool:

.. list-table::
:widths: 25,75
:header-rows: 1

* - Setting
- Description

* - :urioption:`connectTimeoutMS`

- Specifies the maximum amount of time, in milliseconds, the Java driver
waits for a connection to open before timing out. A value of 0 instructs
the driver to never time out while waiting for a connection to open.

*Default:* ``10000`` (10 seconds)

* - :urioption:`maxConnecting`

- Maximum number of connections a pool may establish
concurrently.

.. include:: /includes/connection-pool/max-connecting-use-case.rst

*Default:* ``2``

* - :urioption:`maxIdleTimeMS`

- The maximum number of milliseconds that a connection can
remain idle in the pool before being removed and closed.

*Default:* ``0``

* - :urioption:`maxPoolSize`

- Maximum number of connections opened in the pool. When the
connection pool reaches the maximum number of connections, new
connections wait up until to the value of
:urioption:`waitQueueTimeoutMS`.

*Default:* ``100``

* - :urioption:`minPoolSize`

- Minimum number of connections opened in the pool.
The value of :urioption:`minPoolSize` must be less than
the value of :urioption:`maxPoolSize`.

*Default*: ``0``

* - :urioption:`socketTimeoutMS`

- Number of milliseconds to wait before timeout on a TCP
connection.

Do *not* use :urioption:`socketTimeoutMS` as a mechanism for
preventing long-running server operations.

Setting low socket timeouts may result in operations that error
before the server responds.

*Default*: ``0``, which means no timeout.

* - :urioption:`waitQueueTimeoutMS`

- Maximum wait time in milliseconds that a thread can wait for
a connection to become available. A value of ``0`` means there
is no limit.

*Default*: ``120000`` (120 seconds)

For more information on these connection string options, see the
:ref:`Connection Options <connection-options>`
guide.

For more information on configuring you connection pool by using a
``MongoClientSettings`` object see the Connection Pool Settings section
of the :ref:`<specify-mongoclient-settings>` guide.

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

For more information on using a connection pool, see the
:manual:`Connection Pool </administration/connection-pool-overview>`
documentation in the Server manual.
36 changes: 36 additions & 0 deletions source/includes/fundamentals/code-snippets/ConnectionPool.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import static java.util.concurrent.TimeUnit.*;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.connection.ClusterConnectionMode;
import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;

public class ConnectionPool {

public static void main(String[] args) {

System.out.println("MongoSettings:");
createMongoSettings();
System.out.println();

}

private static void createMongoSettings() {
try {
//begin MongoSettings
MongoClient mongoClient = MongoClients.create(
MongoClientSettings.builder().applyConnectionString(
new ConnectionString("<your connection string>"))
.applyToConnectionPoolSettings(builder ->
builder.maxSize(50))
.build());
//end MongoSettings
mongoClient.listDatabaseNames().forEach(n -> System.out.println(n));
mongoClient.close();
} finally {
System.out.print("---------------------------------------");
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ private static void createClusterSettings() {
MongoClient mongoClient = MongoClients.create(
MongoClientSettings.builder()
.applyToClusterSettings(builder ->
builder.mode(ClusterConnectionMode.SINGLE)
builder.mode(ClusterConnectionMode.SINGLE))
.build());
//end ClusterSettings
mongoClient.listDatabaseNames().forEach(n -> System.out.println(n));
Expand Down Expand Up @@ -109,7 +109,7 @@ private static void createConnectionPoolSettings() {
MongoClientSettings.builder().applyConnectionString(new ConnectionString("<your connection string>"))
.applyToConnectionPoolSettings(builder ->
builder.maxWaitTime(10, SECONDS)
.maxSize(200)
.maxSize(200))
.build());
//end ConnectionPoolSettings
mongoClient.listDatabaseNames().forEach(n -> System.out.println(n));
Expand Down
Loading