← Building blocks

Pool database connections

Latency & performancefundamental

Each request opens a new DB connection, which is slow and exhausts the server.

Say it like this

A new Postgres connection costs a TLS handshake and a forked backend, so each app instance keeps a small pool of warm connections and borrows one per query; the database sees a few hundred connections, not one per request.

Basic solution

Keep a pool of open connections per app instance and borrow one per request.

PgBouncerHikariCPRDS ProxyProxySQL

Client pools and a server-side pooler

Each instance borrows from its own small pool. PgBouncer multiplexes the 480 client connections across all instances onto about 40 real backends, which is what the database can actually use.

How it works

  1. At startup each application instance opens a fixed number of connections to the database (say 10), completing the TCP and TLS handshakes and authentication once, and keeps them idle in a pool.
  2. A request that needs the database borrows a connection from the pool, runs its queries on it, and returns it when done. The connection stays open and is reused by the next request; no handshake happens per request.
  3. If every connection is busy, the request waits in a queue for a bounded time, then fails fast with a clear error instead of opening more connections and overloading the database.
  4. The pool checks idle connections periodically and replaces any that the database has closed, so a request never borrows a dead connection.
  5. When there are many application instances, a server-side pooler (PgBouncer, RDS Proxy) sits between them and the database. It accepts thousands of client connections and multiplexes them onto a few hundred real database connections, handing a real connection to a client only while it is running a transaction.

What a connection costs without a pool

  • A TCP handshake, a TLS handshake, authentication, and in Postgres a forked backend process with its own memory. That is tens of milliseconds and a few MB per connection, paid again on every request.

Worked example

URL creation service on the shortener

  • 40 writes/s average, 400/s at peak, across 8 app instances. Each insert takes ~3 ms on the database.
  • Without a pool: 400 connections/s opened and closed; at ~30 ms per connect the connect time alone is 10× the query time, and connection churn consumes the database's CPU.
  • With a pool of 10 per instance: 80 connections total. Concurrent demand at peak is 400/s × 3 ms = 1.2 connections busy on average; 80 is ample and mostly idle.
  • The redirect service has 40 instances with pools of 10, so 400 more connections. Postgres default max_connections is 100 and each backend uses ~5–10 MB; 480 connections is too many and wasteful.
  • Fix: PgBouncer in transaction mode in front of the database. 480 client connections map onto ~40 server connections (enough for 40K reads/s × 1 ms = 40 busy). The database holds 40 backends instead of 480.

Variants and when each wins

Client-side pool per instance

  • A library inside the application (HikariCP, pgx pool, SQLAlchemy pool) keeps the connections. It wins for having no extra component; total connections grow with the number of instances.

Server-side pooler

  • PgBouncer, RDS Proxy or ProxySQL sits between the applications and the database and multiplexes many client connections onto a few server ones. It wins once instances × pool size approaches the database's limit; it adds a hop and, in transaction mode, forbids session state such as prepared statements and temp tables.

Transaction vs session pooling

  • Session mode binds a server connection to one client for the client's whole lifetime, which is safe but reuses little. Transaction mode hands a server connection to a client only for the duration of each transaction, which reuses heavily but breaks anything that expects the same connection across transactions. Statement mode reassigns per statement and is rarely safe.

Serverless connection brokers

  • For functions that start by the thousand, a broker (RDS Proxy, Neon's pooler) holds the real pool and each function keeps zero or one connection. It wins because it is the only way such clients can share a database at all.

Use a client pool in every instance, add a server-side pooler in transaction mode once instances × pool size approaches the database's limit, and size pools from measured concurrency, not guesses.

Failure modes

Pool exhaustion

  • Requests time out waiting for a connection while the database itself is idle. It happens because a slow query or a connection that was never returned is holding the pool's connections, or the pool is smaller than the real concurrency. Always release connections in a finally block, set a statement timeout so a slow query cannot hold one forever, size the pool from concurrency × latency, and alert on pool wait time.

Database connection limit hit

  • New instances fail to start with a too-many-connections error. It happens because instances × pool size now exceeds the database's max_connections. Add a server-side pooler or shrink the per-instance pools, and keep a reserved superuser slot so operators can still log in.

Stale connections after a failover

  • Every query fails for a minute after the database fails over. It happens because the pooled connections still point at the old primary, which is gone. Validate connections on borrow, use a short TCP keepalive so dead connections are noticed, and have the pool reconnect on the first error.

Session state in transaction mode

  • Errors such as "prepared statement does not exist" or a wrong search_path appear at random. It happens because session-level state was set on one server connection and the next transaction ran on a different one. Disable server-side prepared statements, set state per transaction, or route those clients through session mode.

Too large a pool

  • The database gets slower as the pool gets bigger. It happens because hundreds of backends contend for CPU and locks, and throughput peaks at a few times the core count. Shrink the pools and let requests queue in the application rather than in the database.

Interviewer follow-ups

Answer out loud before you open each one.

How do you size a connection pool?

Start from concurrency: requests per second times average query time gives connections busy on average; add headroom for bursts. A common ceiling for the whole database is a small multiple of its core count, because more backends just contend. Then measure pool wait time and adjust.

When do you need PgBouncer or RDS Proxy on top of client pools?

When instances multiplied by pool size approaches the database limit, or when clients are short-lived such as serverless functions. The pooler multiplexes thousands of client connections onto a few hundred real ones.

What breaks in transaction pooling mode?

Anything that assumes the same server connection across transactions: server-side prepared statements, session variables, temporary tables, advisory locks held across transactions, LISTEN/NOTIFY. Either avoid them or route those clients through session mode.

What happens to the pool during a database failover?

Existing connections point at the old primary and fail. The pool must detect errors, discard the connection, and reconnect through the endpoint that now resolves to the new primary. Validation on borrow and short timeouts make this a few seconds rather than minutes.

Connections

Built on
LRU cache: hash map + doubly linked list
Pairs with
Never wait forever · Batch small operations · Spread reads across replicas · Spread traffic across servers · Survive losing a node
Pulls against
Scale out, not up

The same parts on other clouds

The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon EC2 Auto ScalingRedirect instance 1, Redirect instance N, Creation instance, PgBouncerCompute Engine managed instance groupsVirtual Machine Scale SetsKubernetes Deployment with a HorizontalPodAutoscaler, Nomad
Amazon AuroraPostgresAlloyDB for PostgreSQL, Cloud SQLAzure Database for PostgreSQL or MySQLPostgreSQL, MySQL, CockroachDB