CS › Web-Network

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.

TCP handshakes, TIME_WAIT states, and connection reuse

When outbound API calls spike and your backend starts throwing Cannot assign requested address or random multi-second delays, the root cause usually sits in the TCP connection lifecycle. This post walks through Linux handshake queues, why TIME_WAIT lasts 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:

  1. SYN Queue: Holds half-open SYN_RECV connections where the server has received SYN and sent SYN-ACK. Its capacity is influenced by net.ipv4.tcp_max_syn_backlog.
  2. Accept Queue: Holds fully established sockets after the final ACK arrives. Its size is capped at min(backlog, net.core.somaxconn), and entries only drain when the server process calls accept().

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 ACK gets lost on the network, the peer stuck in LAST_ACK will retransmit its FIN. If the Active Close socket had already vanished, the kernel would reply with RST, causing an abnormal close on the peer. Holding TIME_WAIT gives the kernel time to resend the ACK.
  • 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:

DimensionTIME_WAITCLOSE_WAIT
Which side enters itActive Close (initiated shutdown)Passive Close (received FIN)
Root causeNormal TCP close safety windowApplication leaked close() on the socket
LifetimeAutomatically reclaimed after 2MSL (60 s)Persists until the process exits
Failure symptomEphemeral port exhaustionFile descriptor (FD) exhaustion
Primary fixHTTP Keep-Alive and connection poolingFix 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, raise maxConnPerRoute to 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 = 1 only allows outbound client connections to reuse TIME_WAIT sockets 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 older tcp_tw_recycle option 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 -tan first to separate TIME_WAIT (active close / no pooling) from CLOSE_WAIT (unclosed streams).
  • Check nstat -az TcpExtListenOverflows when clients report sudden 1 s or 3 s connect stalls.
  • Size maxConnPerRoute and maxConnTotal explicitly on your HTTP client instead of relying on library defaults.
  • Keep client idle eviction strictly shorter than upstream proxy/load-balancer idle timeouts.

References

This post is licensed under CC BY 4.0 by the author.