Skip to main content
← PROBLEMS / SYSTEM-DESIGN
An end-to-end domain learning journey

Mitigating 40K/s TCP TIME_WAIT Ephemeral
Port Exhaustion in API Gateways.

Resolve a 35% EADDRNOTAVAIL / 502 Bad Gateway outage on a 40,000 req/s API gateway caused by unpooled upstream TCP sockets exhausting all 28,232 Linux ephemeral ports in 60s TIME_WAIT.
Start the journey7 stages· Last modified Nov 26, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

256-socket Keep-Alive pooling + 64,511 ephemeral ports + `tcp_tw_reuse=1` eliminates `EADDRNOTAVAIL` at 40K+ req/s.

TL;DR30-second simplified summary
▾

Production Scenario #29's 35% EADDRNOTAVAIL failure was caused by missing HTTP/1.1 Keep-Alive headers pinning 28,232 ports in 60s TIME_WAIT.

Enabling 256-socket Keep-Alive pooling, widening ip_local_port_range to 1024..65535, and setting tcp_tw_reuse=1 eliminates port exhaustion.

Full walkthrough · 7 stages
01
foundation

Stage 1: Incident Triage — 35% EADDRNOTAVAIL at 30% CPU.

Why this matters: Diagnose ephemeral port exhaustion using ss -s, netstat, and gateway error logs.

When a gateway logs connect() failed (99: Cannot assign requested address) (EADDRNOTAVAIL) while CPU is 30%, run ss -s and ss -tan state time-wait | wc -l. Seeing ~28,232 TIME_WAIT sockets targeting the same upstream VIP confirms ephemeral port exhaustion.

FOUNDATION · INCIDENT TRIAGE

Identifying a 28,232-Socket TIME_WAIT Storm at 30% CPU

502 + EADDRNOTAVAIL(35%)Alert Symptomss -s / ss -tanKernel Proofip_local_port_rangePool LimitUnpooled UpstreamHTTPRoot CauseCompare vs port range

1.Check Inside Pod Netns: In Kubernetes, run ss -s inside the gateway pod's network namespace rather than the host node.

2.Check Conntrack Too: Verify dmesg for 'nf_conntrack: table full, dropping packet' if NAT/kube-proxy is in the path.

35% EADDRNOTAVAIL at 30% CPU with ~28,232 TIME_WAIT sockets in ss -s confirms unpooled outbound port exhaustion.

02
foundation

Stage 2: Fixing NGINX / Envoy Upstream Keep-Alive Pools.

Why this matters: Eliminate per-request socket teardown by enabling HTTP/1.1 Keep-Alive or HTTP/2 upstream pools.

In NGINX, setting upstream { keepalive 256; } alone STILL closes connections unless proxy_http_version 1.1; and proxy_set_header Connection ""; are configured (since HTTP/1.0 defaults to Connection: close). Enabling Keep-Alive reduces 40,000 req/s from 40,000 new sockets/sec down to 256 persistent reused sockets.

FOUNDATION · KEEP-ALIVE POOL

Fixing HTTP/1.1 Keep-Alive Headers & Upstream Pool Sizing

proxy_http_version1.1Header Fixkeepalive 256 PoolSocket PoolUpstream Timeout =65sRace Guard40K req/s on 256SocketsResolvedAlign idle timeouts

1.HTTP/2 Multiplexing: Upgrading upstream links to HTTP/2 or gRPC multiplexes hundreds of concurrent requests per TCP socket.

2.Keepalive_requests Cap: Rotating a pooled socket every 10,000 requests balances load across newly scaled upstream pods.

Enabling HTTP/1.1 Keep-Alive headers and a 256-socket pool cuts 40K/s socket churn to near zero.

03
intermediate

Stage 3: Sysctl Hardening (Port Range & tcp_tw_reuse).

Why this matters: Configure kernel sysctls safely for bursty fallback traffic and Kubernetes pod namespaces.

Apply net.ipv4.ip_local_port_range = 1024 65535 (64,511 ports), net.ipv4.tcp_timestamps = 1, and net.ipv4.tcp_tw_reuse = 1 via DaemonSet or pod securityContext.sysctls (for safe namespaced sysctls). Also set ip_local_reserved_ports for any daemon listen ports in the 1024..65535 range.

INTERMEDIATE · KERNEL SYSCTLS

Pod-Safe Sysctl Hardening for 64,511 Ephemeral Ports

ip_local_port_rang…Port Poolip_local_reserved_p…Listen Guardtcp_tw_reuse=1 +timestamps=1Reuse PolicyPod Netns SysctlInitK8s RolloutEnable PAWS reuse

1.2.3x Burst Runway: 64,511 ports sustain ~1,075 unpooled req/s per tuple during fallback bursts.

2.No Root-Only Unsafe Flags: ip_local_port_range is a namespaced sysctl allowed in Kubernetes pods once whitelisted on kubelet.

Widening ip_local_port_range with reserved listen ports and tcp_tw_reuse=1 adds safe kernel headroom in pod namespaces.

04
intermediate

Stage 4: Multi-IP SNAT Pool for > 64K Concurrent Connections.

Why this matters: Scale beyond 64,511 sockets to a single upstream VIP using multiple source IPs.

