Connection Pooling
Reuse a bounded set of database connections so your app stays fast and the database does not drown in connections.
Intermediate · about 3 hours · difficulty 3/5
Learn first: ORMs and Query Builders, Transactions, ACID and Isolation
Opening a database connection is expensive: TCP handshake, TLS, authentication and, in PostgreSQL, a whole backend process per connection. Doing it per request adds latency, and letting every app instance open hundreds of connections can exhaust the database.
Application-side pools
Nearly every driver and ORM has a pool (pg.Pool, Prisma's pool, SQLAlchemy's engine pool, HikariCP in Java). The pool keeps a few open connections, lends one to each query or transaction and takes it back afterwards. Key settings:
- Max size: total connections this process may hold. The whole fleet's total must stay below the database's limit.
- Idle timeout and max lifetime so stale connections get recycled.
- Acquire timeout so requests fail fast instead of hanging when the pool is exhausted.
External poolers
When you run many instances or serverless functions, each with its own pool, use a proxy pooler such as PgBouncer, RDS Proxy or Supavisor. In transaction pooling mode it multiplexes thousands of client connections onto a few dozen real ones, with caveats: session-level features like some prepared statements or SET commands may behave differently.
Sizing intuition
More connections is not faster. A database with 8 cores often performs best with a few dozen active connections; beyond that they fight over CPU and locks. Measure instead of guessing.
Pitfalls
- Leaking connections by not releasing them on errors, until the pool is empty.
- Holding a connection while calling a slow external API inside a transaction.
- Serverless functions each opening fresh connections and overwhelming the database.
You are ready to move on when you can compute a safe pool size for your fleet, observe pool wait time under load, and explain transaction pooling.
Key concepts
- Why connections are expensive
- Pool size and timeouts
- Connection leaks
- PgBouncer and proxy poolers
- Session vs transaction pooling
- Serverless connection limits
Mini project
Load test an API with pool size 5, 20 and 100, graph latency and database CPU for each, and put PgBouncer in front to compare.
Check yourself
You have 20 app instances each with a pool of 20 and Postgres allows 200 connections. What goes wrong and how do you fix it?
Free resources
- PgBouncer (PgBouncer)
- HikariCP: About pool sizing (HikariCP)
- node-postgres: Pooling (node-postgres)