An engineer pings you: "the client for our backend has about 24,000 sockets in TIME_WAIT — that has to be a leak, can we lower a sysctl?" The service opens a fresh TCP connection for every request, reads the response and calls close(), and it runs at about 400 requests/s. What is actually going on, and why that number?
- Lowering
net.ipv4.tcp_fin_timeoutwill shorten TIME_WAIT and shrink the count.tcp_fin_timeoutgoverns FIN_WAIT_2 (waiting for the peer's FIN). TIME_WAIT length is compiled in at 60 s on Linux and has no sysctl. - TIME_WAIT always accumulates on the server because the server owns the listening port. TIME_WAIT is held by whichever side actively closes; the listening socket is irrelevant. Servers accumulate it only when they close first (for example on
Connection: close). - They are leaked file descriptors from connections the application forgot to close. A TIME_WAIT socket has already been closed by the application; it holds no file descriptor and no user-space state, only a kernel 4-tuple waiting to expire.
- The side that sends the first FIN enters TIME_WAIT for 60 s on Linux to absorb late segments for that 4-tuple; the client closes first, so it holds them, and 400 connections/s × 60 s ≈ 24,000. TIME_WAIT belongs to the active closer, lasts a fixed 60 s (TCP_TIMEWAIT_LEN) on Linux, and the steady-state count is simply close rate × 60.
The client closes first, so it holds every closed connection in TIME_WAIT for 60 seconds.
After the active closer sends its final ACK, TCP keeps the 4-tuple in TIME_WAIT for 2×MSL — a fixed 60 s on Linux — so a delayed segment from the old connection cannot be mistaken for part of a new one on the same tuple. Each TIME_WAIT on the client pins one ephemeral port toward that destination, so at 400 connections/s you carry about 400×60 of them. The default ephemeral range (32768–60999) is 28,232 ports, which caps a client near 470 new connections/s to one destination before connect() fails with EADDRNOTAVAIL. The engineering fix is to stop opening a connection per request (keepalive or a pool), not to fight the kernel with sysctls.
Treating TIME_WAIT as a leak and answering with a kernel setting. tcp_fin_timeout does not touch TIME_WAIT, tcp_tw_recycle no longer exists, and the interviewer knows both; the answer they want is "stop opening a connection per request".