CLOSE_WAIT means the peer finished and this host never called close. Reproduce it on loopback, find the leaking pool and fix it in the application.
The state name already tells you whose bug it is
A service that calls the stock system at Belgavi's Book Store starts failing after a few days of uptime with errors about too many open files. Someone runs netstat or ss on the host and finds thousands of connections in CLOSE_WAIT to the stock system's port. The usual first reaction is to look for a kernel setting that makes them expire. There is none worth changing, because CLOSE_WAIT is not a network condition. It is a program that has not called close.
RFC 9293, the current TCP specification, defines the state in one line: CLOSE-WAIT represents waiting for a connection termination request from the local user. The remote side has already sent FIN, meaning it has finished sending. TCP has acknowledged that FIN and is now waiting for the application on this host to say it is finished too. Until the application closes the socket, the connection stays in CLOSE_WAIT, with its file descriptor, buffers and kernel state. This guide reproduces the state on loopback, shows how a connection pool leaks it, and gives the fix and the checks.
Walk the close handshake once
TCP connections close in each direction separately. The side that closes first is the active closer. Its close sends FIN and moves it to FIN_WAIT_1, and when the peer acknowledges, to FIN_WAIT_2. The peer that receives the FIN moves to CLOSE_WAIT and its application sees end of file: a read returns zero bytes. When that application calls close, its TCP sends its own FIN and moves to LAST_ACK, and once the active closer acknowledges, the passive side is gone. The active closer waits in TIME_WAIT for twice the maximum segment lifetime before it, too, disappears.
So the two states that accumulate tell different stories. Many TIME_WAIT entries on a host mean this host closed many connections first; that is normal and bounded by the TIME_WAIT duration. Many CLOSE_WAIT entries mean peers closed connections and this host never did. The second number has no natural bound. It grows until the process runs out of descriptors.
Reproduce it on loopback
The companion probe opens five loopback connections whose server side closes immediately, keeps the client sockets open, and reads the states from netstat on Windows 11. One recorded run:
after server close, client open: {'client CLOSE_WAIT': 5, 'server FIN_WAIT_2': 5}
recv on first client returns b''
after reading EOF but not closing: {'client CLOSE_WAIT': 5, 'server FIN_WAIT_2': 5}
after client close(): {'server TIME_WAIT': 4}Two details matter. Reading end of file did not change anything: the first client's recv returned an empty byte string, and that socket stayed in CLOSE_WAIT. Seeing EOF is not closing. Only close moved the sockets on, after which the client entries vanished and the server side showed TIME_WAIT. netstat snapshots are not atomic, and this run listed four of the five TIME_WAIT entries; an earlier run also showed transitional states. Read the counts as a picture of the handshake, not as an exact census.
On Linux, ss -tan state close-wait lists the same connections, and ss -tanp adds the owning process, which is usually the fastest way to find the culprit.
How a pool leaks half-closed sockets
Almost nobody writes code that reads EOF and then forgets to close. The common source is a keep-alive connection pool. The stock service closes connections that have been idle for a while, as most HTTP servers and proxies do. The client pool keeps idle connections for reuse and only looks at one when a request needs it. If traffic is bursty, the pool opens several connections during a burst, they go idle afterwards, the server closes them, and the pool never touches them again. Each becomes a CLOSE_WAIT entry that lives as long as the pool does.
The companion example builds that pool against a local stub of the stock service with a short idle timeout. Five bursts of four concurrent requests leave the buggy pool holding 20 idle sockets, all 20 already closed by the server. The fixed pool checks idle sockets before reuse and on a periodic sweep.
# Author: Sandeep Belgavi. Detect a peer that has finished sending without consuming data.
def peer_closed(s: socket.socket) -> bool:
s.setblocking(False)
try:
return s.recv(1, socket.MSG_PEEK) == b"" # EOF: the peer sent FIN
except BlockingIOError:
return False # nothing to read: still open
except OSError:
return True # reset or error: also unusable
finally:
s.setblocking(True)After the same bursts the fixed pool holds no sockets at all. The check also prevents a second bug: reusing a socket whose peer has gone produces a failed request. In the example's tests the buggy pool's second request on a dead socket either reads end of file or raises a connection error, depending on the platform; on Windows 11 it raised ConnectionAbortedError. The fixed pool skips the dead socket and succeeds.
Where to look in real code
HTTP client response bodies are the classic case in Java and Go. A response whose body is never read to the end or closed can pin its connection, and depending on the client, the connection is neither returned to the pool nor closed. Always close the response in a finally block or a try-with-resources statement, including on error paths and when you only need the status code.
Exception paths are the next most common. A handler that opens a socket, gets an exception from a parser and returns without closing leaks one connection per failure. Under an error storm the leak rate follows the error rate. Make the close unconditional with a context manager or try-with-resources rather than relying on every branch.
Pools with no idle eviction are the third. Most mature HTTP client libraries have an idle-connection eviction setting, sometimes off by default. Set the client's idle timeout below the server's, so the client closes first and the server never sees a half-closed peer.
Finally, a process that hands a socket to another component and loses track of it, such as a websocket upgraded and then abandoned by a framework, shows up the same way. ss -tanp names the process; a heap dump or descriptor listing then names the object.
The other side of the connection
The stock service is not harmed in the same way. Its sockets were closed by its own code, so they sit in FIN_WAIT_2 waiting for the client's FIN, and operating systems limit how long an orphaned connection may stay there. The client's CLOSE_WAIT sockets have no such limit, because the application still owns them. That asymmetry is why the leak shows up on the client host first, often as descriptor exhaustion in the client process while the server looks healthy. A server that sends a Connection: close header before closing gives the client fair warning; a client that ignores it still has to close its end.
Why kernel tuning does not help
Settings such as the FIN timeout govern how long the active closer waits in FIN_WAIT_2 for the peer's FIN, not CLOSE_WAIT. TCP keepalive probes can detect a dead peer on an idle connection, but a peer that sent FIN is not dead; it is waiting politely for you. Raising the open-file limit buys time and hides the leak until the next limit. The only fix that holds is closing the socket in the application.
Monitor it
Export the count of CLOSE_WAIT connections per process as a metric and alert on sustained growth, not on a fixed threshold, because a busy service legitimately has a few in transit at any moment. Track open file descriptors per process alongside it; when both climb together, the leak is sockets. Record the remote endpoint for the top entries, because the peer's identity usually points straight at the client code that talks to it.
Verification checklist
Reproduce the leak in a test: run the client against a stub server that closes idle connections quickly, drive bursty load, and assert that the number of half-closed sockets the client holds returns to zero after a sweep. Run the same test against every HTTP or database client configuration you ship, because idle eviction settings differ by library. In production, compare ss output for CLOSE_WAIT before and after a deploy of any change to connection handling. For the TCP retransmission side of connection behaviour, see /blogs/networking/tcp_retransmission_timeout_rfc6298.html.