Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Operations 68 min read

Linux TCP TIME_WAIT Tuning: Root-Cause Analysis & Multi-Layer Fixes

This article provides a systematic troubleshooting guide for excessive Linux TCP TIME_WAIT states, covering root-cause identification via packet capture, application-layer fixes like Nginx keepalive and connection pools, kernel parameter tuning (tcp_tw_reuse, port range), and architectural solutions such as multi-target IP distribution, with verification commands and rollback procedures.

1. Problem Background

A gateway server experienced intermittent 502 errors during peak hours with java.net.BindException: Cannot assign requested address. The ss -s output showed 380,000 TIME_WAIT connections, and kernel logs reported TCP: time wait bucket table overflow. This is a classic backend operations issue often oversimplified as "tune a kernel parameter", but the real fix requires identifying which side holds TIME_WAIT, who initiates active close, and why connection count is so high before deciding on application, parameter, or architecture changes.

2. Applicable Scenarios

Server ss -ant state time-wait | wc -l stays in hundreds of thousands with errors, memory growth, port exhaustion.

Load testing with curl /short-connection scripts reports cannot assign requested address or EADDRNOTAVAIL.

Nginx as client (proxy_pass) throughput limited by connection establishment.

Java/Go/Python services creating new TCP connection per request.

Post-deploy/restart/health-check spikes causing secondary failures.

LVS FullNAT or cloud LB backend TIME_WAIT buildup.

Containerized Pods via NodePort/ClusterIP accumulating TIME_WAIT on node or Pod.

Not applicable: SYN queue overflow, CLOSE_WAIT buildup (application bug), RST storms.

3. Core Concepts

3.1 Which Side Holds TIME_WAIT

TIME_WAIT appears on the active closer (the side sending the first FIN). The passive closer goes directly to CLOSED after the final ACK. "Server" does not equal "passive closer"; e.g., Nginx closing idle keepalive connections becomes active closer.

3.2 Why TIME_WAIT Exists

Ensure final ACK delivery: if passive side's FIN is unacknowledged, it retransmits; active side must retain the 4-tuple to reply ACK, else RST causes peer errors.

Let delayed segments expire: wait 2MSL (Linux hardcodes TCP_TIMEWAIT_LEN = 60s, not tunable via sysctl) so old segments vanish before 4-tuple reuse.

Packet-level experiment: tcpdump a single curl request shows full handshake and FIN sequence; ss -ant state time-wait 'dport = :8000' lists the connection occupying local port for 60s. Reusing connection via curl http://... http://... yields only one TIME_WAIT.

3.3 TIME_WAIT Resource Accounting

Client-side (outbound): consumes local ephemeral ports. For a single targetIP:targetPort, max concurrent TIME_WAIT = ephemeral port count (default ~28,232 ports for 32768-60999). Formula: new_connections_per_sec * 60 > port_count → port exhaustion ( Cannot assign requested address). Example: 28,232 ports / 60 ≈ 470 new connections/sec per target. Expanding range to 10000-64999 (55k ports) raises limit to ~916/sec but doubles kernel socket memory.

Server-side (inbound): consumes kernel socket memory, not listening port. Risks: memory pressure, tcp_max_tw_buckets overflow, sockstat orphan/inuse misjudgment. Common causes: server actively closing keepalive connections, process restarts, frequent health checks.

3.4 Kernel Parameters & Common Misconceptions

net.ipv4.tcp_fin_timeout

: controls FIN_WAIT_2 timeout (default 60s), cannot shorten TIME_WAIT. net.ipv4.tcp_tw_reuse: allows reusing TIME_WAIT sockets for new outbound connections ; requires tcp_timestamps=1 (PAWS mechanism). Ineffective for inbound. net.ipv4.tcp_tw_recycle: fast recycle; removed in Linux 4.12 due to NAT timestamp inconsistency causing massive drops. Any guide suggesting it is obsolete. net.ipv4.tcp_max_tw_buckets: TIME_WAIT table cap (default ~262144). Exceeding triggers forced recycle and TCP: time wait bucket table overflow logs. It's a safety fuse, not an optimization; lowering sacrifices reliability. net.ipv4.ip_local_port_range: ephemeral port range, directly sets client-side port space ceiling. net.ipv4.tcp_timestamps: enables TCP timestamps; required for

tw_reuse</strong>. Generally keep enabled.</li><li><code>net.core.somaxconn

, net.ipv4.tcp_max_syn_backlog: accept/SYN queues; unrelated to TIME_WAIT but needed when debugging connection refusals.

