Course contents

15. Performance Engineering Lesson 7 of 8

Connection Management

See what TCP and TLS handshakes cost, how keep-alive and pooling save latency and capacity, why idle timeouts must match, and how idle connections starve pools.

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

Summary

  • A new TCP + TLS 1.3 connection costs two round trips before the first request byte; far away, that is more than the call.
  • Setup time also holds the caller’s worker, so it eats capacity as well as latency (Little’s law).
  • Create clients once and reuse pooled keep-alive connections; HTTP/2 and gRPC multiplex requests over one connection.
  • The side that reuses a connection must close it before the other side’s idle timeout, or requests hit resets.
  • Idle connections occupy slots; bound idle time, recycle connections and give workloads separate pools.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

Connection management is everything a system does about the lifecycle of network connections: when to open them, how long to keep them, how many to allow, how to reuse them, and when and by whom they are closed. It applies at every hop: browser to edge, load balancer to backend, service to service, application to database or cache.

Why it exists

Connections are not free. Opening one costs round trips (TCP, TLS, sometimes authentication) and CPU (key exchange). Keeping one open costs memory and a slot on both ends: a file descriptor, kernel buffers, often a thread or, for Postgres, a whole backend process. Get it wrong and you pay in latency (handshakes on every call), in capacity (workers waiting on handshakes, slots held by idle connections) and in errors (requests sent on connections the other side just closed).

How it works

Setup cost. A TCP connection needs a handshake (SYN, SYN-ACK, ACK): one round trip before data can flow. TLS 1.3 adds one more round trip (TLS 1.2 added two). So a new HTTPS connection costs two round trips before the first request byte, plus the request’s own round trip. At 40 ms RTT that is 80 ms of setup for a call whose real work might be 15 ms. TLS session resumption and 0-RTT reduce this for repeat connections (0-RTT data can be replayed, so it is limited to safe requests); QUIC (HTTP/3) combines the transport and TLS handshakes into one round trip.

Reuse. HTTP/1.1 keeps connections open by default (keep-alive) but carries one request at a time per connection, so clients keep a pool of connections per destination. HTTP/2 and gRPC multiplex many concurrent requests over one connection. In both cases the setup is paid once and amortised over many requests, but only if the client object (and its pool) is created once and shared, not created per request.

Limits. Every server caps connections: web servers and proxies by configuration and file descriptors, databases by settings such as Postgres max_connections (default 100). Clients are limited too: each outgoing connection to the same destination uses an ephemeral port, and closed connections linger in TIME_WAIT on the side that closed first, so opening and closing connections at a high rate can exhaust ports.

Idle timeouts. Both ends close connections that stay idle too long, and they rarely agree on how long. If the server closes first while the client still considers the connection reusable, a request sent at that moment meets a closing socket and fails with a reset (or a 502 from a proxy). The fix is to make the reusing side (client pool, load balancer) close idle connections before the server does, and to retry idempotent requests once on a fresh connection.

Lifetime. Long-lived connections pin a client to the backend it first reached. After scaling out or a DNS change, old connections keep going to old backends. A maximum connection lifetime (and HTTP/2 GOAWAY on the server side) forces periodic reconnects, so load spreads to new instances.

When to use it

Always, on any path that makes repeated calls to the same destination: service-to-service HTTP and gRPC, database and cache clients, load balancer to backend. It matters most when round trips are long (cross-zone, cross-region, mobile), when TLS is used everywhere (service meshes, zero-trust networks), and when the server has a hard connection cap.

When not to

  • One-off or very rare calls, where an idle pool only holds resources.
  • Clients behind middleboxes that silently drop idle connections; there, shorter idle timeouts or TCP keepalive probes matter more than long reuse.
  • Huge numbers of mostly idle clients (IoT, push): use a server designed for many cheap connections (event-driven, not thread-per-connection) rather than relying on reuse.

Trade-offs

Choice You gain You pay
Long idle timeout on the client pool Fewer handshakes after quiet periods More idle slots held; risk of racing the server’s close
Short idle timeout Fewer idle connections, no stale sockets More handshakes and setup latency
Larger pool per destination Fewer waits for a connection More load and memory on the server; pools multiply with instances
HTTP/2 or gRPC multiplexing Many requests over one connection One connection pins to one backend; needs per-request balancing or a max lifetime
Maximum connection lifetime Picks up new backends and DNS changes Periodic reconnect cost

Alternatives

  • A pooler or proxy in the middle (PgBouncer for Postgres, a sidecar proxy in a service mesh): many cheap client connections share a few expensive server connections.
  • Multiplexing protocols (HTTP/2, HTTP/3, gRPC) instead of many HTTP/1.1 connections.
  • Event-driven servers (epoll/kqueue-based) that keep idle connections cheap compared with one thread per connection.
  • Asynchronous messaging, where producers keep one long-lived connection to a broker instead of calling each consumer.

