WalkthroughDifficulty: Intermediate2 min

Closing a Connection, and TIME_WAIT

Each side closes its own direction, and the side that closes first waits before forgetting the connection.

A TCP connection closes in each direction separately: each side sends a FIN when it has finished sending, and the other acknowledges it. The side that closes first then stays in a state called TIME_WAIT for a while before forgetting the connection, so that a late segment cannot confuse a new connection with the same five values.

The four segments of a close, with each side's state

Closing the connection, segment by segment

The client sends a FIN

The client has nothing more to send. Its FIN says so; it can still receive.

The server acknowledges it

The connection is now half closed: the client's direction is finished, and the server may still send data, such as the rest of a response.

The server sends its own FIN

When the server's program closes its side, the server sends a FIN in turn.

The client acknowledges and waits

The client sends the final ACK and enters TIME_WAIT. The server, once it receives that ACK, forgets the connection.

TIME_WAIT lasts twice the maximum segment lifetime, the longest a segment is assumed to survive in the network. It serves two purposes. If the final ACK is lost, the server sends its FIN again, and the client is still there to answer. And any delayed segment from the old connection expires before a new connection with the same five values can start and mistake it for its own. Linux holds TIME_WAIT for 60 seconds.

It becomes visible on busy machines. A client that opens and closes thousands of short connections to one server accumulates thousands of connections in TIME_WAIT, each holding an ephemeral port, and can run out of ports. Reusing connections, rather than opening one per request, removes the problem at its cause.

A connection can also be aborted at once with an RST, which skips the exchange and discards any unsent data. Programs see that as "connection reset by peer".

So a close is two half closes, and the side that starts it pays the wait.