Why TIME_WAIT Connections Exhaust Your Server and How to Fix Them
TIME_WAIT is a TCP state that appears on the side actively closing a connection; when many sockets linger in this state, ports are exhausted, causing connection failures, and the article explains typical scenarios, underlying causes, kernel limits, and practical client‑ and server‑side solutions.
What is TIME_WAIT?
TIME_WAIT is a normal TCP state that appears on the side that actively closes a connection; many such states can prevent new connections.
Typical Scenarios
Microservice API calls: Service A frequently calls Service B without Keep-Alive.
Short connections: Applications open a new database connection for each query (e.g., MySQL without a connection pool).
Crawlers: Multi‑threaded web scrapers that close connections immediately after fetching.
Root Causes
Limited temporary port range (default 32768‑60999 on Linux). cat /proc/sys/net/ipv4/ip_local_port_range Each TIME_WAIT consumes a local port, quickly exhausting the range under high‑frequency connect/close cycles.
ss -ano | grep TIME-WAIT | wc -l # count
netstat: bind: Address already in use # new connection errorKernel Parameter Limits
tcp_max_tw_buckets: limits the maximum number of TIME_WAIT sockets (typically 18,000‑30,000); excess connections are dropped.
cat /proc/sys/net/ipv4/tcp_max_tw_bucketsSolutions
Client side
Enable port reuse: set net.ipv4.tcp_tw_reuse = 1.
Expand the local port range, e.g., net.ipv4.ip_local_port_range = 1024 65000.
Use persistent connections (Keep‑Alive) to reduce connection churn.
Server side
Reduce FIN timeout: net.ipv4.tcp_fin_timeout = 30 (default 60 s).
Increase file‑descriptor limits to avoid exhaustion.
Key Takeaways
The side that initiates closure enters TIME_WAIT for twice the maximum segment lifetime (≈2 minutes).
Ports held by TIME_WAIT cannot be reused until the state expires.
Linux supports up to 65,535 ports; excessive TIME_WAIT can cause “address already in use” errors.
Adjust kernel parameters and application design (e.g., keep‑alive, connection pooling) to mitigate the issue.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Efficient Ops
This public account is maintained by Xiaotianguo and friends, regularly publishing widely-read original technical articles. We focus on operations transformation and accompany you throughout your operations career, growing together happily.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