Failure modes

  • Client per request: an HTTP or database client created inside the request handler opens a new connection every time; latency and CPU rise, and ports run out under load.
  • Idle-timeout race: intermittent resets or 502s after quiet periods, because the server closes idle connections before the client or balancer does.
  • Pool starvation by idle connections: a job or a leak holds connections without using them (idle in transaction in Postgres), others time out waiting, while the database is nearly idle.
  • Connection storms: after a restart or failover every client reconnects at once, and the handshake CPU load slows the server further. Jittered reconnects and backoff help.
  • Pinned connections: new instances get no traffic because existing long-lived connections stay on the old ones.

In production

Create HTTP and database clients once per process and share them. Set the client pool’s idle timeout below the server’s keep-alive timeout (for example 4 s against 5 s; behind a load balancer, the backend’s keep-alive above the balancer’s idle timeout). Give connections a maximum lifetime of minutes, not days. On databases, set an idle-in-transaction timeout and give batch jobs their own small pool. Monitor new connections per second, pool wait time and acquire timeouts, connections by state, TLS handshake rate and resets.

Common misconceptions

  • “Keep-alive is on, so connections are reused.” Only if the same client object is reused; a client created per request has its own empty pool.
  • “Handshakes only add latency.” They also hold the caller’s worker, thread or connection slot, which costs capacity.
  • “Idle connections are free.” They take memory and a slot from a fixed budget on the server.
  • “Longer idle timeouts are always better.” Not if the other side closes first; then they cause errors.

Interview angle

When a design has service-to-service calls across zones or regions, mention connection reuse and estimate the setup cost in round trips. For databases, size pools against the server’s connection cap across all instances, and mention a pooler. If asked about intermittent 502s behind a load balancer, explain the idle-timeout mismatch and its fix. Bonus: long-lived HTTP/2 or gRPC connections and how they defeat connection-level load balancing.

Model assumptions

Simplified model, not a benchmark. Handshakes, keep-alive and the idle-timeout race are scripted illustrations: the engine has no TCP or TLS model. API → Payments is a cross-region hop of 20 ms one way (40 ms RTT). In the simulated steps, a new TCP + TLS 1.3 connection per call is modelled by adding its two round trips (80 ms) to that hop; the API has 24 workers with 5 ms of work each and holds a worker while it waits for Payments (40 workers, 15 ms). The ledger database is the engine’s connection pool (16 connections, 25 ms per query, lognormal); connections held idle by the reporting job are modelled as fewer usable connections. Arrivals are random (Poisson). Utilisation is the fraction of busy workers or connections, not CPU. Numbers are illustrative.

