The Linux default port range and 60 s TIME_WAIT cap one client at about 470 new connections per second to one destination. Measured TIME_WAIT pile-up and the fix: reuse.
The error that appears only under load
Hansini's price-sync job for Belgavi's Book Store calls an internal catalog service once per book. It opens a new HTTP connection for each request, because the first version used a quick script with no connection pool, and nobody changed it. At a few requests per second it is fine. During a full re-sync it runs hundreds of requests per second, and after about a minute every request fails with EADDRNOTAVAIL ("Cannot assign requested address") on Linux, or a socket error such as WSAEADDRINUSE or WSAENOBUFS on Windows. The catalog service is healthy. The client has run out of ports.
This guide explains the arithmetic behind that ceiling, shows the TIME_WAIT pile-up in a local measurement, and explains why the fix is connection reuse rather than kernel settings.
Why closing a connection keeps a port busy
A TCP connection is identified by four values: source address, source port, destination address and destination port. When a client connects without binding a port, the operating system picks an ephemeral source port from a configured range.
When a connection closes, the side that closes first moves to the TIME_WAIT state and keeps the four-tuple reserved for a while. TIME_WAIT exists for two reasons in the TCP specification: so a final acknowledgement that gets lost can be retransmitted, and so delayed segments from the old connection cannot be mistaken for segments of a new connection with the same four-tuple. On Linux, the duration is fixed by TCP_TIMEWAIT_LEN, defined in the kernel source as 60 seconds.
So each short-lived connection from a client to one destination occupies one ephemeral port for about a minute after it ends, if the client closes first. That is the normal case for HTTP clients that close after a response.
The ceiling, worked out
The Linux kernel documentation gives the default ip_local_port_range as 32768 to 60999. That is 28,232 ports. If each one is held for 60 seconds after use, a single client address can open at most about
28,232 ports / 60 s ≈ 470 new connections per second
to one destination address and port, sustained. A burst above that rate works for up to a minute and then fails. The limit is per destination: Linux can reuse a local port for a connection to a different destination address or port, because the four-tuple differs. That is why the failure appears when one client hammers one service, and why it can disappear when the same traffic is spread across several destination addresses.
On Windows the default dynamic port range is different. On the machine used for this guide, netsh int ipv4 show dynamicport tcp reported a start port of 49152 and 16,384 ports, roughly 40 percent fewer than the Linux default.
Measured: TIME_WAIT accumulating
The companion probe opens 3,000 short-lived connections to a server on the loopback interface, one after another. Each sends a few bytes, reads the reply and closes; the server waits for the client to close first, as an HTTP server with keep-alive would. It then counts sockets in TIME_WAIT with netstat.
| Measurement | Value |
|---|---|
| Connections opened and closed | 3,000 |
| Elapsed time | 1.74 s |
| Sockets in TIME_WAIT on the client side afterwards | 2,981 |
| Sockets in TIME_WAIT on the server side afterwards | 0 |
| Windows dynamic port range | 49152, 16,384 ports |
That loop ran at about 1,700 connections per second. At that rate the 16,384 ports on this machine would be used up in under ten seconds if TIME_WAIT lasted that long, and the measurement shows nearly every connection still holding its port when the loop ended. The TIME_WAIT is all on the client side, because the client closed first. We did not measure how long Windows keeps sockets in TIME_WAIT on this machine; the count above was taken immediately after the loop.
The fix: reuse connections
Opening a new connection per request also costs a TCP handshake and, with TLS, a TLS handshake for every request. Reusing connections removes both costs and the port problem together. A pooled client sends many requests over each connection, so the number of connections opened per second, and therefore the number of TIME_WAIT sockets, drops by the reuse factor.
import http.client
def sync_prices(host: str, isbns: list[str]) -> list[int]:
# One persistent connection for the whole batch instead of one per request.
conn = http.client.HTTPConnection(host, timeout=5)
statuses = []
try:
for isbn in isbns:
conn.request("GET", f"/price/{isbn}")
resp = conn.getresponse()
resp.read() # drain the body so the connection can be reused
statuses.append(resp.status)
finally:
conn.close()
return statusesMost HTTP libraries pool for you if you keep one client object for the life of the process: a requests.Session in Python, a single java.net.http.HttpClient instance in Java, an http.Agent with keepAlive in Node.js. The bug is usually that a new client is created per request, which throws the pool away each time. Drain or close every response body, too; a connection whose response was not read to the end cannot be reused, and some clients silently open a new one.
The companion example sends the same 200 requests both ways against a loopback server and counts connections: 200 with a new connection each time, 1 with a persistent connection.
Why not tune the kernel instead
Three knobs come up when people search for this error, and each has a cost.
- Widening
ip_local_port_rangeraises the ceiling proportionally. It is a reasonable safety margin, but it moves the limit rather than removing the cause, and the low end must stay above ports other services listen on. tcp_tw_reuseallows a new outgoing connection to reuse a port in TIME_WAIT when TCP timestamps make it safe. The kernel documentation lists the values as 0 to disable, 1 for global enable and 2 for loopback traffic only, with 2 the default, and adds that "It should not be changed without advice/request of technical experts." Turning it on globally helps clients, not servers, and depends on timestamps being enabled on both ends.- Shortening TIME_WAIT is not a sysctl on Linux at all; the 60-second value is compiled in. Advice to change
tcp_fin_timeoutfor this is mistaken, since that setting controls the FIN-WAIT-2 state, not TIME_WAIT.
There is also an older knob, tcp_tw_recycle, that broke clients behind NAT and was removed from Linux in version 4.12; any guide that recommends it is out of date.
When the server closes first
TIME_WAIT lands on whichever side closes first. When a server closes, for example because it closes idle keep-alive connections or speaks HTTP/1.0 without keep-alive, the server accumulates the TIME_WAIT sockets instead. That does not exhaust ports on the server, since all those connections share its one listening port and differ in the client's address and port. It costs memory and, on Linux, is bounded by tcp_max_tw_buckets, which the kernel documentation describes as the "Maximal number of timewait sockets held by system simultaneously". If that bound is reached, new TIME_WAIT sockets are destroyed immediately and the kernel logs a warning. A server with millions of TIME_WAIT entries is a sign that clients are not reusing connections either; the fix is again on the client side, or in matching idle timeouts so that the client, not the server, ends idle connections.
Watching for it before it fails
Count TIME_WAIT sockets per destination on clients (ss -tan state time-wait on Linux, netstat -ano on Windows) and alert when the count approaches the port range. Track new connections per second per destination in the client's metrics, if the HTTP library exposes them. A sudden rise in connection count with flat request count is the signature of a client that stopped reusing connections, often after a refactor that moved client creation inside a loop.
Limits
The local measurement ran on loopback on one Windows 11 machine, with Python 3.13.5 sockets; it shows the accumulation, not production rates. The Linux figures come from kernel documentation and source, not from a Linux measurement here. Network address translation adds its own port limits on the NAT device, which are separate from the client's own range.