Two hard rules: tcp_fin_timeout does not affect TIME_WAIT; tcp_tw_recycle is gone — upgrade kernels <4.12.

3.5 SO_LINGER & RST: Shifting Burden, Not Solving

Setting SO_LINGER {on=1, linger=0} sends RST instead of FIN, avoiding TIME_WAIT locally. Costs: peer receives RST (logs connection reset), unacknowledged data discarded. Only acceptable for fire-and-forget traffic (stats reporting); never for DB, RPC, MQ.

3.6 Distinguishing Other States

Table mapping state → side → cause → normal/abnormal. Key: CLOSE_WAIT on passive side means application didn't call close() — a bug. Diagnose with ss -antp state close-wait to find offending PID, then inspect FD count and code.

4. Overall Troubleshooting & Implementation Flow

Goal: eliminate port exhaustion/overflow, stabilize TIME_WAIT at acceptable level
 1. Environment assumptions & pre-check (connection inventory, topology)
 2. Determine role: TIME_WAIT outbound or inbound? Peer?
 3. Identify active closer: tcpdump FIN exchange
 4. Application-layer fixes (highest priority): keepalive, connection pools, health-check frequency, client connection reuse
 5. Kernel parameters (fallback): tw_reuse / port range / max_tw_buckets / queue params
 6. Architecture (long-term): multi-target IP distribution, LVS FullNAT, long-connection refactor, pool sharding
 7. Verification & observation (metrics regression, load-test re-run, canary comparison)
 8. Risks & rollback (each change independently reversible)
 9. Maintenance advice & postmortem

Core principle: First reduce connection count, then widen parameters, finally consider protocol behavior changes (RST/recycle).

5. Practical Steps

5.0 Assumptions

OS: CentOS 7/Stream, Ubuntu 20.04+, Rocky 8/9; kernels 3.10 or 4.x/5.x/6.x. Differences noted.

Role: machine is Nginx gateway (server downstream, client upstream), downstream services on port 8080.

Privileges: root/sudo for sysctl, ss -p.

Change discipline: backup → single-parameter canary → observe → persist; never dump ten params into /etc/sysctl.conf and run sysctl -p.

5.1 Pre-check: Connection Inventory

ss -s

gives overview (example: timewait 380105, estab 18234, ratio 20:1 indicates mostly short connections). ss -ant state time-wait | tail -n +2 | wc -l precise count. cat /proc/net/sockstat shows tw and mem (pages, 4KB each; e.g., mem 9214 ≈ 36MB). dmesg -T | grep -i 'time wait' reveals overflow logs — proof that reliability is already compromised.

5.2 Role Determination: Outbound vs Inbound

Outbound (client): ss -ant state time-wait 'dport = :8080'. Inbound (server): ss -ant state time-wait 'sport = :443'. Aggregate peer distribution:

ss -ant state time-wait | tail -n +2 | awk '{print $5}' | sed 's/:[0-9]*$//' | sort | uniq -c | sort -rn | head -20

. Logic: outbound dominant + concentrated targets → client port exhaustion → prioritize connection reuse + tw_reuse + port expansion. Inbound dominant + concentrated peers → likely few callers storming short connections or server keepalive timeout; confirm with packet capture.

5.3 Identify Active Closer: Capture FIN Exchange

tcpdump -i any -nn "tcp port 8080 and '(tcp[tcpflags] & (tcp-fin) != 0)'" -c 200 -w /tmp/handshake.pcap

. If gateway sends Flags [FIN.] first → gateway actively closes (check connection pool idle timeout, HTTP keepalive). If peer sends Flags [F.] first → upstream actively closes (upstream keepalive timeout, pool limit). RST storms indicate different issues (process restart, firewall).

5.4 Application Fix 1: Enable HTTP Keepalive Upstream (Nginx)

Nginx defaults to HTTP/1.0 per-request connections. Must configure upstream block with

keepalive 64; keepalive_requests 1000; keepalive_timeout 60s;

and in location: proxy_http_version 1.1; proxy_set_header Connection "";. Reload with nginx -t && nginx -s reload. Critical: client idle timeout < server keepalive_timeout (client closes first) to avoid server-side TIME_WAIT spikes. Verify: ss -ant state established 'dport = :8080' | wc -l should stabilize; 30-sec TIME_WAIT increment should drop an order of magnitude.

5.5 Application Fix 2: Client Connection Pools

