TCP Teardown
Four-way (or three-way with FIN-ACK) close, TIME-WAIT, and why half-open exists.
Level: intermediate
What is it?
TCP connection teardown is the process of independently closing each direction of a byte stream. A FIN indicates that a sender has no more data to send in that direction; the peer may continue sending until it also closes.
Why does it matter?
Full-duplex connections have two directions with separate state. Correct teardown prevents loss of trailing data and allows each endpoint to know when the peer has finished sending.
Mental model
A TCP connection has two one-way streams. Closing one direction is a half-close; the other direction can continue until its endpoint sends FIN or the connection is reset.
How it works
- A typical orderly close uses FIN and ACK exchanges, often described as four segments although acknowledgements may be combined.
- TIME-WAIT is held by the active closer in common TCP state models to handle delayed segments and protect a subsequent connection using the same tuple.
- RST aborts a connection rather than performing an orderly half-close.
- A process closing its socket should still read or handle pending data according to the protocol/API contract.
- Application-level shutdown and TCP-level close are related but not identical events.
Steps
- Endpoint A finishes sending data and sends FIN.
- Endpoint B acknowledges A's FIN and can continue sending its own pending data.
- When B finishes, it sends its FIN and A acknowledges it.
- The endpoints transition through TCP states; the active closer may remain in TIME-WAIT before the tuple is safely reused.
Real-world usage
- Debugging lingering sockets and TIME-WAIT counts.
- Implementing orderly shutdown for servers and streaming protocols.
Common mistakes
- Assuming FIN means the entire connection is immediately closed both ways.
- Using RST where the application needs graceful delivery of pending bytes.
- Treating TIME-WAIT as necessarily a leak; it serves protocol safety purposes.
Interview questions
What does TCP FIN mean?
The sender has finished sending on its direction of the byte stream; it does not automatically close the peer's sending direction.
Why does TIME-WAIT exist?
It helps absorb delayed duplicate segments and ensure the final acknowledgement can be retransmitted before the connection tuple is reused.