FULL AI ANALYSIS

PM2-managed Node.js behind NGINX exhausts ephemeral ports (TIME_WAIT spike) during traffic bursts causing intermittent 502s

Generated Oct 29, 2026, 9:46:59 AM

Analysis summary

Symptoms point to ephemeral local port exhaustion on backend hosts used for outgoing upstream connections or for backend worker processes establishing many short connections to other services. Large number of TIME_WAIT sockets indicates many TCP connections are being closed actively by local side; default local ephemeral range plus TIME_WAIT timeout leads to port reuse exhaustion. Contributing factors include short-lived connection patterns, low ephemeral port range, long tcp_fin_timeout/tcp_tw_reuse/tcp_tw_recycle kernel settings, and possible lack of upstream connection reuse in Node.js HTTP clients. NGINX 502s occur when proxy cannot allocate local ephemeral port to connect upstream or when upstream actively refuses due to resource limits.

Possible causes

Default ephemeral port range too small for peak concurrent outbound connections leading to port exhaustion (TIME_WAIT sockets occupy ports).

85%

Application creates many short-lived outbound connections (no keepalive/reuse) from Node.js, causing local side to close and accumulate TIME_WAIT.

80%

Kernel TIME-WAIT timeout (tcp_fin_timeout/tcp_tw_timeout) set high, delaying port reuse and increasing TIME_WAIT count.

60%

NGINX upstream configuration not reusing keepalive connections (too many new upstream connects) increasing ephemeral usage.

55%

Suggested fixes

1

Diagnostic step 1

Measure outgoing connection count and TIME_WAIT with ss -s and ss -tanp during a controlled load test to reproduce and quantify limits.

2

Diagnostic step 2

Enable and configure keepalive reuse in Node.js HTTP clients (set agent.keepAlive = true and increase maxSockets) and in NGINX upstream (keepalive directive) to reduce new TCP handshakes.

3

Diagnostic step 3

Increase ephemeral port range: sudo sysctl -w net.ipv4.ip_local_port_range='20000 65000' and persist in /etc/sysctl.conf; monitor for improvement.

4

Diagnostic step 4

Tune TIME-WAIT behavior conservatively: consider enabling tcp_tw_reuse=1 (allow reuse for new outgoing connections) and reduce tcp_fin_timeout to 30–60s only after testing; do not enable tcp_tw_recycle on NATted servers.

5

Diagnostic step 5

If using many short client connections, consider introducing a local connection pool or sticky upstream micro-proxy to amortize sockets, or use HTTP/2 multiplexing where possible.