DEV Community

Cover image for Connection Pools in a Nutshell
Polly Sutcliffe
Polly Sutcliffe

Posted on

Connection Pools in a Nutshell

A short overview of what connections pools are and why they're important.


If you work with databases in any way, it won't be long before you encounter documentation about the connection pool. It will likely be one of the options in the config object you pass when connecting to the database from your server.

Connections?

When you connect to a database, you open a connection -- a channel through which the server can request data and the database and send back that data. Each time you open a connection, you add another connection.

Databases can only handle so many simultaneous connections. If you misconfigure your server and open a new connection each time you want to get information from the database, you could end up opening thousands of connections and crashing your database. This is obviously very undesirable in a production environment.

We can set up a connection pool to prevent this kind of situation.

Connection Pools

Let's say you set the connection pool to 10. This will prevent the server from opening more than 10 connections simultaneously. When the server first starts, it will open 10 connections to the database that then sit and wait for requests. Each new request from the server will go through one of these ready-and-waiting connections.

If the 10 connections are already busy with requests, any further requests from the server will get queued until one of the existing pool of connections finishes its previous task and becomes free. This stops the database from being overwhelmed and helps to increase performance because you aren't opening and closing connections for each request -- instead, the 10 connections in the initial pool remain open as long as the server is running. Opening and closing database connections is fairly resource-intensive, so it's important to remember to set a connection pool limit whenever you work with a database.

How Many Connections?

Deciding on how many connections to limit the pool to is a question of fine tuning. Usually, you'll set a number to start with, then look at how your database and app are performing, and adjust accordingly. If pages aren't loading quickly enough, you likely need more connections in the pool, but you'll also need to watch for performance issues on the database side once you increase the pool. If the database isn't performing fast enough, you may need to upgrade your database service.

Top comments (0)