Programming
We provide developers and engineers the guides and tutorials they...
Search
We provide developers and engineers the guides and tutorials they...
Content is king. It's not just about how you're going to write, b...
Looking for an engaging connection with thousands of other people...
What connection pooling is, why opening database connections is slow, how to size a pool, PgBouncer pooling modes, and pitfalls like leaks and exhaustion.
Quick answer: Opening a database connection is slow and each open connection costs the database memory. A connection pool keeps a small set of connections open and lends them out: your code borrows one, runs its queries, and returns it for the next request to reuse. This removes the set-up cost from every request, caps the number of connections so the database is not overwhelmed, and lets hundreds of application threads share a few dozen connections. Without pooling, busy applications are slower and hit "too many connections" errors.
Creating a connection involves several steps before any query can run:
Together these take from a few milliseconds to tens of milliseconds, often longer than the query itself. Doing that on every web request wastes most of the request time.
Connections are also costly to keep. In PostgreSQL each one is a process using several megabytes of memory, and thousands of them cause heavy context switching. That is why databases set a max_connections limit, and why exceeding it gives the familiar "sorry, too many clients already" error.
Typical settings:
| Setting | Meaning |
|---|---|
| Maximum size | The most connections the pool will open |
| Minimum idle | Connections kept ready when traffic is quiet |
| Acquisition timeout | How long a caller waits for a free connection before failing |
| Idle timeout | When unused connections are closed |
| Maximum lifetime | When a connection is retired and replaced |
| Validation | A check that a connection is still alive before lending it |
The instinct is to make the pool large. That usually makes things worse.
A database server has a fixed number of CPU cores and a limited rate of disk I/O. If 200 queries run at once on 8 cores, they do not run faster. They compete, switching constantly and fighting over locks and caches. Total throughput goes down.
The HikariCP project's page About Pool Sizing makes this argument with benchmarks and suggests a starting point of roughly:
connections = (CPU cores × 2) + effective number of disks
For many systems that means a pool of perhaps 10 to 30 connections serving thousands of users. Requests queue briefly in the application, which is cheap, instead of piling into the database, which is not.
One more calculation matters: total connections across all application instances. A pool of 20 on each of 50 app servers is 1,000 connections. That total must stay under the database's limit, with room for admin and maintenance connections.
Most database libraries include a pool: HikariCP for Java, SQLAlchemy's pool for Python, database/sql in Go, pg.Pool for Node.js, and the pools built into Rails and Django. This is the simplest option and works well with a modest number of long-lived application processes.
When there are many application processes, or they come and go, a separate pooling proxy sits between applications and the database. Clients open cheap connections to the proxy, and the proxy multiplexes them over a small number of real database connections. PgBouncer is the classic example for PostgreSQL; ProxySQL does the same for MySQL, and cloud providers offer managed equivalents.
PgBouncer has three pooling modes, described on its features page:
| Mode | Connection is returned to the pool | Trade-off |
|---|---|---|
| Session | When the client disconnects | Fully compatible, least sharing |
| Transaction | At the end of each transaction | Much more sharing; session-level features do not carry over |
| Statement | After every statement | Maximum sharing; multi-statement transactions are not allowed |
Transaction mode is the most popular, because a connection is only tied up while a transaction is actually running. The catch is that features relying on session state, such as session variables, advisory locks and some uses of prepared statements, need care.
Serverless functions and aggressively autoscaled containers can create hundreds of instances in seconds, each opening its own connections. A traffic spike becomes a connection storm that knocks the database over.
The fixes:
More on that environment in what serverless really means.
finally block, or use a with / try-with-resources construct.A pool where callers regularly wait means the database is saturated or queries are too slow. It is a signal to investigate, not necessarily to raise the limit.
A cache of open database connections that application code borrows and returns, so connections are reused instead of being created for every request.
Start small, around twice the database's CPU core count, and measure. Bigger pools often reduce throughput.
The total connections opened by all clients exceeded the database's limit, commonly from many app instances each with a large pool, leaked connections, or a serverless traffic spike.
Not for a few long-lived app servers. It becomes valuable with many processes, serverless functions, or when total connections approach the database limit.
Connection pooling is a small piece of infrastructure with a large effect: it removes connection set-up from every request and protects the database from being flooded. Keep pools small, return connections promptly, add an external pooler when instances multiply, and treat a waiting queue as a clue about slow queries.