Keep-Alive and Connection Reuse
Reusing a connection skips the TCP and TLS handshakes and starts with a grown congestion window — but both ends, and every proxy between them, close idle connections on their own timers, and the race between a server closing and a client reusing produces the sporadic ECONNRESET every production system eventually meets.
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
What reuse saves
Without reuse, each request is connect → request → close: a The Three-Way Handshake (1 RTT), a The TLS Handshake (1 RTT with 1.3, 2 with 1.2), the request/response (1 RTT), then a FIN exchange and a socket parked in TIME_WAIT for a minute (The Connection Lifecycle: Close, Reset, TIME_WAIT, CLOSE_WAIT). Three requests cost nine round trips and three TIME_WAIT sockets. With reuse it is connect → request → request → request → close: two handshake RTTs paid once, then one RTT per request — five round trips for the same work, and one socket.
The second saving is invisible in the RTT count. A new TCP connection starts with an initial congestion window of about 10 segments (~14 kB) and grows it per round trip (Congestion Control: Protecting the Network); a reused connection has already grown its cwnd to whatever the path allows and can send a 200 kB response in one burst. On a 100 ms link that is the difference between one round trip and four for the same response. Reused connections are warm in two senses: no handshake, and a window sized to the path.
HTTP/1.1 makes persistence the default (HTTP/1.1: Persistent Connections and Their Limits); HTTP/2 and HTTP/3 connections are designed to live for the whole session and carry all requests as streams. The mechanism therefore matters most for 1.1 clients — every backend service calling another backend service, every SDK, every script — where the client library’s defaults decide whether reuse happens at all.
WITHOUT REUSE WITH REUSE TCP handshake 100 ms TCP handshake 100 ms TLS handshake 100 ms TLS handshake 100 ms request 1 100 ms request 1 100 ms close (FIN/ACK) — request 2 100 ms (cwnd already grown) TCP handshake 100 ms request 3 100 ms TLS handshake 100 ms close (later, idle) request 2 100 ms ───────────────────────────── TCP handshake 100 ms total ≈ 500 ms, 1 socket TLS handshake 100 ms request 3 100 ms ───────────────────────────── total ≈ 900 ms, 3 sockets in TIME_WAIT
Idle timeouts and the reuse race
An open connection costs a file descriptor, kernel buffers and — on a thread-per-connection server — a thread, so servers close connections that have been idle for a while: Node’s http.Server after keepAliveTimeout (5 s by default), nginx after keepalive_timeout (75 s), Apache after KeepAliveTimeout (5 s), Go’s net/http never by default. Clients keep their own idle timers. When those timers differ, a race appears: the server’s timer fires and it sends FIN; at the same instant the client, whose timer has not fired, writes the next request onto the socket. The request arrives at a socket the server has closed; the kernel answers with RST; the client sees ECONNRESET, socket hang up, Connection reset by peer, or a 502 from an intermediate proxy that hit the same race against its upstream.
The symptom is maddening because it is rare and unreproducible: it happens only when a request lands in the window between the server deciding to close and the client learning about it — one RTT wide, and only after an idle period of exactly the server’s timeout. Dashboards show a 0.1% error rate at a steady trickle, always on the first request after a quiet moment. The classic production instance: Node’s 5-second keepAliveTimeout behind an AWS ALB whose idle timeout was 60 s — the ALB reused connections that Node had closed and returned 502s, until Node’s timeout was raised above the balancer’s (and headersTimeout above that).
The rule is: the client’s idle timeout must be shorter than the server’s, at every hop. Then the client always closes first, and never writes to a connection the other side has given up on. Where you cannot control the client, make the server’s timeout longer than any intermediary’s. And because a race can still be lost (a server closing for other reasons: deploy, overload), clients should retry *idempotent* requests that fail with a reset before any response bytes were received — which is why the method semantics in HTTP: Requests, Responses, Headers and Status Codes matter.
- Node:
server.keepAliveTimeout(default 5000 ms); set it above your load balancer’s idle timeout; setheadersTimeouthigher still. - AWS ALB idle timeout default 60 s; nginx
keepalive_timeout75 s downstream andkeepalivepool +keepalive_timeoutupstream; Envoy/Istio have their own. - Every proxy in the chain has *two* timeouts — one facing the client, one facing the upstream — and the race exists at each hop.
- A
FINfrom the server closes only its write side; the kernel answers later writes withRST. The client cannot detect the close before writing unless it reads first.
Two different keep-alives
The word names two unrelated mechanisms. The HTTP `Keep-Alive` header (Keep-Alive: timeout=5, max=1000) is an HTTP/1.x, hop-by-hop hint accompanying Connection: keep-alive that tells the peer how long the connection may stay idle and how many requests it will accept; it is advisory, dropped by proxies, and forbidden in HTTP/2. It is about connection reuse at the HTTP layer.
TCP keepalive is a socket option (SO_KEEPALIVE) that makes the kernel send empty probe segments on an idle connection to detect that the peer has vanished — a crashed host, a NAT that dropped the mapping, a cable unplugged. Linux defaults are 7200 s before the first probe (tcp_keepalive_time), then 9 probes 75 s apart, so a dead peer is noticed after about two hours unless the application lowers the values. It is about liveness detection at the transport layer and has nothing to do with HTTP persistence. Enabling one does not enable the other; a Node http.Agent({ keepAlive: true }) enables HTTP reuse *and* sets SO_KEEPALIVE on the socket, which is a source of the confusion.
For long-lived connections through NATs and load balancers, TCP keepalive (or an application-level ping — HTTP/2 PING, WebSocket ping frames) is what keeps the intermediary’s mapping alive and detects half-open connections; HTTP keep-alive just decides whether the next request may use the same socket.
| HTTP `Keep-Alive` header | TCP keepalive (`SO_KEEPALIVE`) | |
|---|---|---|
| Layer | HTTP/1.x (hop-by-hop header) | TCP, in the kernel |
| Purpose | Allow the next request on the same connection; hint idle timeout and max requests | Detect a dead or half-open peer by sending empty probes |
| Who acts | HTTP client/server code | The kernel, after the application sets the socket option |
| Default timing | Server-specific: 5 s (Node, Apache), 75 s (nginx) | Linux: first probe after 7200 s, 9 probes every 75 s |
| In HTTP/2 and /3 | Forbidden / not applicable; connections are persistent by design | Still useful; also PING frames at the protocol level |
Key points
- Reuse turns connect/request/close × N into connect/request × N/close: two handshake RTTs paid once, and the congestion window stays grown.
- Both ends and every proxy close idle connections on their own timers; a server closing while the client reuses yields sporadic
ECONNRESET/socket hang up/ 502. - Rule: the client-side idle timeout must be shorter than the server-side one at every hop, and idempotent requests that fail with a reset before any response should be retried.
- Node’s 5 s
keepAliveTimeoutbehind a 60 s ALB is the canonical instance of the race. - HTTP
Keep-Alive(connection reuse hint) and TCP keepalive (SO_KEEPALIVEliveness probes) are different mechanisms at different layers. - Long-lived connections through NATs need transport- or protocol-level pings to stay mapped and to detect half-open peers.
Why does this exist?
Mechanisms are answers to constraints. Open each question before reading the answer.
▸Why do servers close idle connections at all?
Each open connection holds a descriptor, kernel buffers and possibly a thread; ten thousand idle clients would pin resources doing nothing. Closing after a few seconds of silence reclaims them at the cost of a handshake for the occasional returning client.
▸Why can the client not check the connection before writing?
A FIN sits in the client’s receive buffer until the client reads; a write does not look there first. Only a read (or a failed write answered by RST) reveals the close, and by then the request is gone. Ordering the timeouts is the only reliable prevention.
▸Why does a reused connection deliver a large response faster even with the same RTT?
TCP’s congestion window grows with successful round trips and persists for the connection; a new connection starts at ~14 kB and needs several RTTs to reach the path’s capacity, a warm one already has it.
Keep-alive
How it fails
What the failure looks like from inside real software.Reference · showHide
- 0.1% of requests fail with
ECONNRESET/socket hang up, always after an idle gap: server idle timeout shorter than client’s (or than the load balancer’s). - ALB returns intermittent 502s to a Node backend:
keepAliveTimeout(5 s) below the ALB idle timeout (60 s). Raise the server’s above the balancer’s. - Client library with pooling disabled (
Connection: close,keepAlive: false, one-shotrequests.get): p50 latency two handshakes higher than necessary andTIME_WAITsockets pile up until ephemeral ports run out. - Long-lived connection through a NAT dies silently after 5 minutes idle; the next write hangs for the full TCP retransmission timeout because TCP keepalive is at its 2-hour default.
- Non-idempotent
POSTretried after a reset by a client that could not tell whether the server processed it; duplicate side effects. - A proxy honours
Keep-Alive: timeout=5from the origin but the client behind it has a 30 s idle timer; the race moves to the proxy’s upstream side.
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.Why does a TCP connection sit in TIME_WAIT after it closes? Which side ends up in that state, and when does it become a production problem?
Show a strong answerHide the answer
TCP closes with a four-way exchange: each side sends
FINand acknowledges the other’s. The side that sends the first FIN — the active closer — must, after receiving the peer’s FIN and sending the final ACK, stay inTIME_WAITfor 2×MSL (on Linux a fixed 60 s;tcp_fin_timeoutdoes *not* change it — it governsFIN_WAIT_2). The passive closer goes straight toCLOSED. See The Connection Lifecycle: Close, Reset, TIME_WAIT, CLOSE_WAIT.Two reasons. First, the final ACK may be lost; the peer then retransmits its FIN, and someone must still be there to ACK it — otherwise the peer gets a RST and reports an error on a connection that closed cleanly. Second, old duplicates: a segment from this connection delayed somewhere in the network could arrive after a *new* connection with the same four-tuple (src IP, src port, dst IP, dst port) is established, and be accepted as part of it because sequence numbers can overlap. Holding the tuple reserved for 2×MSL lets those stragglers expire. TIME_WAIT is correctness, not laziness.
It becomes a problem because of who closes. A client that opens a fresh connection per request to the same server — an HTTP client without keep-alive, a proxy without an upstream pool, a service hammering one database — is usually the active closer, so every request leaves a
TIME_WAITsocket holding one ephemeral port for 60 s. Linux’s default rangeip_local_port_rangeis 32768–60999, about 28 000 ports, so against a single destination the sustainable rate is 28 000 / 60 ≈ 470 connections per second. Beyond thatconnect()fails withEADDRNOTAVAIL("Cannot assign requested address") before a packet is sent, which looks like a network outage and is not one. See Ports: Addressing a Process, Not a Machine.The real fix is to stop opening connections: keep-alive and a bounded pool (Connection Pooling) turn 470 connections per second into a handful of long-lived ones. Secondary knobs: widen the port range (to ~64 000), use several source IPs, or on the client
Full interview question, with follow-ups and red flags →net.ipv4.tcp_tw_reuse=1, which lets aTIME_WAITtuple be reused for an *outgoing* connection after 1 s when TCP timestamps prove the new segments are newer — safe.tcp_tw_recyclewas removed in Linux 4.12 because it dropped legitimate SYNs from clients behind NAT whose timestamps were not monotonic; recommending it is a red flag.SO_LINGERwith a zero timeout sends RST instead of FIN and skips TIME_WAIT entirely — at the cost of possibly discarding unsent data and every guarantee above.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 →