Docs Menu
Docs Home
/ / /
PyMongo
/

Connection Pools

On this page

  • Overview
  • Configuring Connection Pools
  • Additional Information
  • API Documentation

In this guide, you can learn about how PyMongo 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 PyMongo. When your application requests a connection to MongoDB, PyMongo 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 PyMongo.

You can specify the following connection pool settings in your MongoClient object or in your connection URI:

Setting
Description

connectTimeoutMS

Sets the time that PyMongo waits when connecting a new socket before timing out.
Defaults to 20000

maxConnecting

Sets the maximum number of connections that each pool can establish concurrently. If this limit is reached, further requests wait until a connection is established or another in-use connection is checked back into the pool.
Defaults to 2

maxIdleTimeMS

Sets the maximum time that a connection can remain idle in the pool.
Defaults to None (no limit)

maxPoolSize

Sets the maximum number of concurrent connections that the pool maintains. If the maximum pool size is reached, further requests wait until a connection becomes available.
Defaults to 100

minPoolSize

Sets the minimum number of concurrent connections that the pool maintains. If the number of open connections falls below this value due to network errors, PyMongo attempts to create new connections to maintain this minimum.
Defaults to 0

socketTimeoutMS

Sets the length of time that PyMongo waits for a response from the server before timing out.
Defaults to None (no timeout)

waitQueueTimeoutMS

Sets how long a thread waits for a connection to become available in the connection pool before timing out.
Defaults to None (no timeout)

The following code creates a client with a maximum connection pool size of 50 by using the maxPoolSize parameter:

client = MongoClient(host, port, maxPoolSize=50)

The following code creates a client with the same configuration as the preceding example, but uses a connection URI:

client = MongoClient("mongodb://<host>:<port>/?maxPoolSize=50")

To learn more about connection pools, see Connection Pool Overview in the MongoDB Server manual.

To learn more about any of the methods or types discussed in this guide, see the following API documentation:

Back

Limit Server Execution Time