Deep Dive into Connection Pooling

As your application grows in functionality and/or usage, managing resources becomes increasingly important. Failure to properly utilize connection pooling is one major “gotcha” that we’ve seen greatly impact MongoDB performance and trip up developers of all levels.

Connection pools

Creating new authenticated connections to the database is expensive. So, instead of creating and destroying connections for each request to the database, you want to re-use existing connections as much as possible. This is where connection pooling comes in.

A Connection Pool is a cache of database connections maintained by your driver so that connections can be re-used when new connections to the database are required. When properly used, connection pools allow you to minimize the frequency and number of new connections to your database.

Connection churn

Used improperly however, or not at all, your application will likely open and close new database connections too often, resulting in what we call “connection churn”. In a high-throughput application this can result in a constant flood of new connection requests to your database which will adversely affect the performance of your database and your application.

Opening too many connections

Alternately, although less common, is the problem of creating too many MongoClient objects that are never closed.  In this case, instead of churn, you get a steady increase in the number of connections to your database such that you have tens of thousands of connections open when you application could almost certainly due with far fewer. Since each connection takes RAM, you may find yourself wasting a good portion of your memory on connections which will also adversely affect your application’s performance.

Although every application is different and the total number of connections to your database will greatly depend on how many client processes or application servers are connected, in our experience, any connection count greater than 1000 – 1500 connections should raise an eyebrow, and most of the time your application will require far fewer than that.

MongoClient and connection pooling

Most MongoDB language drivers implement the MongoClient class which, if used properly, will handle connection pooling for you automatically.

The syntax differs per language, but often you do something like this to create a new connection-pool-enabled client to your database:

mongoClient = new MongoClient(URI, connectionOptions);

Here the mongoClient object holds your connection pool, and will give your app connections as needed. You should strive to create this object once as your application initializes and re-use this object throughout your application to talk to your database. The most common connection pooling problem we see results from applications that create a MongoClient object way too often, sometimes on each database request. If you do this you will not be using your connection pool as each MongoClient object maintains a separate pool that is not being reused by your application.

Example with Node.js

Let’s look at a concrete example using the Node.js driver.

Creating new connections to the database using the Node.js driver is done like this:

The syntax for using MongoClient is slightly different here than with other drivers given Node’s single-threaded nature, but the concept is the same. You only want to call ‘connect’ once during your apps initialization phase vs. on each database request.

Let’s take a closer look at the difference between doing the right thing vs. doing the wrong thing.

Note: If you clone the repo from here, the logger will output your logs in your console so you can follow along.

Consider the following examples:

The first (no pooling):

  • calls connect() in every request handler
  • establishes new connections for every request (connection churn)
  • initializes the app (app.listen()) before database connections are made

The second (with pooling):

  • calls connect() once
  • reuses the database/collection variable (reuses existing connections) waits to initialize the app until after the database connection is established

If you run the first example and refresh your browser enough times, you’ll quickly see that your MongoDB has a hard time handling the flood of connections and will terminate.

Further consideration – connection pool size

Most MongoDB drivers support a parameter that sets the max number of connections (pool size) available to your application. The connection pool size can be thought of as the max number of concurrent requests that your driver can service. The default pool size varies from driver to driver, e.g. for Node it is 5, whereas for Python it is 100. If you anticipate your application receiving many concurrent or long-running requests, we recommend increasing your pool size- adjust accordingly!

, , , , , ,

  • IamStalker

    Thank you it’s a real nice example, I will defently going to implement it in my web apps

    • Chris Chang

      Glad it helps, happy hacking!

  • http://www.chaim.com Chaim Krause

    My app.js file is starting to get crowded with all the routes. I want to modularize my routes and move them to files in a route directory. I haven’t figured out how to make the database connection available to the modules. How do you suggest I do that? Should I make a global variable or should I move the MongoClient code to a module and require it? Any suggestions would be appreciated.

    Thanks for the article.

    • Chris Chang

      Good question. Either works, as they both would ensure that you’re only creating one MongoClient. For a smaller app, you can get by with a global variable. For larger apps, you’ll want to modularize.

      Keep in mind to initialize the app after the database connection is created. We’ve seen users encounter unexpected behavior when their app first boots up and tries to query the database before the connection is ready.

      Thanks for reading!

  • Pingback: MongoDB driver tips & tricks: Mongoid 3

  • Pingback: mongo connection pooling | wolfhesse

  • Luke Boehning

    Thanks for straightening this out for me. I had copied and pasted the connection examples from api at Mongo (http://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html#mongoclient-connect), where the connection is made once for each route. I sent about 1000 post messages to a route and my Express app bogged down to a crawl. Finally, Mongo sent a message back to Node letting me it hand “ended the connection”. After hours of digging, I found this post.

    Would somebody correct that horrible example at #mongoclient-connect?

    • Chris Chang

      Glad to hear this post helped, Luke. I’ll try to get in contact with some folks from the MongoDB team and see if we can replace that code.

      Cheers!