Root cause: each request creates new TCP connection. Examples: HikariCP (MySQL) with max-lifetime < MySQL wait_timeout; Apache HttpClient PoolingHttpClientConnectionManager with setDefaultMaxPerRoute; Python requests.Session() with HTTPAdapter pool. Verify same 30-sec TIME_WAIT increment metric.

5.6 Application Fix 3: Reduce Health Check & Monitoring Frequency

Self-inflicted: Prometheus node_exporter (9100), custom scripts. Check

ss -ant state time-wait | tail -n +2 | awk '{print $5}' | awk -F: '{print $NF}' | sort | uniq -c | sort -rn | head

. Fix: use keepalive in collectors, batch probes, lower frequency.

5.7 Kernel Parameter Tuning (After Application Fixes)

Baseline current values:

sysctl net.ipv4.ip_local_port_range net.ipv4.tcp_tw_reuse net.ipv4.tcp_timestamps net.ipv4.tcp_max_tw_buckets net.core.somaxconn net.ipv4.tcp_max_syn_backlog

.

Expand ephemeral port range (outbound first): sysctl -w net.ipv4.ip_local_port_range="10000 65000" (~55k ports). Risk: conflict with local listening ports; verify with ss -lntu. Persist in /etc/sysctl.d/99-tcp-timewait.conf.

Enable tcp_tw_reuse (outbound only, needs timestamps): sysctl -w net.ipv4.tcp_tw_reuse=1. Verify tcp_timestamps=1. Risk: rare timestamp anomalies cause connection issues; canary only. Rollback: sysctl -w net.ipv4.tcp_tw_reuse=0.

tcp_max_tw_buckets (safety fuse, not optimization): default usually fine; raising allows more memory, lowering sacrifices reliability. Only adjust with capacity calculation.

somaxconn (indirect): only if netstat -s shows growing ListenOverflows.

Persist config in /etc/sysctl.d/99-tcp-timewait.conf and apply with sysctl -p /etc/sysctl.d/99-tcp-timewait.conf.

5.8 Architecture-Level Fixes

Multi-target IP distribution: split traffic across multiple VIPs or direct backend IPs to multiply 4-tuple space.

LVS FullNAT / cloud LB: verify address translation with ipvsadm -Ln; don't infer role from RS-viewed peer IP.

Kubernetes: SNAT causes Node-port exhaustion when Pods access Service ClusterIP. Mitigations: service.topologyKeys, headless Service + client-side LB, expand Node port range, hostNetwork (reduces isolation).

Long-connection refactor: gRPC, connection pools, message queues — ultimate solution.

5.9 Attribute TIME_WAIT to Process

Outbound TIME_WAIT lacks direct PID. Infer from active connections:

ss -antp state established 'dport = :8080' 2>/dev/null | grep -oP 'users:(("")[^"]+' | sort | uniq -c | sort -rn

. Dominant process → check its pool config (Java -D, Go http.Transport, C++ socket options). Long-term: eBPF funccount 'tcp_v4_connect' -i 5 or nstat delta for connection rate.

5.10 Load Test Reproduction & Capacity Validation

Tools: hey -z 60s -q 200 -disable-keepalive http://target (forces short connections) while watching

watch -n 2 'ss -ant state time-wait dport = :8080 | tail -n +2 | wc -l'

. Python script to saturate port space and observe EADDRNOTAVAIL threshold. Formula:

max_new_connections_per_sec ≈ available_ephemeral_ports / 60

(e.g., 28,232 ports → ~470/sec). Document in capacity docs.

6. Command Cheatsheet

Key commands for state counts, peer aggregation, process attribution, parameter inspection, kernel counters ( nstat, netstat -s), continuous watch, sar history, FIN capture. Note: ss -antp needs root; nstat / netstat -s read /proc/net/snmp, /proc/net/netstat.

7. Configuration Templates

Complete /etc/sysctl.d/99-tcp-timewait.conf with comments explaining each item's precondition. Nginx upstream capacity calc: worker_processes * upstream_servers * keepalive = max idle connections; verify with ss -ant state established 'dport = :8080' | wc -l.

8. Log & Metric Observation

Monitor during change window: (1) TIME_WAIT level via ss -s every 10s — compare slope before/after. (2) Kernel overflow logs:

journalctl -k --since "1 hour ago" | grep -c 'time wait bucket'

should be zero. (3) App connection failures ( Cannot assign requested address) count → zero. (4) Kernel counters via nstat delta: TcpExtTCPTimeWaitElapsed (per-sec TIME_WAIT entries), TcpActiveOpens (per-sec new connections) — both should drop with app fixes. (5) Memory:

/proc/net/sockstat
tw

