Course contents

04. Database Fundamentals Lesson 9 of 10

Connection Pooling

See why connections are pooled, how pool wait and pool timeouts show up in latency, why bigger pools hurt, how pools multiply with scale-out, and what PgBouncer does.

15 minIntermediate8 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • A new connection costs handshakes, authentication and (in Postgres) a server process; pools reuse connections.
  • When every connection is busy, requests wait; that wait is latency, and past capacity it becomes pool timeouts.
  • More active connections than the database can work on add contention, not capacity.
  • Total connections = instances × pool size, so scaling the app tier scales the load on the database.
  • A pooler like PgBouncer lets many client connections share a few server connections; size it with Little’s law.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

A connection pool keeps a set of open database connections and lends them to requests: a request borrows a connection, runs its queries and gives it back. Pools live inside the application (HikariCP, the pools built into Npgsql, psycopg, node-postgres, SQLAlchemy and others) or in a separate pooler process in front of the database (PgBouncer, PgCat, Odyssey, managed proxies such as RDS Proxy).

Why it exists

Opening a connection is expensive. For Postgres it means a TCP handshake, usually a TLS handshake, an authentication exchange (SCRAM-SHA-256 takes two round trips) and the server forking a new backend process with its own memory. Doing that per request adds milliseconds of latency and burns database CPU on process management. On the other side, every open connection costs the database memory, and active ones compete for CPU, locks and I/O, so the number of connections has to be controlled, not just made cheap.

How it works

Borrow and return. The pool opens connections up front or on demand up to a maximum size. A request that finds all connections busy waits in the pool's queue; if it waits longer than the acquire timeout (connectionTimeout in HikariCP, Timeout in Npgsql), it fails. Connections are validated, recycled after a maximum lifetime, and closed when idle too long.

Capacity. A pool of N connections holding each for t seconds can serve at most N ÷ t requests per second. Near that limit, waiting time grows quickly (queueing); past it, the wait grows until requests time out. The wait does not show up in the database's query statistics, only in the application's latency.

The database's limit. A database works best with a limited number of active queries, roughly a small multiple of its CPU cores, more when queries spend most of their time waiting on disk or locks. Beyond that, extra concurrency adds context switching, lock contention and cache pressure: each query gets slower and total throughput can fall.

Multiplication. Pools are per process. With k instances of a service, each with a pool of n, the database sees up to k × n connections, plus those of every other service. Postgres refuses connections beyond max_connections (100 by default) with "sorry, too many clients already".

Poolers. PgBouncer accepts many cheap client connections and multiplexes them onto a small number of server connections per database and user (default_pool_size). Modes: session (a server connection per client session; little gain), transaction (a server connection only for the duration of a transaction; the common choice) and statement (per statement; no multi-statement transactions). Transaction mode breaks features that rely on session state: session-level SET, session advisory locks, LISTEN, WITH HOLD cursors, temporary tables kept across transactions. Protocol-level prepared statements are supported in transaction mode since PgBouncer 1.21 (max_prepared_statements).

When to use it

  • Always use an application-side pool for a database that speaks a connection-oriented protocol.
  • Add a pooler when the number of application processes is large or variable (autoscaling, many services, serverless functions, short-lived jobs), or when connection storms on deploys hurt the database.
  • Use a managed proxy when the platform provides one and its limits fit (connection pinning rules, added latency).

When not to

  • Do not size pools "big for safety": a pool larger than the database's useful concurrency only moves queueing into the database, where it is more expensive.
  • Do not put session-dependent workloads (LISTEN/NOTIFY listeners, session advisory locks, long-lived cursors) behind a transaction-mode pooler; give them a direct connection or a session-mode pool.
  • Very low-traffic scripts and admin tools can connect directly.

Trade-offs

Choice You gain You pay
Small pool Low contention in the database, predictable latency Requests queue in the app at peaks
Large pool Fewer app-side waits at low load Contention, memory per connection, collapse under overload
Short acquire timeout Overload fails fast, threads freed More visible errors at peaks
PgBouncer in transaction mode Many clients on few server connections Another hop and component; session features restricted
Per-service pools without a pooler Simple Totals grow with instances and services; max_connections limits scale-out

Alternatives

  • Fewer, cheaper queries (see Query Performance): shorter hold times raise pool capacity more than extra connections do.
  • HTTP-based data APIs for serverless environments, where the provider pools behind the API.
  • Read replicas to spread read concurrency over more servers, each with its own pool limit.
  • Queues to smooth bursts of write work into a steady rate the pool can handle.

