How is a TCP connection closed, and what is the TIME_WAIT state?
Each side closes its own direction with FIN and the other side ACKs it, so teardown takes four segments. The side that closes first then waits in TIME_WAIT, about twice the maximum segment lifetime (60 seconds on Linux), to catch late packets and to resend the last ACK if lost.
Explain it simply
Ending a WhatsApp call politely: you say "I am done", they say "okay", then they say "I am done too", and you say "okay". Each person closes their own side separately, so it takes four lines, not two.
Example
Client Server
FIN ----> client finished sending (FIN_WAIT_1)
<---- ACK (FIN_WAIT_2)
<---- FIN server finished too (LAST_ACK)
ACK ----> client enters TIME_WAIT, then CLOSEDThe wait exists for two reasons. If the final ACK is lost, the server resends its FIN, and the client must still be around to answer. Also, stray delayed segments from this connection could be mistaken for data in a new connection that reuses the same four-tuple.
On a busy server that closes many short connections, thousands of sockets can sit in TIME_WAIT. This is normal. The fix is usually connection reuse (keep-alive, pooling), not shortening the timer.
What to say in the interview
"Teardown is four segments because each direction closes independently. The active closer enters TIME_WAIT for 2 times MSL so that a lost final ACK can be resent and old packets die out. Many TIME_WAIT sockets are a symptom of lots of short connections."
Common mistakes
- Believing TIME_WAIT is a leak or a bug.