and mem together; tcp_mem pressure thresholds (pages). (6) Peer error rate: watch for connection resets when tw_reuse enabled. Prometheus metrics: node_sockstat_TCP_tw, node_netstat_Tcp_CurrEstab, node_netstat_TcpExt_ListenOverflows, node_netstat_TcpExt_TCPTimeWaitElapsed.

9. Full Incident Walkthrough (Closed-Loop Postmortem)

Real case: gateway 502s, BindException, ss -s 380k TIME_WAIT, 370k outbound to 2 VIPs, dmesg overflow, ListenOverflows stable. nstat showed TcpActiveOpens ~6500/sec matching QPS → every request new connection. tcpdump confirmed gateway sent FIN first. Nginx config missing upstream keepalive trio and proxy_http_version 1.1. Fix: enable keepalive, reload. Result: ESTAB stable ~1800, 30-sec TIME_WAIT increment from ~200k to <3000, BindException gone, TcpActiveOpens down >90%. Rollback: config backup + nginx -s reload; sysctl baseline restore. Postmortem: TIME_WAIT alert is capacity issue — single VIP limit = ephemeral_ports/60 ≈ 500 new/sec. Future: long-connection refactor, multi-IP distribution. Joint alert: node_sockstat_TCP_tw + app connection failures + kernel overflow.

10. Risk Warnings

Table mapping operation → risk → prerequisite → rollback. Three red lines: (1) Never set SO_LINGER{1,0} for DB/RPC/MQ. (2) Never try tcp_tw_recycle (deleted in new kernels, fatal in old). (3) Never treat "raise tcp_max_tw_buckets " as fix for overflow — overflow means short-connection runaway, fix at app layer.

11. Validation Checklist

Parameter effective:

sysctl -a | grep -E 'tw_reuse|ip_local_port_range|timestamps'

matches; reboot or sysctl --system confirms persistence.

Functional: load test reproduces pre-fix failure scenario; Cannot assign requested address absent.

Effect: same-period comparison of TIME_WAIT level, TcpActiveOpens rate, 30-sec increment — all order-of-magnitude lower.

Side-effects: 30-min watch — peer no new connection resets; TcpExtListenDrops, retransmits stable.

Rollback drill: on canary node execute "restore baseline + reload", confirm path works and time acceptable.

12. Rollback Procedures

Independent per layer: Nginx ( cp backup && nginx -t && nginx -s reload), sysctl (

sysctl -w param=baseline; mv /etc/sysctl.d/99-tcp-timewait.conf /root/...disabled; sysctl --system

), iptables (backup iptables -S, delete specific rules with -D, never -F), app pool config (config revert + rolling restart). Pre-agree triggers: new-connection success rate drop, peer reset spike, retransmit surge.

13. Production Notes

No kernel changes during peak; sysctl immediate, no graceful transition.

Single-parameter canary, one node at a time.

Container/Cloud sysctl boundaries: namespace-limited params in container; host-namespace params need privileged pod or node-level; K8s SecurityContext.sysctl whitelist only.

Cloud LB/security groups unaffected by local params; health checks add steady TIME_WAIT.

Archive evidence: ss -s, nstat, dmesg before/after in ticket.

Alert on combined conditions: TIME_WAIT slope anomaly + app connection failures + kernel overflow.

Bake fixes into image/init scripts (Ansible, cloud-init).

Kernel version consistency: group by uname -r before mass changes. sysctl does NOT require network restart; systemctl restart network is unnecessary risk.

Remote changes: keep out-of-band access (VNC/serial) in case firewall misconfig locks you out.

14. Appendix A: Periodic Inspection Script

Bash script /usr/local/bin/tcp_tw_check.sh collects TIME_WAIT, ESTAB, overflow count (last 10min), TcpActiveOpens / TCPTimeWaitElapsed rates; logs baseline every run; alerts if thresholds exceeded (configurable via env). Deploy via cron with PATH fix; logrotate daily keep 14 compressed. Sample log shows normal ~40k TIME_WAIT, 6.5k/sec active opens; alert lines at 14:02 with 380k TIME_WAIT and 23 overflows. Parameter change template for audit trail.

15. Appendix B: FAQ Highlights

High TIME_WAIT without errors → no action needed; act only with port exhaustion, overflow logs, memory pressure, or rate near ports/60.

Server-side TIME_WAIT high, client clean → hidden cost (memory, overflow risk); check server keepalive timeout vs client pool lifetime.

ss -s
closed

≠ TIME_WAIT; includes many states.

