The TCP CLOSE_WAIT Leak: Why Application Restarts Left Thousands of Sockets Hanging
When a remote peer closes a TCP connection, the OS kernel acknowledges the FIN and leaves the local socket in CLOSE_WAIT until the application closes its file descriptor. How missed EOF checks and unclosed HTTP client bodies exhaust system ulimits.
During an incident involving an outbound microservice gateway, operators noticed an alarming metric: despite traffic dropping after a downstream partner service restarted, the gateway node CPU remained elevated, outbound HTTP requests started throwing dial: too many open files (EMFILE), and memory slowly exhausted. Running diagnostic socket inspections revealed over 40,000 TCP sockets pinned permanently in the CLOSE_WAIT state.
Engineers often confuse TIME_WAIT with CLOSE_WAIT. While TIME_WAIT is managed automatically by the kernel on the active closer, CLOSE_WAIT represents an application-level bug on the passive closer. The kernel has fulfilled its side of the TCP contract and is waiting indefinitely for user-space code to release its file descriptor.
1. Anatomy of the TCP Passive Close Sequence
Terminating a standard TCP connection requires a four-step exchange between the two participating endpoints:
Active Closer (Remote Peer) Passive Closer (Local App)
--------------------------- --------------------------
(Sends FIN) --- [FIN, SEQ=100] ---> (Kernel receives FIN)
Kernel sends ACK back
(State: FIN_WAIT_2) <--- [ACK, SEQ=101] --- (State: CLOSE_WAIT)
|
[Application must close fd]
|
(Receives FIN) <--- [FIN, SEQ=300] --- (State: LAST_ACK)
Kernel sends ACK --- [ACK, SEQ=301] ---> (Socket Destroyed: CLOSED)
(State: TIME_WAIT)
When the remote peer closes its connection (or crashes and sends a FIN), the local Linux kernel immediately acknowledges that FIN with an ACK packet. The connection is now half-closed. The remote peer can no longer transmit data, but the local socket remains fully open for writing until the local program invokes the close() system call.
The socket transitions into CLOSE_WAIT. In this state, the OS kernel will never time out or automatically destroy the socket. It will stay in CLOSE_WAIT until the operating system process terminates or user-space closes the descriptor.
2. The Myth of net.ipv4.tcp_fin_timeout
A common misconfiguration during CLOSE_WAIT incidents is attempting to tune kernel sysctl parameters such as net.ipv4.tcp_fin_timeout:
# This sysctl does NOT help with CLOSE_WAIT:
sysctl -w net.ipv4.tcp_fin_timeout=15
The tcp_fin_timeout parameter only governs sockets in the FIN_WAIT_2 state on the active close side when waiting for the passive closer to shut down. The Linux kernel has no authority to close a CLOSE_WAIT socket on behalf of a running process because doing so would invalidate the process's file descriptor table behind its back. If an application holds 50,000 open descriptors in CLOSE_WAIT, the blame lies entirely in user-space code.
3. Root Causes in Modern Runtimes
How do applications forget to close sockets? The three most prevalent code patterns:
A. Unclosed HTTP Response Bodies in Go
In Go, an outbound HTTP call leaves the underlying TCP transport stream open for connection pooling unless the caller fully drains and closes the response body:
resp, err := httpClient.Do(req)
if err != nil {
return err
}
// BUG: If error handling or early returns bypass Close(), the socket leaks!
defer resp.Body.Close()
io.Copy(io.Discard, resp.Body)
If an early error check, panic, or unhandled status branch returns without calling resp.Body.Close(), the connection pool cannot recycle the socket, and when the remote server eventually terminates idle connections, the socket remains permanently stranded in CLOSE_WAIT.
B. Missing EOF Handling in Custom Socket Loops
In network daemons reading directly from raw TCP streams (Node.js, C++, Java NIO), receiving a FIN manifest as a read returning 0 bytes (EOF). If the event handler fails to register an end listener or ignores the n == 0 return value, the socket descriptor never gets closed:
// Node.js example: socket readable but end not handled
socket.on('data', (chunk) => {
processPayload(chunk);
});
// Missing socket.on('end', () => socket.end());
// When peer closes, socket stays in CLOSE_WAIT until process exit!
C. Deadlocked Worker Threadpool in Connection Pools
In Java (Apache HttpClient, HikariCP), if worker threads become blocked waiting on an internal queue or downstream lock while holding a checked-out connection, the pool cannot clean up connections that receive background peer disconnects, accumulating hundreds of CLOSE_WAIT handles.
4. Detection and Remediation Strategies
A. Real-Time Socket Audit Command
Inspect the distribution of socket states on production hosts using the high-performance ss tool:
# Count all sockets by state:
ss -s
# List top processes holding CLOSE_WAIT sockets:
ss -tap state close-wait | awk '{print $6}' | sort | uniq -c | sort -nr
B. Enforce Aggressive Idle and Read Timeouts
Never rely on default HTTP client configurations. Always establish explicit idle socket timeouts and keepalive probes to guarantee that stalled sockets are swept proactively:
// Go Transport with resilient timeouts
var transport = &http.Transport{
DialContext: (&net.Dialer{
Timeout: 5 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
IdleConnTimeout: 90 * time.Second,
ResponseHeaderTimeout: 10 * time.Second,
MaxIdleConns: 100,
MaxIdleConnsPerHost: 10,
}
Summary
Sockets in CLOSE_WAIT are unequivocal proof of leaked file descriptors in application code. When an upstream or downstream service restarts, healthy applications must immediately detect the incoming FIN, drain unread bytes, and invoke close(). Hardening response body handling, enforcing strict client timeouts, and monitoring ss -tan state close-wait protects critical services from file descriptor exhaustion.