How to Tune HTTP Connection Pools
Size pools with Little’s law, enable keep-alive, cap per-host sockets, and instrument wait time so connection setup stops taxing every request.
On this page
Introduction
Every outbound HTTP request that runs on a fresh connection pays for DNS resolution, a TCP handshake, and a TLS handshake before a single byte of application data moves. That is one to three round trips, tens of milliseconds on a good network and far more across continents. Behind that cost sits a second one: creating sockets, sockets buffers, and TLS state is CPU work on both ends. Connection pooling eliminates both by reusing established connections for many requests, and every serious client library ships one. What libraries cannot do is choose the right size for the workload, and wrong sizes fail in both directions: too small and requests queue behind pool acquisition, too large and the pool exhausts the server or the local file descriptor limit. This tutorial shows how to measure whether pooling is the actual bottleneck, how to compute a defensible pool size, and how to configure the three most common client stacks so the configuration survives production traffic.
Measure before tuning
Pool tuning without measurement optimizes the wrong thing. Three numbers establish the baseline. Connection establishment latency: the time from socket creation to the first request byte, visible in tracing spans or by timing a single cold request repeatedly. Connection reuse rate: the fraction of requests served by an existing connection, which most clients export or can be derived from handshake counters on the server. Pool wait time: how long a request waits for an available connection before it starts, which is the direct symptom of an undersized pool. If reuse rate is already above ninety-five percent and pool wait is near zero, the pool is not the bottleneck and effort belongs elsewhere, usually in payload size or serialization. If pool wait is significant, the pool is undersized. If reuse rate is low despite keep-alive, connections are being evicted before reuse, which points at idle timeout mismatches rather than size. Diagnosing which of these three patterns is present turns guesswork into a two-line change.
Size the pool with arithmetic
Pool size follows from Little’s law: average concurrency equals arrival rate multiplied by average latency. A service making two hundred requests per second to a dependency whose p50 latency is forty milliseconds has an average concurrency of eight. The pool must hold at least eight connections or requests queue. Size for the p99 tail rather than the average: if p99 latency is two hundred milliseconds and the request burst is four hundred per second, the tail needs eighty connections. Add headroom of twenty to thirty percent and that is the ceiling, not a starting point to grow from. Going larger does not make the dependency faster; it lets the client open more concurrent work than the server can serve, converting queueing in the pool into queueing in the server, which is strictly worse because the server queue is shared with other clients. The per-host cap matters more than the global cap, because dependencies differ: a fast internal service tolerates fifty sockets while a rate-limited third-party API should be capped at whatever its quota implies.
Configure Node.js clients
Node’s default HTTP agent historically disabled keep-alive. Since Node 19 the global agent keeps connections alive with a five-second timeout, but production code should create an explicit agent rather than rely on defaults, because the default has no maximum and no observability.
import http from 'node:http';
const agent = new http.Agent({
keepAlive: true,
keepAliveMsecs: 30_000,
maxSockets: 64,
maxFreeSockets: 32,
scheduling: 'fifo',
});
const client = http.request;
function fetchUpstream(path) {
return new Promise((resolve, reject) => {
const req = client({ host: 'internal-api', path, agent }, res => {
const chunks = [];
res.on('data', c => chunks.push(c));
res.on('end', () => resolve(Buffer.concat(chunks).toString()));
});
req.setTimeout(2_000, () => req.destroy(new Error('upstream timeout')));
req.on('error', reject);
req.end();
});
}
For higher-level clients such as got or axios, pass the same agent through the options; creating a new client per request throws away the pool entirely. Set maxFreeSockets lower than maxSockets so idle connections are reclaimed when a burst ends. The scheduling option controls which free connection a request takes; fifo spreads load across connections, which keeps more of them alive and warm.
Configure Go and Python clients
Go’s standard transport pools by default and exposes the knobs through http.Transport. The default MaxIdleConnsPerHost is famously small, two, which causes exactly the eviction problem described earlier for any client with moderate concurrency.
transport := &http.Transport{
MaxIdleConns: 100,
MaxIdleConnsPerHost: 32,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 3 * time.Second,
}
client := &http.Client{Transport: transport, Timeout: 5 * time.Second}
Python’s requests library pools through urllib3. A session holds one PoolManager, and the per-host connection count is set by mounting an adapter with an explicit pool size.
import requests
from requests.adapters import HTTPAdapter
session = requests.Session()
adapter = HTTPAdapter(pool_connections=8, pool_maxsize=32, max_retries=0)
session.mount('https://', adapter)
resp = session.get('https://internal-api/report', timeout=(1, 4))
The two timeout values in the Python example are connect and read timeouts, both of which matter more than pool tuning once the pool is correctly sized. In every stack, the client instance must be a singleton created at startup and reused for the life of the process.
Idle eviction and timeout matching
A pooled connection only pays off if it survives until the next request. Idle connections are closed by three independent parties: the client after its idle timeout, the server after its keep-alive timeout, and any intermediary in between. If the server closes at five seconds and the client keeps connections for thirty, the client regularly hands a request to a socket the server just closed, producing a confusing connection-reset error on a perfectly healthy endpoint. The rule is to keep the client idle timeout shorter than the shortest timeout anywhere on the path to the server. A client of thirty seconds behind a load balancer that closes idle connections at sixty seconds is safe; the reverse is a race. Some clients mitigate the race with optimistic reuse plus retry on a reset for idempotent requests, which is a reasonable belt-and-suspenders addition, but it is a supplement to correct timeouts, not a replacement.
Instrument the pool
A tuned pool decays as traffic grows and dependency latency shifts, so export metrics from the start. The two that matter most are pool wait time, the duration between a request asking for a connection and receiving one, and active connections versus capacity. Pool wait at a sustained nonzero value means the pool is the bottleneck right now. Active connections pinned at capacity while wait climbs confirms the direction. Connection creation rate is the third: a healthy pool creates connections rarely, so a steady creation rate indicates eviction churn or a leak. All three are available with a thin wrapper around acquisition, or from the library’s own metrics in urllib3 and from Go’s httptrace hooks. Alert on pool wait exceeding a small threshold, not on socket counts, because socket counts are an implementation detail while wait time is the user-visible symptom.
import "net/http/httptrace"
req, _ := http.NewRequestWithContext(ctx, 'GET', url, nil)
trace := &httptrace.ClientTrace{
ConnectStart: func(network, addr string) { connCreated.Inc() },
GotConn: func(info httptrace.GotConnInfo) {
if !info.Reused { connCreated.Inc() } else { connReused.Inc() }
},
}
req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
Common pitfalls
- New client per request. The pool never gets a second use; every request pays full handshake cost.
- Trusting defaults. Node before 19, Go’s MaxIdleConnsPerHost of two, and per-adapter urllib3 defaults are all wrong for service-to-service traffic.
- Sizing to fantasy load. Pools sized for peak-of-the-year traffic overload dependencies at every other time.
- Ignoring the server-side ceiling. The dependency’s own connection limits and rate quotas cap the useful pool size.
- Idle timeouts longer than the path allows. Requests land on sockets the server just closed, producing spurious resets.
- One global pool for all dependencies. A slow third-party API starves a fast internal service waiting in the same queue; isolate pools per host.
Conclusion
Connection pooling removes a fixed per-request tax, but only when it is sized, configured, and measured. Establish the baseline first: reuse rate, handshake latency, and pool wait tell you whether the pool is even the problem. Derive the size from arrival rate times tail latency with modest headroom, and cap per host because dependencies are not equal. Configure keep-alive and eviction explicitly in every client library, keep client idle timeouts shorter than anything on the path to the server, and share one client instance per dependency for the process lifetime. Finally, export pool wait and creation metrics so the next traffic doubling turns into a routine resize instead of an incident.
Sources: MDN: Connection management in HTTP/1.x, Node.js http.Agent docs, urllib3 PoolManager reference.
FAQ
- Is a bigger pool always better?
- No. Extra sockets add load to the server, consume file descriptors, and can trigger connection limits or throttling downstream. Size to target concurrency, not to maximum theoretical load.
- Why do I still see handshakes with keep-alive enabled?
- Idle connections are closed by either side after a timeout, and the next request pays setup again. Match the client idle timeout to the server or intermediary keep-alive timeout, keeping the client shorter.
- Should pools be shared across the application?
- Yes, one client instance per dependency, created at startup. Per-request clients defeat pooling entirely and are the most common cause of handshake storms in code reviews.
Report a problem with this articleOpens a pre-filled issue on GitHub.