ML
Concurrency

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.

November 24, 202611 min readConcurrencyNetworkingSystem DesignScaling

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.

SharePostLinkedIn

Reader Discussion

7 replies// weighed in

TopNewestAuthor
Add to the thread
Disagree, agree harder, or share your own experience…
Email instead →markdown okbe kind
  1. Tomáš Havel· Senior EngineerAgrees

    go channels solve a problem you don't have until you have it, and then they're the only thing that solves it. people reaching for sync.Mutex everywhere are usually one refactor away from a clean channel topology.

    Nov 30, 2026·6 days later
  2. Irene Chen· Staff EngineerAgrees

    "push the check into the write" is now the framing I use teaching juniors. once you see check-then-act anti-patterns you can't un-see them — they're hiding in literally every internal tool we have.

    Nov 26, 2026·2 days later
  3. Bảo Trần🇻🇳 Cần Thơ· Software EngineerStory

    Bọn em từng deadlock cổ điển 2-row trong ledger. Ordering by account_id ASC trước khi lock — 1 dòng commit, drop deadlock retries 98% trong tuần. Nhớ mãi vì PR đó merge lúc mình về quê ăn Tết.

    Nov 27, 2026·3 days later
  4. Sofia Marquez· Backend LeadAgrees

    immutability as default is the single most under-rated concurrency advice. every nightmare I've debugged in 8 years comes back to someone mutating shared state "just this once." make wrong things hard to express.

    Nov 28, 2026·4 days later
  5. Hiếu Nguyễn· Full StackPushback

    tiny precision nit — volatile in Java provides visibility AND atomicity for single 32-bit reads/writes (long/double on legacy 32-bit JVMs is the exception). worth being precise because juniors read "visibility primitive" and reach for AtomicInteger when volatile is enough.

    Dec 01, 2026·1 week later·edited
  6. Léa Dubois· SREAsks

    any chance you'd publish these as a PDF collection? would love to print and read offline on flights. screen-fatigue is real.

    Nov 30, 2026·6 days later
  7. Ahmed Rahman· Full StackKind words

    concise + opinionated = my favourite kind of engineering post. so many blogs hedge every claim into mush. give me the spicy take with the receipts. more please.

    Nov 25, 2026·1 day later

Worked on something similar? Email ducminhldm@gmail.com — I read every one. The good ones become future posts.

Comments seeded · live discussion via email