How to Tune HTTP Keep-Alive and Connection Reuse
Configure keep-alive timeouts and pool sizes so clients reuse connections, avoid stale sockets, and cut handshake latency without leaking idle connections.
On this page
Introduction
Every TCP connection costs a handshake, and TLS adds another round trip or two on top. When a service makes many requests to the same origin, reusing connections is one of the highest-return performance changes available, because it removes that setup cost from every call after the first. The mechanism is keep-alive: after a response, the connection stays open for the next request. But keep-alive has sharp edges, and an untuned client either opens too many sockets, queues behind too few, or writes into a socket the server already closed.
This tutorial explains how to tune keep-alive and connection pools for a Node.js client. It covers enabling reuse, sizing the pool to real concurrency, aligning idle timeouts with the server, handling the stale-socket race, and measuring that reuse is actually happening. The examples use an HTTP agent, but the reasoning applies to any client library.
Enable and benefit from reuse
With keep-alive, a client that has finished a request keeps the socket in a free pool rather than closing it. The next request to the same origin grabs the socket and sends immediately, skipping the handshake. For a service making dozens of calls per second to one backend, this removes most of the connection latency from the steady state. The first request still pays the handshake; the rest should not.
Node.js enables keep-alive on its global agent by default in recent versions, but a custom agent or an older default may close sockets after each request. Check the agent configuration explicitly, because a client that silently disables reuse will still work and simply be slower, which is easy to miss.
import { Agent } from 'undici';
const agent = new Agent({
keepAliveTimeout: 10000, // keep idle sockets 10s
keepAliveMaxTimeout: 60000, // cap negotiated extension
connections: 32, // max sockets per origin
pipelining: 1,
});
const res = await fetch('https://api.example.com/orders', { dispatcher: agent });
Size the pool to sustained concurrency
The pool size caps how many requests can be in flight at once on reusable sockets. Set it from the concurrency you actually sustain. If it is too small, requests queue waiting for a free socket and latency rises under load even though the backend is healthy. If it is too large, you hold many idle sockets that consume file descriptors and memory on both sides, and you may exceed connection limits at the server or a proxy.
Watch the queue. A rising wait-for-socket time is the signal to increase the pool; a pool full of idle sockets during quiet periods is the signal to decrease it or shorten the idle timeout. The right size is empirical, not a guess, and it changes as the service’s traffic pattern changes.
Align idle timeouts and handle stale sockets
A server closes an idle keep-alive connection after its own timeout to reclaim resources. If the client’s idle timeout is longer, the client believes the socket is open and writes a request into a socket the server has already closed. The write may appear to succeed into a buffer, and the failure surfaces as a reset on the response, often right after a period of inactivity. Set the client’s idle timeout below the server’s so the client discards the socket first.
Even with aligned timeouts, a race remains: the server can close a socket just as the client is about to use it. A robust client retries a request that fails on a reused, previously idle socket exactly once on a fresh socket. This is safe for idempotent requests and must be gated on idempotency for others. Do not retry a request that may have already reached the server unless it is idempotent.
async function requestWithStaleRetry(send, { idempotent }) {
try {
return await send();
} catch (err) {
if (idempotent && isStaleSocketError(err)) return send(); // one retry, fresh socket
throw err;
}
}
function isStaleSocketError(err) {
return err && (err.code === 'ECONNRESET' || err.code === 'EPIPE');
}
Watch interaction with gateways and TLS
A proxy or load balancer in front of the backend may terminate client connections on its own schedule, shorter than the backend’s. Align the chain so the client’s idle timeout is below the shortest timeout in the path. Otherwise the client keeps sockets the intermediary has closed. If the intermediary rewrites connections, its idle behavior dominates.
For TLS, reuse also saves the handshake and any session resumption negotiation. A socket that is closed and reopened pays both the TCP and the TLS setup, so the reuse benefit is larger over TLS than over plaintext. Measure the setup time you avoid to justify the pool size and the idle window.
Measure reuse and latency
Track connections opened per interval against requests made. In a healthy steady state, requests far exceed connections opened, because most requests reuse a socket. A near one-to-one ratio means reuse is not happening; a sudden jump in connections points at a timeout misalignment or a burst. Also track the time spent waiting for a pooled socket, which rises when the pool is too small.
curl -sv --keepalive-time 10 -o /dev/null https://api.example.com/orders 2>&1 | grep -i 'Re-using'
# expect 'Re-using existing connection' on the second request, not a new TLS handshake
Common pitfalls
Disabling keep-alive and paying a handshake per request, sizing the pool from a guess rather than measured concurrency, setting the client idle timeout longer than the server’s so stale sockets are used, retrying a non-idempotent request after a reset, and leaking sockets by never closing idle ones are the recurring mistakes. Measuring connections opened and queue time exposes them, and aligning timeouts with the server removes the stale-socket race.
Conclusion
Keep-alive turns a per-request handshake into a one-time cost. Enable reuse, size the pool to sustained concurrency rather than a guess, keep the client idle timeout below the server’s, and retry once on a fresh socket when a reused one turns out stale, gated on idempotency. Self-check by measuring requests per connection opened and by confirming a second request reports connection reuse. When reuse is healthy, the network cost of a call drops to the payload itself.
Sources: MDN: Connection management in HTTP, RFC 9112: HTTP/1.1 connection management, MDN: Keep-Alive header.
FAQ
- Who closes an idle keep-alive connection?
- Either side may. A server commonly closes after an idle timeout to reclaim resources, so a client that keeps a socket longer than the server does will send on a closed socket and see a connection reset. Align your idle timeout below the server's and retry once on a fresh socket.
- How large should the pool be?
- Size it to the concurrency you actually sustain, not to an arbitrary large number. Too small queues requests; too large wastes sockets and memory. Measure queue time and increase only when requests are waiting for a socket.
Report a problem with this articleOpens a pre-filled issue on GitHub.