Module 3 · Database designLesson 31 of 886 minIntermediate

Connection pooling

Opening a database connection is slow and each one costs the database memory. A pool opens a few once and shares them.

Try it

With the pool off, watch requests wait for connections and the database start refusing. Turn the pool on and compare response times and errors.

Every time an app talks to a database it needs a connection. Opening one is surprisingly expensive:

  • a TCP handshake, often a TLS handshake,
  • authentication,
  • the database setting up memory (in PostgreSQL, a whole process) for it.

That can take tens of milliseconds, sometimes more than the query itself. And databases can only hold a limited number of connections before they slow down or refuse more.

The pool

A connection pool opens a set number of connections when the app starts and keeps them open:

  1. A request borrows a connection from the pool.
  2. It runs its queries.
  3. It returns the connection for the next request.

If all connections are busy, new requests wait a moment in a queue instead of opening more.

Sizing it

Bigger isn't better. A database with 8 CPU cores can only truly work on a few queries at once; 500 connections just fight over the same cores and memory. A common starting point is a small pool per app server, then measure.

Remember the total: app servers x pool size must fit what the database can take.

External poolers

When you have many app servers, or serverless functions that start and stop constantly, a shared pooler like PgBouncer or RDS Proxy sits in front of the database. Thousands of clients connect to it, and it multiplexes them over a small number of real database connections.

Symptoms of pool trouble

  • Requests waiting a long time to acquire a connection: pool too small, or queries too slow.
  • "Too many connections" errors: total pools too big.
  • Connections leaking: code that borrows but never returns. Always return connections in a finally.

Quick check

You scale from 5 to 50 app servers, each with a pool of 20 connections. What might break?