Topic B6
Connection pools
Lending a few database connections in turn, instead of opening a new one per request.
Watch: three connections are shared in turn by six requests. Without a pool, each request opens a new one and some are refused.
- moving now
- being checked
- finished / the result
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()withoutrelease()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
What's the main benefit of a connection pool?
10 app servers, each with a pool of 15. The database's max_connections is 100. What happens under load?
The pool is exhausted and every request waits, though traffic is normal. Most likely cause?
0 of 3 answered.
Built on
Used in
No follow-up topics yet.