The lesson as textEvery step of the simulation, written out.
  1. 1. A new connection costs round trips

    The API calls a Payments service in another region, 40 ms round trip away. Before the first byte of the request can be sent, a new connection needs a TCP handshake (SYN, SYN-ACK: one round trip) and a TLS 1.3 handshake (ClientHello, ServerHello with certificate: one more). TLS 1.2 needed two.

    The call itself is then one more round trip plus 15 ms of work: 135 ms in total, of which 80 ms is setup. The setup cost scales with distance, not with how much data you send. (Scripted illustration.)

    Scene: Scripted: the API opens a new connection to Payments: a TCP handshake and a TLS 1.3 handshake, one round trip each, then the request and its response. 135 ms in total, 80 ms of it setup.

    Key idea: New TCP + TLS 1.3 connection = 2 round trips before the request. Far away, setup can cost more than the call.

  2. 2. Keep the connection open and reuse it

    With keep-alive (the default in HTTP/1.1 and later), the connection stays open after the response. The next call skips both handshakes and costs one round trip plus the work: 55 ms. Two calls go out here on the same connection, back to back.

    HTTP/1.1 carries one request at a time per connection, so a client keeps a pool of them; HTTP/2 and gRPC multiplex many requests over one. Either way, the setup is paid once and spread over thousands of calls. (Scripted illustration.)

    Scene: Scripted: two calls travel over the same open connection, each taking one round trip plus 15 ms of work, with no handshakes.

    Key idea: Reuse amortises setup: pay the handshakes once per connection, not once per request.

  3. 3. Live traffic, a new connection per call

    Now real traffic: 100 requests per second, and the API’s HTTP client opens a fresh connection for every call (a client created per request, or keep-alive switched off). In the model the two handshake round trips are added to the API → Payments hop.

    P50 is about 160 ms: 20 ms to the user and back, 5 ms of API work, and a 135 ms Payments call. The API is about 60% busy, because each worker waits through the handshakes too.

    Scene: Users send 100 requests per second. Each API call to Payments opens a new connection; P50 is about 160 ms and the API is about 60% busy.

    Key idea: Handshake time is not only latency: the caller’s worker is tied up for all of it.

  4. 4. Double the traffic: the API runs out of workers

    Traffic doubles to 200 requests per second. By Little’s law the API needs about 200 × 0.14 s ≈ 28 busy workers, and it has 24. Its queue fills and requests are rejected, although the API itself does only 5 ms of work per request and Payments has plenty of room.

    The capacity is being spent on waiting for handshakes. The same applies to anything holding a slot while it connects: threads, file descriptors, ephemeral ports on the client.

    Scene: At 200 requests per second the API is fully busy waiting on new connections; its queue is full and some requests are rejected.

    Key idea: Connection setup inflates how long every slot is held, so it eats capacity as well as latency.

  5. 5. A shared client with a connection pool

    Create the HTTP client once and share it, so its pool keeps connections to Payments open. Each call now costs one round trip: the API → Payments hop is back to 20 ms.

    At the same 200 requests per second, P50 falls by about 80 ms to roughly 80 ms, the API drops to about half busy and the rejections stop. Nothing got faster on either server; the work simply stopped waiting for handshakes.

    Scene: The API reuses pooled connections to Payments. At 200 requests per second P50 is about 80 ms, the API is about half busy and nothing is rejected.

    Key idea: Reusing connections is often the cheapest latency and capacity win in a service-to-service call path.

  6. 6. Idle timeouts that do not match

    Open connections do not live forever. Payments closes a connection after 5 s idle; the API’s pool keeps idle connections for 60 s. When a quiet connection hits 5 s, Payments sends FIN, and if the API picks that same connection for a request at that moment, the request meets a closed socket: connection reset, or a 502 from a proxy.

    The rule: the side that reuses connections (client pool, load balancer) must give up on idle ones before the server does, for example pool idle timeout 4 s against the server’s 5 s. Then the next call opens a fresh connection, as shown after the error. (Scripted illustration.)

    Scene: Scripted: Payments closes an idle connection while the API sends a request on it; the request fails with a connection reset. The API then opens a fresh connection with a handshake and the call succeeds.

    Key idea: Client idle timeout < server keep-alive timeout, otherwise reuse races with close and requests fail.

  7. 7. Every server caps its connections

    Payments stores charges in a ledger database. Servers limit connections because each one costs memory and bookkeeping even when idle: a Postgres connection is a whole backend process, and max_connections defaults to 100. Payments gets a pool of 16 of them.

    At 200 requests per second and about 25 ms per query, Little’s law says only about 5 are busy at a time, so the pool is comfortable. Traffic is back on and nothing fails.

    Scene: Payments now queries a ledger database through a pool of 16 connections. At 200 requests per second about 5 are busy and nothing fails.

    Key idea: Connection limits exist because connections cost the server resources whether they are working or idle.

  8. 8. Idle connections still occupy slots

    A reporting job shares the same pool budget. It opens a transaction, then sits idle while it formats a report, holding 12 connections that do nothing (idle in transaction). Payments is left with 4.

    It needs about 5. Queries queue for a connection, Payments and API workers wait with them, and the backlog climbs up the chain until the API runs out of workers and rejects requests. The ones that get through take more than twice as long. The database is barely working; its connection slots are simply taken.

    Scene: A reporting job holds 12 of the 16 connections idle. Payments has 4, fewer than it needs; queries wait for a connection, the API fills up and rejects some requests, and the rest are more than twice as slow.

    Key idea: An idle connection uses a slot as surely as a busy one. Leaked or parked connections starve everyone else.

  9. 9. Reclaim idle connections, isolate the job

    Three fixes, usually together. The database ends sessions that sit idle inside a transaction (Postgres: idle_in_transaction_session_timeout). Pools close connections idle longer than an idle timeout and replace connections older than a maximum lifetime. And the reporting job gets its own small pool, so it can never take Payments’ share.

    Payments has its 16 connections back, queries stop waiting and the errors disappear.

    Scene: Idle sessions are reclaimed and the reporting job has its own pool. Payments uses its 16 connections again and nothing fails.

    Key idea: Bound idle time on both sides and give each workload its own connection budget.

  10. 10. Manage connections like any other resource

    Connections are expensive to open (round trips, CPU for TLS, a process or thread on some servers) and cost resources while open, busy or idle. So: reuse them through a long-lived, shared client; cap them per server and per workload; time out idle ones, with the client giving up before the server; and recycle them after a maximum lifetime so DNS changes and rebalanced backends are picked up.

    Watch for: new connections per second, pool wait time and acquire timeouts, connections by state (active, idle, idle in transaction), and resets after idle periods.

    Scene: Users, API, Payments and the ledger database at 200 requests per second with pooled connections everywhere; nothing fails.

    Key idea: Open few, reuse many, cap them per server and workload, and retire idle ones before the other side does.