If long-lived WebSocket/SSE fan-out requires 200,000 concurrent connections to one upstream VIP, a single src_ip hits the 64,511-port ceiling. Attaching 4 secondary SNAT IPs (M = 4) expands unique 4-tuples to 4 * 64,511 = 258,044 sockets, using round-robin source IP selection.

INTERMEDIATE · MULTI-IP SNAT

Scaling Past 64K Concurrent Sockets via 4-IP SNAT Diversity

200K ConcurrentSocketsScale Target4 Secondary SNAT IPsIP PoolIP_BIND_ADDRESS_NO…Socket OptionSingle Upstream VIPTargetBind IP without port=0 lock

1.25% Safety Headroom: Provisioning 4 IPs for 200K connections leaves 22% headroom for rolling restarts and uneven hashing.

2.Multiple Upstream VIPs: Alternatively, resolving 4 upstream pod IPs directly (headless service) multiplies 4-tuples without extra SNAT IPs.

Multi-IP SNAT pools (or direct pod-IP load balancing) multiply 4-tuple capacity past 64,511 sockets per gateway.

05
intermediate

Stage 5: Conntrack Table Sizing & Bypass for High-Churn Nodes.

Why this matters: Prevent nf_conntrack table exhaustion when gateway pods sit behind Linux iptables/IPVS NAT.

Every TCP connection (including TIME_WAIT entries held for nf_conntrack_tcp_timeout_time_wait = 120s) consumes ~320 bytes in nf_conntrack. Scaling nf_conntrack_max to 1,048,576 (with hashsize = max / 4) or enabling eBPF/Cilium DSR or NOTRACK on high-rate internal VIPs prevents silent conntrack packet drops.

INTERMEDIATE · CONNTRACK GUARD

Preventing Silent nf_conntrack Table Drops on NAT Nodes

iptables /kube-proxy NATNAT Layernf_conntrack_max =1MTable Capconntrack_tw_timeo…= 30sGC TuningOr eBPF / NOTRACKBypassFast PathExpire TIME_WAIT flows

1.Silent Drop Hazard: When nf_conntrack fills, Linux drops new SYN packets silently—looking like mysterious 1s-3s TCP retransmit stalls.

2.320 MB for 1M Entries: Raising nf_conntrack_max to 1M costs only ~320 MB of kernel slab memory.

Sizing nf_conntrack_max=1M with matching hashsize or using eBPF bypass prevents silent NAT packet drops.

06
advanced

Stage 6: Graceful Draining & Avoiding Keep-Alive Race EOFs.

Why this matters: Coordinate upstream pod shutdowns and idle timeouts so pooled sockets never hit stale 502s.

When an upstream pod scales down or closes an idle Keep-Alive socket at the exact millisecond the gateway writes a new request onto it, the gateway receives an RST/EOF and returns HTTP 502. Setting gateway keepalive_timeout (55s) < upstream keepalive_timeout (65s) and enabling idempotent-only retry on GET/HEAD eliminates race 502s.

ADVANCED · KEEP-ALIVE RACE

Eliminating Stale-Socket 502s with Asymmetric Timeouts & Safe Retries

Gateway Pool (55sIdle)Client TimerUpstream Server (65sIdle)Server TimerSIGTERM preStopDrainGraceful ExitIdempotent SocketRetryZero 502sSignal graceful drain

1.10-Second Timeout Gap: A 10s gap (55s client vs 65s server) prevents simultaneous close/write race conditions.

2.Never Retry Non-Idempotent POSTs: Only retry a broken Keep-Alive socket on POST if 0 bytes were written or an Idempotency-Key is present.

Asymmetric idle timeouts (55s < 65s), graceful Connection: close draining, and safe EOF retries eliminate Keep-Alive 502s.

07
advanced

Stage 7: Load-Test Verification & Continuous Port SLOs.

Why this matters: Validate 40K+ req/s stability in staging and alert on TIME_WAIT regressions in production.

Before shipping, run a 10-minute 40K req/s soak test while asserting ss -tan state time-wait | wc -l < 500, zero EADDRNOTAVAIL, and < 1% new-connections-per-request ratio. In production, alert when TCP_tw / ip_local_port_range > 0.60 or TCPTimeWaitOverflow > 0.

ADVANCED · VERIFICATION & SLOS

40K Req/Sec Soak Verification & Production Port-Churn Alerts

40K Req/Sec SoakTestStaging GateAssert TIME_WAIT <500Reuse Checknode_sockstat_TCP_…Prod TelemetryZero EADDRNOTAVAILSLO MetPass CI release gate

1.Regression Detection: A single NGINX config refactor dropping proxy_http_version 1.1 spikes new_conns/RPS to 100% immediately in staging.

2.Zero 502s at 40K+ RPS: Persistent pooling + tuned sysctls keep open sockets < 500 and eliminate EADDRNOTAVAIL.

40K req/s soak assertions (TIME_WAIT < 500) and >60% port-range alerts prevent Keep-Alive regressions from reaching production.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

You added `keepalive 256;` to an NGINX `upstream` block, but `ss -s` still shows 28,000 `TIME_WAIT` sockets and `EADDRNOTAVAIL` errors. Why?

Recommended Learning Flow