Fix NGINX/Envoy Keep-Alive headers (`proxy_http_version 1.1`), widen ephemeral ports to 64,511, and never use `tcp_tw_recycle`.
TL;DR30-second simplified summary▾
In Production Scenario #29, 40,000 outbound req/s hit 35% EADDRNOTAVAIL failures at 30% CPU because unpooled sockets pinned all 28,232 ports in 60s TIME_WAIT.
Enabling a 256-socket Keep-Alive pool, widening ip_local_port_range to 1024..65535, and setting tcp_tw_reuse=1 eliminates port exhaustion.
Stage 1: TCP 4-Way Teardown & Why TIME_WAIT Exists.
Why this matters: Understand the two RFC 9293 guarantees provided by the 60-second 2*MSL TIME_WAIT state.
When a client or gateway closes a TCP socket first (active close), it sends FIN, receives ACK/FIN, and transmits the final ACK. It must remain in TIME_WAIT for 2 * MSL (60s on Linux) so: (1) if the final ACK is dropped, it can retransmit it on FIN retry; and (2) stale in-flight packets expire before the same 4-tuple is reused.
Why the Active Closer Holds the 4-Tuple in 60s TIME_WAIT
1.Active vs Passive Closer: Only the side that initiates close() first enters TIME_WAIT; servers letting clients close first avoid holding TIME_WAIT.
2.470 req/s Ceiling: 28,232 default ports / 60s = 470.5 new connections/sec per (src_ip, dst_ip, dst_port) tuple.
The active closer holds TIME_WAIT for 60 seconds to retransmit lost final ACKs and drain delayed duplicate packets.
Stage 2: The 4-Tuple & Linux Ephemeral Port Exhaustion.
Why this matters: Explain why 28,232 ephemeral ports cap unpooled throughput per destination and trigger EADDRNOTAVAIL.
A TCP connection is uniquely identified by (src_ip, src_port, dst_ip, dst_port). When an outbound client connects to a single upstream VIP (dst_ip, dst_port) from one src_ip, only src_port varies—drawing from ip_local_port_range (32768..60999 = 28,232 ports). Once all 28,232 sit in TIME_WAIT, connect() fails with EADDRNOTAVAIL.
Saturating 28,232 Ephemeral Ports at 470+ Unpooled Req/Sec
1.Low-CPU Failure Signature: Port exhaustion returns EADDRNOTAVAIL immediately without burning CPU, appearing as 502s at ~30% CPU.
2.Conntrack Amplification: High TIME_WAIT churn can also fill nf_conntrack_max tables in Kubernetes/NAT nodes, dropping packets silently.
With fixed destination IP/port and one source IP, 28,232 default ephemeral ports saturate at 470 unpooled req/s.
Stage 3: HTTP Keep-Alive & Persistent Connection Pooling.
Why this matters: Eliminate socket churn completely by reusing a small pool of persistent TCP/HTTP2 connections.
The primary fix for TIME_WAIT exhaustion is never closing sockets per request. Configuring HTTP/1.1 Keep-Alive pools (e.g., 256 persistent connections) or multiplexed HTTP/2 / gRPC channels lets 40,000+ req/sec flow over 256 open sockets—dropping TIME_WAIT sockets from 28,232 to near zero while saving TLS/TCP handshake latency.
Serving 40,000 Req/Sec Over 256 Persistent Keep-Alive Sockets
1.Set Client Idle < Server Idle: Configure client pool idle timeout (e.g., 55s) shorter than server keepalive_timeout (65s) to prevent race-condition EOFs.
2.NGINX Upstream Trap: In NGINX, proxy_http_version 1.1 and proxy_set_header Connection "" are required or keepalive silently closes every socket!
Persistent HTTP Keep-Alive pooling (256 sockets) serves 40,000+ req/sec with zero TIME_WAIT churn.
Stage 4: Kernel Tuning — ip_local_port_range & tcp_tw_reuse.
Why this matters: Safely expand ephemeral port headroom and enable RFC 7323 timestamp-based TIME_WAIT reuse.
As a secondary defense for short-lived bursty clients, widen net.ipv4.ip_local_port_range = 1024 65535 (doubling capacity from 28,232 to 64,511 ports) and set net.ipv4.tcp_tw_reuse = 1 (or 2 for loopback-only), which safely reuses TIME_WAIT sockets for outbound connect() when TCP timestamps (tcp_timestamps = 1) prove the new packet is newer.
Widening Ephemeral Ports & Timestamp-Safe tcp_tw_reuse
1.Why tcp_tw_recycle Was Removed: tcp_tw_recycle broke behind NATs because clients share one IP with unsynchronized clocks, dropping legitimate SYNs.
2.Listen-Port Collisions: Reserve specific server listen ports (e.g., 8080, 9090) via ip_local_reserved_ports so outbound sockets don't grab them.
Widening ip_local_port_range to 1024..65535 and enabling tcp_tw_reuse=1 with timestamps adds safe outbound port headroom.
Stage 5: Multi-IP SNAT Diversity & 4-Tuple Scaling.
Why this matters: Scale past 64,511 sockets when connecting to a single upstream VIP using multiple source IPs or IP_BIND_ADDRESS_NO_PORT.
If a proxy legitimately needs > 64,511 concurrent connections to one (dst_ip, dst_port) (e.g., 200K WebSockets), a single src_ip cannot exceed 64K ports. Assigning M source IPs (SNAT pool or bind() across M IPs with IP_BIND_ADDRESS_NO_PORT) multiplies unique 4-tuples to M * 64,511.
Multiplying Port Capacity with Multi-IP SNAT & IP_BIND_ADDRESS_NO_PORT
1.IP_BIND_ADDRESS_NO_PORT: Calling bind(src_ip, port=0) without this flag locks the port globally across all destinations instead of per-destination 4-tuple!
2.Conntrack Sizing: Scale nf_conntrack_max proportionally when running multi-IP SNAT gateways.
Multi-IP SNAT pools paired with IP_BIND_ADDRESS_NO_PORT multiply outbound 4-tuple capacity to M * 64,511 sockets.
Stage 6: Avoiding SO_LINGER RST Anti-Patterns.
Why this matters: Explain why setting SO_LINGER(on, 0) to skip TIME_WAIT causes silent data corruption and connection resets.
Some developers try to bypass TIME_WAIT by setting SO_LINGER with l_linger = 0, forcing the kernel to send RST instead of FIN. That aborts unread buffered data on the peer, throws ECONNRESET in clients, and removes the 2*MSL duplicate-packet shield—corrupting subsequent connections on that port.
Why SO_LINGER(0) RST Bypasses Corrupt In-Flight Streams
1.Silent Payload Truncation: An immediate RST can wipe unread tail bytes in the peer's TCP receive buffer even after send() succeeded locally.
2.Valid RST Use Case: Only use RST when intentionally aborting a half-open or protocol-violating malicious connection.
Never use SO_LINGER(0) RST to bypass TIME_WAIT; it causes ECONNRESET failures and loses the 2*MSL duplicate-packet shield.
Stage 7: Live Socket Telemetry & Ephemeral Port Alerting.
Why this matters: Detect TIME_WAIT buildup early using ss -s, conntrack metrics, and port-utilization SLO alerts.
Export node_sockstat_TCP_tw and node_netstat_TcpExt_TCPTimeWaitOverflow from Prometheus node_exporter, alongside ss -tan state time-wait | wc -l and nf_conntrack_count / nf_conntrack_max. Alert at 60% ephemeral port utilization so teams fix Keep-Alive misconfigurations before EADDRNOTAVAIL 502s occur.
Monitoring TCP_tw, Conntrack & Pool Hit Rates Before 502s
1.New-Conn/Sec Ratio: If new outbound TCP connects/sec exceeds 1% of total RPS on an HTTP gateway, Keep-Alive pooling is broken.
2.Per-Container Namespace: Remember Kubernetes pods have isolated network namespaces—check ip_local_port_range inside the pod netns, not just the host.
Monitoring TCP_tw ratio, conntrack utilization, and new-connections/sec catches broken Keep-Alive pools before 502s hit.
Practice: Make the trade-off yourself.
With Linux's default `ip_local_port_range` (32768..60999 = 28,232 ports) and 60s `TIME_WAIT`, what is the maximum unpooled outbound RPS to a single `(dst_ip, dst_port)`?