TCP handshakes, TIME_WAIT states, and connection reuse
Understand TCP 3-way and 4-way handshakes, why TIME_WAIT lasts 2MSL, and how to diagnose ephemeral port exhaustion and fix it with HTTP connection pooling.
When outbound API calls spike and your backend starts throwing
Cannot assign requested addressor random multi-second delays, the root cause usually sits in the TCP connection lifecycle. This post walks through Linux handshake queues, whyTIME_WAITlasts 2MSL, how to diagnose port exhaustion, and how to fix it with proper connection pooling.
Environment reference: RFC 9293 (TCP), Linux Kernel 6.x, Spring Boot 3.x / Java 21.
TCP 3-way handshake and Linux kernel queues
TCP synchronizes sequence numbers (ISN) in both directions through a SYN -> SYN-ACK -> ACK 3-way handshake before entering the ESTABLISHED state. Inside the Linux kernel, every listening socket sits behind two separate queues that manage this transition:
- SYN Queue: Holds half-open
SYN_RECVconnections where the server has receivedSYNand sentSYN-ACK. Its capacity is influenced bynet.ipv4.tcp_max_syn_backlog. - Accept Queue: Holds fully established sockets after the final
ACKarrives. Its size is capped atmin(backlog, net.core.somaxconn), and entries only drain when the server process callsaccept().
When traffic spikes and the Accept Queue fills up, Linux’s default behavior (tcp_abort_on_overflow = 0) is to silently drop the client’s final ACK. The server assumes the packet was lost and retransmits SYN-ACK with exponential backoff (1 s, 2 s, 4 s). From the client’s perspective, the request stalls for several seconds even though the server never returned an error.
The 4-way close and why TIME_WAIT lasts 2MSL
Closing a TCP connection tears down each direction independently via a 4-way handshake. The side that sends the first FIN performs an Active Close; the side that receives it performs a Passive Close.
sequenceDiagram
participant C as Client
participant S as Server
C->>S: FIN (Active Close)
Note over C: FIN_WAIT_1
S-->>C: ACK
Note over S: CLOSE_WAIT
Note over C: FIN_WAIT_2
S->>C: FIN (Passive Close)
Note over S: LAST_ACK
C-->>S: Final ACK
Note over C: TIME_WAIT (2MSL = 60s)
Note over S: CLOSED
After sending the final ACK, the Active Close side doesn’t transition straight to CLOSED. It stays in TIME_WAIT for 2MSL—hardcoded in the Linux kernel as TCP_TIMEWAIT_LEN = 60 seconds—for two specific reasons:
- Protecting the final ACK: If the final
ACKgets lost on the network, the peer stuck inLAST_ACKwill retransmit itsFIN. If the Active Close socket had already vanished, the kernel would reply withRST, causing an abnormal close on the peer. HoldingTIME_WAITgives the kernel time to resend theACK. - Preventing stale packet corruption: If a new connection immediately reuses the exact same 4-tuple
(src IP, src port, dst IP, dst port), delayed packets from the old connection could arrive late and corrupt the new byte stream. Waiting 2MSL lets old segments drain from the network.
In incident rooms, TIME_WAIT and CLOSE_WAIT get mixed up constantly, even though they have opposite root causes and fixes:
| Dimension | TIME_WAIT | CLOSE_WAIT |
|---|---|---|
| Which side enters it | Active Close (initiated shutdown) | Passive Close (received FIN) |
| Root cause | Normal TCP close safety window | Application leaked close() on the socket |
| Lifetime | Automatically reclaimed after 2MSL (60 s) | Persists until the process exits |
| Failure symptom | Ephemeral port exhaustion | File descriptor (FD) exhaustion |
| Primary fix | HTTP Keep-Alive and connection pooling | Fix stream/client closing and timeouts |
Diagnosing ephemeral port exhaustion on Linux
A backend service that calls external APIs at high volume frequently acts as the Active Close side. For each outbound connection, Linux allocates an ephemeral port from net.ipv4.ip_local_port_range (default 32768 60999, giving 28,232 ports).
If your app opens and closes a fresh TCP connection on every request at 500 requests per second to the same (IP, port) destination, you accumulate ~30,000 TIME_WAIT sockets within 60 seconds. Once the port range runs dry, the kernel returns EADDRNOTAVAIL, and the JVM throws BindException: Cannot assign requested address.
You can check socket states, kernel limits, and Accept Queue overflows in seconds with ss, sysctl, and nstat:
1
2
3
4
5
6
7
8
9
10
11
# 1. Count sockets grouped by TCP state
ss -tan | awk 'NR>1 {cnt[$1]++} END {for (s in cnt) print s, cnt[s]}' | sort -k2 -nr
# 2. Count TIME-WAIT sockets pinned to a specific destination
ss -tan state time-wait dst 10.20.30.40:443 | wc -l
# 3. Inspect ephemeral port range, Accept Queue limits, and TIME_WAIT reuse flag
sysctl net.ipv4.ip_local_port_range net.core.somaxconn net.ipv4.tcp_max_syn_backlog net.ipv4.tcp_tw_reuse
# 4. Check cumulative Accept Queue overflows and drops
nstat -az TcpExtListenOverflows TcpExtListenDrops
Fixing port exhaustion with HTTP connection pooling
The real fix isn’t kernel tuning—it’s reusing ESTABLISHED sockets through HTTP Keep-Alive and a connection pool. Pairing Spring Boot 3.x’s RestClient with Apache HttpClient 5’s PoolingHttpClientConnectionManager eliminates both repeated 3-way handshakes and TIME_WAIT buildup.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// src/main/kotlin/com/example/config/HttpClientConfig.kt
package com.example.config
import org.apache.hc.client5.http.config.ConnectionConfig
import org.apache.hc.client5.http.impl.classic.HttpClients
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder
import org.apache.hc.core5.util.TimeValue
import org.apache.hc.core5.util.Timeout
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory
import org.springframework.web.client.RestClient
@Configuration
class HttpClientConfig {
@Bean
fun externalRestClient(builder: RestClient.Builder): RestClient {
val connConfig = ConnectionConfig.custom()
.setConnectTimeout(Timeout.ofSeconds(2))
.setSocketTimeout(Timeout.ofSeconds(5))
.setTimeToLive(TimeValue.ofMinutes(3))
.build()
val manager = PoolingHttpClientConnectionManagerBuilder.create()
.setDefaultConnectionConfig(connConfig)
.setMaxConnTotal(200)
.setMaxConnPerRoute(50)
.build()
val httpClient = HttpClients.custom()
.setConnectionManager(manager)
.evictExpiredConnections()
.evictIdleConnections(TimeValue.ofSeconds(30))
.build()
return builder
.requestFactory(HttpComponentsClientHttpRequestFactory(httpClient))
.build()
}
}
Two settings here matter most in practice:
maxConnPerRoute: Apache HttpClient’s default per-route cap is tiny (5 connections). If most of your outbound traffic hits one partner API or internal gateway, raisemaxConnPerRouteto match your concurrency target.evictIdleConnections: Set your client idle eviction shorter than the upstream server’s Keep-Alive timeout (for example, 30 s when Nginx is at 65 s or AWS ALB is at 60 s). Otherwise, the upstream closes the socket first, leaving your pool holding a half-closed connection that fails on the next request.
When not to rely on kernel tweaks and production pitfalls
Warning:
net.ipv4.tcp_tw_reuse = 1only allows outbound client connections to reuseTIME_WAITsockets after 1 second using TCP timestamps. Behind NAT gateways where multiple hosts share one public IP with unsynchronized clocks, timestamp mismatches can cause silent connection drops. The oldertcp_tw_recycleoption was removed in Linux 4.12 for the same reason.
Don’t reach for sysctl flags as your first move. Widening ip_local_port_range or enabling tcp_tw_reuse is a reasonable stopgap for short-lived CLI workers or legacy binaries that can’t pool connections, but it only hides a connection leak in a long-running backend. And if you see CLOSE_WAIT climbing instead of TIME_WAIT, no kernel parameter will help—check your application code to confirm every HTTP response InputStream is closed cleanly via use or try-with-resources.
Keep this diagnostic checklist handy during network incidents:
- Run
ss -tanfirst to separateTIME_WAIT(active close / no pooling) fromCLOSE_WAIT(unclosed streams). - Check
nstat -az TcpExtListenOverflowswhen clients report sudden 1 s or 3 s connect stalls. - Size
maxConnPerRouteandmaxConnTotalexplicitly on your HTTP client instead of relying on library defaults. - Keep client idle eviction strictly shorter than upstream proxy/load-balancer idle timeouts.