Failure modes

  • Pool exhaustion: slow queries, long transactions or a slow external call inside a transaction hold connections; everything else waits and times out.
  • Oversized pools amplifying overload: the database thrashes, every query slows, timeouts and retries add more load.
  • Connection storms: after a deploy or failover, every instance opens its pool at once.
  • Scale-out hitting max_connections: new instances fail to start or fail every request.
  • Leaked connections: code paths that never return a connection slowly drain the pool (use leak detection).
  • Stale connections through firewalls or load balancers that drop idle TCP sessions; use keepalives and a maximum lifetime shorter than the idle timeout.

In production

Size the total, not the instance: decide how many active queries the database should run, then divide among instances and services, or put a pooler in front. Measure and alert on pool wait time and pool utilisation, not just query time. Set an acquire timeout below the request timeout. Keep transactions short so connections return quickly. Reserve connections for administration (superuser_reserved_connections, or a separate role limit) so you can still log in during an incident. Run PgBouncer redundantly and monitor its SHOW POOLS waiting clients.

Common misconceptions

  • "More connections means more throughput." Only up to what the database can run in parallel; then it reverses.
  • "Pool timeouts mean the network is broken." They mean demand exceeded what the connections can finish.
  • "Pool size is per database." It is per process; the database sees the sum.
  • "PgBouncer makes queries faster." It makes connections cheaper and limits concurrency; the queries cost the same.

Interview angle

When a design puts many stateless instances in front of one relational database, interviewers expect you to bring up connection limits: instances × pool size against max_connections, a pooler such as PgBouncer or a managed proxy, and pool sizing from throughput × query time. Mention that pool wait is part of latency and that the cure for exhausted pools is usually shorter queries and transactions, not bigger pools.

Model assumptions