Cannot shorten TIME_WAIT (hardcoded 60s). tcp_tw_reuse + timestamps = safe via PAWS; risk only if middlebox strips timestamps. tw_reuse applies to all outbound (DB, Redis too); still canary.

If sysctl -w changed but test still fails: (a) existing 60-sec TIME_WAIT must drain, (b) param not actually applied (container/namespace).

Container vs host: separate network namespaces; SNAT moves TIME_WAIT to host.

Don't lower port range below 1024 (system reserved).

TIME_WAIT doesn't directly slow accept; only via tcp_mem pressure.

Linux uses 60s not 120s (2MSL) for capacity math.

Both ends having TIME_WAIT is normal with long connections; abnormal if rate tracks request volume.

Different TIME_WAIT on identically configured nodes → traffic/pool/release differences, not params. conntrack table full often co-occurs; expand both together.

Firewall session timeout >60s can block new SYNs even after local port free.

Alert thresholds: baseline P99 * 1.5-2 for warning, *3 for critical; plus hard conditions (overflow log, app failures). worker_connections not a TIME_WAIT capacity metric.

Nginx restart spikes TIME_WAIT (all connections closed); reload avoids it. tw_reuse irrelevant if pool sized correctly (no new connections).

No kernel param forces long connections without code/gateway/sidecar changes.

16. Appendix C: Scenario-to-Fix Mapping

Table: Gateway port exhaustion (client) → upstream keepalive trio → port expand + tw_reuse; SDK no pool (client) → push connection reuse → same fallback; Server keepalive kick (server) → align idle timeouts (client < server) → evaluate max_tw_buckets; Deploy/restart storm (server) → graceful drain + pre-warm → accept spike, suppress alert; K8s Node SNAT exhaustion → expand Node ports / direct Pod IP / IPVS → client-side LB; Health-check storm → merge, lower freq, long-conn; Monitoring scripts → reuse connections; DB pool lifetime > wait_timeout → max-lifetime < wait_timeout.

17. Summary

TIME_WAIT on active closer, fixed 60s; count = active_closes_per_sec * 60 → traffic structure problem, not a toggle.

Client bottleneck = ephemeral port space; Server cost = memory & table overflow. tcp_fin_timeout doesn't shrink TIME_WAIT; tcp_tw_recycle deleted; tcp_max_tw_buckets is fuse; tcp_tw_reuse outbound-only + timestamps.

Fix order: long-connections/pools → port range/reuse params → architecture distribution → RST only as last-resort isolation.

Every step needs evidence chain: FIN capture for direction, nstat for rate, 30-sec increment for effect, app failures for regression, rollback drill before full rollout.

One-liner: Fix TIME_WAIT by fixing short connections; parameters are seatbelts, not steering wheels.

Appendix D: Error-to-Cause Quick Reference

Table mapping observed error ( Cannot assign requested address, Go/Java variants, TCP: time wait bucket table overflow, Connection reset by peer, deploy-window spike, missing tcp_tw_recycle, Pod-only failure) → probable meaning → first verification command.

Appendix E: Additional Q&A

Covers tcp_tw_reuse vs SO_REUSEPORT (unrelated), eBPF forced TIME_WAIT deletion (equiv to lowering max_tw_buckets, banned), LB+nginx keepalive segments (each hop independent), ss vs netstat (trust ss), port-range-only expansion math (new_ports/60 rate increase, memory doubles), TIME_WAIT performance impact (only under memory pressure), 60s vs 120s, dual-end TIME_WAIT normalcy, node variance reasons, conntrack correlation, firewall session table interference, alert threshold methodology, worker_connections relation, restart vs reload spike, tw_reuse with HTTPS pools, non-code long-connection enforcement (gateway/sidecar/peer config only).

Appendix F: Postmortem Checklist

[ ] TIME_WAIT count & direction archived with top peers.

[ ] Active closer determined via pcap.

[ ] Rate evidence: TcpActiveOpens / TCPTimeWaitElapsed match request volume.

[ ] Root cause tier identified (app/param/arch).

[ ] Change records: each sysctl/config independently reversible with baseline.

[ ] Rollback drill executed on canary.

[ ] Effect verified: 30-sec increment, connection failures, peer resets all regressed.

[ ] Alerts improved: baseline thresholds, overflow + app logs in joint alert.

[ ] Templates updated: Ansible role / image baseline.

[ ] Capacity doc: single-target max new rate = ports/60 recorded.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

TroubleshootingTIME_WAITsysctlconnection poolingport exhaustionkernel parametersLinux TCP tuningNginx keepalive

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion