Backend Case Studies

Topic B6

Connection pools

Lending a few database connections in turn, instead of opening a new one per request.

9 min · intermediate

Watch: three connections are shared in turn by six requests. Without a pool, each request opens a new one and some are refused.

conn 1conn 2conn 3waitingdonepoolDB
  • moving now
  • being checked
  • finished / the result
Step 1 of 7

The pool holds 3 connections that are already open and shared in turn. Opening a new database connection needs a TCP handshake, TLS and a login: slow.

Database connections are expensive to open and limited in number. A pool opens them once and lends them out in turn.

Like taxis at an airport

Imagine every passenger had to buy a new car for one trip, then scrap it. Expensive and slow. At the airport, a fleet of taxis waits in a rank; passengers get in, get dropped off, the taxi comes back. If every taxi is out, the next passenger waits a little. A pool is that taxi rank.

Why connections are limited

In PostgreSQL every connection is its own process using memory (a few MB). The default max_connections is 100. More connections don't mean more speed either: the database has limited CPU and disk, so 500 queries running at once fight each other and all slow down. A short queue in front of a small number of connections usually gives higher throughput.

Code, for programmersA pool in Node.js with pg
import { Pool } from "pg";

const pool = new Pool({
  max: 10,                       // at most 10 open connections from this process
  idleTimeoutMillis: 30_000,     // close connections idle for 30 s
  connectionTimeoutMillis: 2_000 // give up if no connection frees up within 2 s
});

// every query borrows a connection and returns it automatically
const { rows } = await pool.query("SELECT * FROM users WHERE id = $1", [42]);

Common traps

  • Many servers, one database: 20 instances × a pool of 20 = 400 connections, but the database only allows 100. Count the total, not per server.
  • Serverless: every Lambda or Vercel function can open its own connection. Use an external pooler (PgBouncer, RDS Proxy, the Supabase pooler).
  • Connections never returned: pool.connect() without release() on the error path drains the pool slowly, until every request waits forever.
  • Long transactions: a connection held while calling another API or waiting on a user can't serve anyone else.

Quiz

  1. What's the main benefit of a connection pool?

  2. 10 app servers, each with a pool of 15. The database's max_connections is 100. What happens under load?

  3. The pool is exhausted and every request waits, though traffic is normal. Most likely cause?

0 of 3 answered.