Simulated, not a benchmark. The engine models one pool per database node: its size is the total number of queries the database runs at once (the sum of every instance's pool), waiting for a free connection counts toward latency, and waiting more than 500 ms fails the request. Per-instance pools, max_connections refusals and connection setup are not modelled separately; setup appears as an extra ~25 ms of database time per request, and its handshake packets are a scripted close-up. Contention is a cost model set by hand: about 40 ms per request's database work with up to ~24 active connections, about 120 ms at 60 and 250 ms at 100 (illustrative); the engine does not derive it. PgBouncer is modelled as a server with 24 workers, each held while its query runs, like transaction pooling. Arrivals are random (Poisson), durations lognormal.

The lesson as textEvery step of the simulation, written out.
  1. 1. A new connection for every request

    Two app instances serve 300 requests per second, and each request opens its own connection to Postgres. A new connection is expensive: a TCP handshake, a TLS handshake, SCRAM authentication (two more round trips), and Postgres starts a new backend process for it. Only then is the query sent.

    The slowed-down packets on App 1 are a scripted close-up of that setup; the live traffic is simulated. In this model setup adds about 25 ms to the 40 ms of real database work, so every request pays it, and the database burns CPU on process start-up instead of queries.

    Scene: Users send 300 requests per second through a load balancer to two app instances. Each request opens a new Postgres connection (handshakes and authentication) before its query, so database time per request is about 65 ms.

    Key idea: Opening a database connection costs several round trips and a server process. Paying it per request wastes time on both sides.

  2. 2. Keep connections open and reuse them

    Each app instance now keeps a pool of 10 open connections (HikariCP, the Npgsql or psycopg pool, and so on). A request borrows a connection, runs its query and returns it; the next request reuses it. No handshakes, no new processes.

    Database time per request drops from ~65 ms to the 40 ms of actual work, and P50 falls with it. Postgres sees a steady 20 connections (2 instances × 10) instead of a churn of short-lived ones.

    Scene: Each app instance keeps 10 open connections and reuses them. Queries go straight to the database; database time per request drops to about 40 ms and latency falls.

    Key idea: A pool pays the connection cost once and reuses the connection for thousands of queries.

  3. 3. When all connections are busy, requests wait

    One second in, traffic rises to 480 requests per second. Twenty connections at 40 ms each can finish about 500 queries per second, so the pool is now busy about 95% of the time.

    The query itself still takes 40 ms. But a request that finds every connection in use has to wait for one, and that wait is part of its latency. Watch the waiting count on the database and P95: latency rises while the database is no slower at all.

    Scene: Traffic rises to 480 requests per second. The 20 connections are busy about 95% of the time, requests wait for a free one and P95 latency rises although each query still takes 40 ms.

    Key idea: Pool wait is invisible in database metrics but fully visible to users: it is queueing in front of the database.

  4. 4. Past capacity, waits turn into errors

    Traffic reaches 600 requests per second, more than the 500 the pool can serve. The line of waiting requests grows until waits pass the pool’s acquire timeout (500 ms here, connectionTimeout in HikariCP), and those requests fail.

    The errors say “timeout acquiring connection”, which tempts teams to blame the network or to make the pool bigger. The real limit is how much work the database can do per second.

    Scene: At 600 requests per second the pool is saturated: requests queue for a connection and those waiting longer than 500 ms fail with a pool timeout.

    Key idea: A pool timeout means demand exceeded what the connections can finish, not that connections are broken.

  5. 5. A bigger pool makes it worse

    The obvious fix: raise each pool from 10 to 50, so Postgres now runs up to 100 queries at once. But the database server has a limited number of CPU cores, and its disks, memory and locks are shared. With five times as many active queries, they mostly wait for each other: each query now takes about 250 ms in this model (illustrative).

    The result: P50 jumps, the database completes fewer queries per second than before, and the errors grow. Each Postgres connection is also a process with its own memory, so idle-but-open connections cost RAM too.

    Scene: Each pool grows to 50, so the database runs up to 100 queries at once. Contention makes every query slower; fewer queries complete per second and more requests fail.

    Key idea: More connections than the database can actively work on adds contention, not capacity. Throughput falls and latency rises.

  6. 6. Every new instance brings its own pool

    Pools are back to 10 and traffic to 450. Then autoscaling adds instances for an unrelated CPU spike: 6 app instances × 10 = 60 connections. Nobody changed a pool setting, yet the database now runs up to 60 queries at once, each takes about 120 ms, and P50 more than doubles compared with the two pooled instances.

    Pools multiply with instances. At 10 instances they would ask for 100 connections, Postgres’s default max_connections, and further instances would be refused with “too many clients already”. Serverless functions make it worse: every function instance opens its own pool.

    Scene: Autoscaling grows the app tier to six instances, each with a 10-connection pool. The database runs up to 60 queries at once, each takes about 120 ms, and latency more than doubles.

    Key idea: Total connections = instances × pool size. Scaling the app tier silently scales the load on the database.

  7. 7. A connection pooler in front of Postgres

    Put PgBouncer (or a similar pooler such as PgCat, Odyssey or a managed RDS Proxy) between the apps and Postgres. The apps keep their pools, but those now hold cheap client connections to PgBouncer. PgBouncer keeps just 24 server connections to Postgres.

    In transaction pooling mode a server connection is lent to a client only for the length of one transaction, so 60 client connections share 24 server connections. Postgres runs at most 24 queries at once, each back to about 40 ms; excess requests wait briefly in PgBouncer instead of fighting inside the database. P50 drops back to the two-instance level, now with six instances.

    The catch: session state does not survive between transactions (SET, session advisory locks, LISTEN, temporary tables). Protocol-level prepared statements work in transaction mode since PgBouncer 1.21 (max_prepared_statements).

    Scene: PgBouncer sits between the six app instances and Postgres. The apps’ 60 client connections share 24 server connections in transaction pooling mode; the database runs at most 24 queries at once and latency drops.

    Key idea: A pooler decouples how many clients connect from how many queries the database runs at once.

  8. 8. How many connections?

    Start from Little’s law: busy connections ≈ queries per second × time per query. Here 450 × 40 ms ≈ 18, so 24 leaves headroom for bursts. The database itself sets the upper bound: active queries beyond a small multiple of its CPU cores (more if queries mostly wait on disk) only add contention. The HikariCP rule of thumb, cores × 2 + effective spindles, is a starting point to measure from, not a law.

    Size the total across instances, not per instance; use a pooler when instance counts vary or many services share one database; set an acquire timeout so overload fails fast; and watch pool wait time, not only query time.

    Scene: Six app instances reach Postgres through PgBouncer’s 24 server connections at 450 requests per second; latency is low and nothing fails.

    Key idea: Pool size ≈ throughput × query time, capped by what the database can run in parallel. Size the total, not one instance.