Node.js + PM2 server exhausts ephemeral ports (TIME_WAIT) during traffic bursts causing upstream connection failures and 502s
Environment
Ubuntu 20.04 VMs running Node.js 14 behind HAProxy, PM2 process manager spawning 4 worker processes, kernel 5.4, sysctl at defaults for net.ipv4.ip_local_port_range and tcp_tw_reuse disabled
Symptoms
Under short high-concurrency bursts (thousands of clients), backend process fails to establish outbound connections to database/other services; HAProxy returns 502 for requests that require outbound calls. netstat shows local ports in TIME_WAIT accumulating and no free ephemeral ports.
Observations
ss -s shows tens of thousands of TIME_WAIT in the node process PID range. /proc/sys/net/ipv4/ip_local_port_range remains default 32768-60999. Node process logs show 'connect ECONNREFUSED' for outbound connections when ephemeral port exhaustion occurs. After burst subsides, ports free slowly and services recover.
Already attempted
Bumped ulimit -n, added connection pooling in app but still saw TIME_WAIT growth under synthetic load. Restarting PM2 clears TIME_WAIT quickly and restores service. Tried enabling tcp_tw_reuse=1 temporarily on one host with reduced failures.
Question
How can ephemeral port exhaustion from many short outbound connections by Node.js workers be prevented without restarting processes, and what kernel or app-level changes are safest in production?
Verified community troubleshooting
No answers yet..
Incident analysis
Most likely causes
Summary
Suggested Fixes
Continue troubleshooting
Related troubles
Matched from the title, description and tags
- Servers51% match
PM2-managed Node.js behind NGINX exhausts ephemeral ports (TIME_WAIT spike) during traffic bursts causing intermittent 502s
Open1 answer - Servers21% match
Nginx returns 502 Bad Gateway when proxying to local Node.js upstream intermittently
Open0 answers - Databases21% match
PgBouncer reports 'server closed the connection unexpectedly' during peak write bursts
Open0 answers - Web Development20% match
Next.js API processes hit 'Too many open files' under load behind PM2 — 500s only in production
Open0 answers - Databases20% match
PostgreSQL refuses new clients with 'too many connections' after scaling Node workers
Open1 answer