Connection Pooling
Opening a connection costs handshakes, authentication and a cold congestion window, so clients keep a pool of open ones and hand them out per request — HTTP pools hold stateless connections any request can use, database pools hold connections that carry session state, and both fail the same way when the pool runs dry.
You have not marked these as done yet. Read on anyway if they feel familiar; come back to them if something here does not land.
The problem
Why opening is expensive
Every new connection pays the costs from The Lifecycle of One HTTP Request: a The Three-Way Handshake (1 RTT), a The TLS Handshake (1–2 RTT plus asymmetric crypto), and a congestion window that starts at ~14 kB and must grow (Congestion Control: Protecting the Network). A database connection then adds its own protocol setup on top of the same transport: PostgreSQL’s startup message, SCRAM-SHA-256 authentication (two more round trips), parameter negotiation, and — because PostgreSQL forks a backend process per connection — several milliseconds of fork() and 5–10 MB of memory on the server (Creating Processes: fork, exec, wait). MySQL uses a thread per connection; the cost is smaller but not zero. Then the application’s own setup: SET search_path, SET timezone, prepared statements, an ORM’s type introspection.
Measured on a 1 ms intra-datacentre link, a cold PostgreSQL connection with TLS costs on the order of 5–20 ms end to end; a query on a warm one costs 0.2 ms. Across a region boundary the connection costs hundreds of milliseconds. A handler that opens one per query is two orders of magnitude slower than it needs to be, and a fleet of such handlers exhausts the server’s connection limit (max_connections, default 100) long before it exhausts its CPU.
- HTTPS connection: 2–3 RTT + crypto before the first byte.
- PostgreSQL connection: those, plus auth round trips, plus a
fork()on the server, plus session setup. - Both start with a cold congestion window; a pooled connection is warm.
- Server-side limits are hard:
max_connections, file descriptors, memory per backend.
HTTP pools: stateless connections
An HTTP client pool is a set of open connections per origin (host + port + scheme). A request takes an idle one, or opens a new one up to a limit, or waits. Because HTTP requests carry all their context in headers, any request can use any connection to the same origin: the connection has no memory of the previous request. That makes HTTP pools simple — the only per-connection state is whether it is idle, and the only correctness concern is the idle-timeout race from Keep-Alive and Connection Reuse.
What differs is the defaults, and they bite. Node’s built-in http.Agent did not reuse connections until Node 19 made keepAlive: true the default; before that every fetch-style call from a service opened a new socket unless the code passed an agent. undici (the engine behind Node’s fetch) pools by origin with connections per pool. Python’s requests.get() creates and discards a session per call — no reuse at all — while requests.Session() (urllib3’s PoolManager, 10 connections per host by default) reuses. Go’s http.Transport reuses but keeps only MaxIdleConnsPerHost = 2 idle by default, so a burst of 50 concurrent calls opens 50 connections and closes 48 of them — visible as TIME_WAIT growth and wasted handshakes. Java’s HttpClient and Apache HttpClient pool; the JDK’s old HttpURLConnection does, but per-JVM with a small cap.
For HTTP/2 the pool is usually a single connection per origin carrying many streams, and the sizing question becomes the server’s SETTINGS_MAX_CONCURRENT_STREAMS and whether the client opens a second connection when it is reached (HTTP/2: Streams on One Connection).
1import { Agent, setGlobalDispatcher } from 'undici'2 3// one pooled dispatcher for the process; fetch() reuses connections per origin4setGlobalDispatcher(new Agent({5 connections: 32, // max sockets per origin — beyond this, requests queue6 keepAliveTimeout: 4_000, // must be BELOW the server's idle timeout (see keep-alive)7 pipelining: 1, // one in-flight request per h1 connection8}))9 10// every fetch to the same origin now shares warm connections11const res = await fetch('https://users.internal/users/42')Database pools: connections with state
A database connection is not interchangeable in the same way. It carries a session: an open transaction, SET variables, prepared statements, temporary tables, advisory locks, a cursor position. A pool must therefore hand a connection to exactly one caller at a time for the duration of a unit of work, and reset it on return — roll back any open transaction, DISCARD ALL or the equivalent — so the next borrower does not inherit a half-finished transaction or a search_path someone else set. Application-side pools (HikariCP in Java, pgx’s pool in Go, node-postgres Pool, SQLAlchemy’s QueuePool) do this per process.
A server-side pooler such as PgBouncer sits between many application processes and one database, multiplexing thousands of client connections onto a few dozen real backends. Its pooling mode determines what state it can preserve: session mode ties a backend to a client for the client’s lifetime (safe, little multiplexing); transaction mode assigns a backend only for the duration of a transaction (high multiplexing, but session-level features — SET, prepared statements by name, LISTEN, advisory locks held across transactions — break or need care); statement mode is for autocommit-only workloads. Choosing transaction mode without auditing the application for session state is a classic outage.
The distinction with HTTP is the important part: an HTTP connection is stateless per request and can be reused by anyone; a database connection is a stateful session that must be borrowed exclusively and cleaned. Treat them as different resources with different failure modes even though both are "a TCP socket kept open".
| HTTP client pool | Database connection pool | |
|---|---|---|
| Unit of borrowing | One request (or one stream on h2) | One transaction or unit of work, exclusively |
| State on the connection | None between requests | Transaction, session variables, prepared statements, locks |
| Reset on return | Not needed | Rollback + discard session state |
| Typical size | Tens per origin; bounded by server stream/connection limits | Small: roughly cores × 2 on the database side, shared by all app instances |
| Server-side cost per connection | A socket and buffers | A process (PostgreSQL) or thread (MySQL), memory, lock-table entries |
| Multiplexer | Reverse proxy / LB | PgBouncer, ProxySQL, RDS Proxy |
Sizing and exhaustion
Bigger is not better. A database does useful work on roughly as many connections as it has cores (plus a few waiting on I/O); beyond that, extra connections only add context switches, lock contention and memory. PostgreSQL’s own guidance and HikariCP’s well-known analysis both land near cores × 2 (+ disk spindles) for the *total* across every application instance — a 4-core database serving 20 app pods should not have 20 × 20 = 400 connections. Little’s law gives the demand side: connections needed ≈ request rate × time each holds a connection. 500 queries/s at 4 ms each need about 2 busy connections; if a query is slow at 400 ms, the same load needs 200, which is why one slow query drains a pool.
Pool exhaustion is the failure mode. When every connection is borrowed, the next request waits (a wait queue — Queue) until one is returned or a wait timeout fires: pool timeout, connection pool exhausted, SQLSTATE 53300 too many connections on the database side, ECONNREFUSED-looking stalls on the HTTP side. Causes are always one of: a leak (a handler that takes a connection and never releases it on an exception path), a slow consumer (one query or one downstream call holding connections for seconds), or fan-out (a request that needs three connections at once — nested transactions, parallel queries — so a pool of 10 deadlocks at four concurrent requests each holding two and waiting for a third). The symptom looks like the database is slow while the database is idle: the wait is in the application, in line for a connection.
- Database-side total ≈ cores × 2 (+ spindles); divide it across app instances, or put PgBouncer in front so the sum stays bounded.
- Little’s law: pool size ≈ rate × hold time. Reduce hold time (release before calling another service) before increasing size.
- Always set a borrow timeout; a request that waits forever for a connection is worse than a fast failure.
- Never borrow a second connection while holding one; it is the recipe for pool deadlock.
- Monitor: active, idle, waiting, and wait time — waiting > 0 for more than a moment is the early warning.
Key points
- A new connection costs TCP + TLS handshakes, a cold congestion window, and — for databases — authentication round trips, a server process or thread, and session setup.
- HTTP pools hold stateless connections any request may use; the defaults of the client library (Node < 19,
requests.get, Go’s 2 idle per host) decide whether reuse happens. - Database connections carry session state and must be borrowed exclusively per unit of work and reset on return; PgBouncer’s transaction mode trades session features for multiplexing.
- Size the database pool for the database (≈ cores × 2 total), not for the application’s concurrency; Little’s law relates size, rate and hold time.
- Exhaustion comes from leaks, slow holders or nested borrowing; the symptom is application-side waiting while the database looks idle.
- Set borrow timeouts and monitor waiters; never hold one connection while waiting for another.
Why does this exist?
Mechanisms are answers to constraints. Open each question before reading the answer.
▸Why not open a connection per request and rely on the OS?
Because the OS cannot skip the handshakes, and the database cannot skip the fork and the authentication. Only reuse avoids them, and reuse needs an owner that tracks which connections are idle — a pool.
▸Why is the ideal database pool so small?
A database is bound by cores and disk; connections beyond what those can service run in parallel only in the sense of contending for locks and CPU. Queuing requests in the application costs less than queuing them inside the database.
▸Why can an HTTP connection be shared freely but a database connection cannot?
HTTP puts all context in each request; the database keeps context on the connection (transaction, session settings). Sharing the latter between two callers would interleave their transactions.
▸Why does one slow query take down unrelated endpoints?
They share the pool. By Little’s law the slow query’s hold time multiplies its share of the pool; when it holds every connection, the fast queries wait in line behind it, and the whole service reports timeouts.
How it fails
What the failure looks like from inside real software.Reference · showHide
pool timeout/connection pool exhaustedwhile the database shows 10% CPU: a leak on an exception path, or one slow query holding all connections.- PostgreSQL
FATAL: sorry, too many clients alreadyafter a scale-out: every new pod brought its own full-size pool; the sum exceededmax_connections. - Switching PgBouncer to transaction mode breaks named prepared statements and
SETcalls; queries fail intermittently depending on which backend is assigned. - Go service opens hundreds of short-lived HTTPS connections under load because
MaxIdleConnsPerHostis 2; handshake CPU andTIME_WAITclimb. - Nested borrowing deadlock: each request holds a connection and requests a second; with N concurrent requests and N connections, nobody progresses until the borrow timeout.
- Stale pooled connections after a database failover: every borrowed connection fails on first use with a reset until the pool validates or recycles them.
Check yourself
Answer out loud or on paper first, then compare. These come from the interview questions linked to this lesson.
What does HTTP keep-alive do, what does it cost, and what goes wrong when a client and a server disagree about how long a connection stays open?
Show a strong answerHide the answer
Without reuse every request pays a TCP handshake (1 RTT), a TLS handshake (1–2 RTT) and a fresh slow start in which the first response is throttled to ~14 kB per RTT. With persistent connections — the HTTP/1.1 default,
Connection: keep-alivein 1.0 — the second request pays none of that: the socket is open, the keys exist, and the congestion window is already grown. On a 100 ms path that is 200–300 ms saved per request; for an API client making thousands of calls it is the difference between a busy pool of 20 connections and a stream ofTIME_WAITsockets and port exhaustion (Keep-Alive and Connection Reuse, Connection Pooling).The cost is state that outlives the request. Each idle connection holds a file descriptor, a kernel socket with its buffers, and on a TLS server tens of kilobytes of session state; a server holding 50 000 idle keep-alive connections must be sized for it (fd limits, memory) and its event loop or worker model must not tie a thread to an idle socket (The Event-Driven Server). So both ends impose an idle timeout: nginx defaults to 75 s toward clients, Node’s
http.Server.keepAliveTimeoutto 5 s, AWS ALB to 60 s, Go’shttp.Server.IdleTimeoutto whatever you set. HTTP/1.1’sKeep-Alive: timeout=5, max=100header is only a hint.The race is the classic failure. The server decides an idle connection is dead at exactly the moment the client picks it from the pool and writes a request. The client’s bytes meet a closed socket: it gets
ECONNRESET,EPIPE, "socket hang up" (Node) or "Connection reset by peer" for a request that was never processed — or, worse, was fully written and *may* have been processed before the close raced. A proxy between them turns the same event into a 502. The rule that avoids it: the client’s idle timeout must be shorter than the server’s, at every hop. The textbook incident is Node behind an ALB: ALB idle 60 s, Node default 5 s → intermittent 502s until Node is set tokeepAliveTimeout = 65 000(andheadersTimeoutabove it).This is unrelated to TCP keepalive (
Full interview question, with follow-ups and red flags →SO_KEEPALIVE): kernel probes on an idle connection, by default only after 2 hours (tcp_keepalive_time=7200), whose purpose is to detect a dead peer and to keep NAT and firewall entries from expiring. It does nothing for HTTP request semantics, and its default timing is far too long to matter for the race above.Requests to your API take 3 seconds at p99, but the server sits at 5% CPU and the handler itself measures 20 ms. Where can the other 2.98 seconds be, and how would you find them?
Show a strong answerHide the answer
The handler’s 20 ms is measured from the moment the framework calls it — a request has a long life before and after that point, and none of it burns CPU. Lay out the timeline (Where the Time Goes: The Request Timeline): client DNS lookup → TCP handshake → TLS handshake → request bytes cross the network → the kernel’s accept queue → the application’s own queue (thread pool, event loop) → the handler → response bytes written to the socket buffer → transferred to the client → parsed. "Idle CPU plus slow requests" means the request is *waiting*, and each stage has a characteristic wait.
Exact values are fingerprints. A p99 of ~1 s or ~3 s is the signature of a lost SYN: Linux retransmits at 1 s, then 3 s, then 7 s, so a handshake whose first SYN was dropped — by a full accept queue, a conntrack table at capacity, or a firewall — completes at exactly 1 or 3 s (The Three-Way Handshake, TCP Debugging: Reading the Handshake on the Wire). Check
nstat -az TcpExtListenOverflows TcpExtListenDropsandss -ltnfor Recv-Q at the backlog limit. Steps of ~200 ms or multiples are retransmission timeouts on established connections (RTO_MIN, Packet Loss: Duplicate ACKs, Fast Retransmit and the RTO); ~40 ms per small write is the Nagle + delayed-ACK interaction; exactly 5 s is the glibc DNS resolver timeout — the first nameserver inresolv.confis dead or drops UDP, or an AAAA lookup goes unanswered; 1–3 RTTs of extra latency on *every* request means no keep-alive, so each request re-runs the TCP and TLS handshakes (Keep-Alive and Connection Reuse).Queueing without CPU is the other big family. A thread pool of 32 workers all blocked on a downstream call with a 3 s timeout serves 20 ms handlers with a 3 s wait — the thread-pool queue length, not CPU, is the saturated resource (The Thread Pool Server). An event loop stalled on a synchronous call queues everything behind it. A slow client or a small socket buffer makes
write()fast (it copies into the kernel) but the *transfer* slow, so server-side timing ends before the client has received anything; the LB then reports a long response time the app never saw (What Happens When the Receiver Is Slow). And on the client side, browsers queue requests beyond six per host — DevTools shows that as "Stalled" — and a proxy in between may buffer.Find it by measuring each hop, not the handler. From a client:
Full interview question, with follow-ups and red flags →curl -w "%{time_namelookup} %{time_connect} %{time_appconnect} %{time_starttransfer} %{time_total}"splits DNS, TCP, TLS and time-to-first-byte. At the balancer: ALBrequest_processing_time/target_processing_time/response_processing_time, or nginx$request_timeversus$upstream_connect_time,$upstream_header_time,$upstream_response_time— the gap betweenrequest_timeandupstream_response_timeis client or network. On the server:ss -tiforretrans,rtoandcwndper connection, thread-pool and event-loop lag metrics, and a distributed-tracing span opened at the *ingress* rather than in the handler. Compare p50 to p99: a flat p50 with a spiky p99 at round values is a timer; a smeared p99 is a queue.A service behind nginx gets 502 "upstream prematurely closed connection" about once per thousand requests, only under low traffic. Why low traffic?
Show a strong answerHide the answer
Idle connections are the ones that time out; under load the pool is always busy. The upstream’s idle timeout is shorter than nginx’s; raise it above nginx’s or lower nginx’s.
Full interview question, with follow-ups and red flags →