Skip to content
We areTOP 1%

Why does closing a TCP connection take four steps?

MediumConceptTCP & UDP
Track your progress
First attempt
Re-solve after a few days
Final pass before interviews

Answer

TCP is full-duplex: data flows in both directions independently, so each direction must be closed separately. Each side sends a FIN (finish) when it has no more data, and the other side acknowledges it, giving four messages: FIN, ACK, FIN, ACK.

  • After the first FIN and its ACK, the connection is half-closed: the side that closed can still receive the data the other side has not finished sending.
  • The server's ACK and FIN are usually separate because the server application may still be sending. If it has nothing left, they can be combined into one segment.
  • The side that closes first waits in TIME_WAIT for twice the maximum segment lifetime (2 × MSL; 60 seconds on Linux). This lets it resend the final ACK if it is lost and lets delayed packets of the old connection expire before the same port pair is reused.

Example:

Client                                  Server
  | --- FIN  seq=2000 ---------------->  |   client has finished sending
  | <-- ACK  ack=2001 -----------------  |   server may still send data
  | <-- FIN  seq=7000 -----------------  |   server has finished too
  | --- ACK  ack=7001 ---------------->  |   client enters TIME_WAIT

More in TCP & UDP

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account