TCP dùng 4-way handshake (FIN/ACK/FIN/ACK) để đóng kết nối; sau đó initiator vào TIME_WAIT (2×MSL ≈ 60s) để đảm bảo ACK cuối được nhận.
TCP close connection cần 4 bước vì mỗi direction đóng độc lập:
- Client gửi FIN — muốn đóng kết nối
- Server gửi ACK — xác nhận, nhưng server vẫn có thể tiếp tục gửi data (half-close)
- Server gửi FIN — server cũng muốn đóng
- Client gửi ACK — xác nhận
TIME_WAIT state: sau khi client gửi ACK cuối, client vào TIME_WAIT trong 2*MSL (Maximum Segment Lifetime, thường 60 giây) trước khi port được tái sử dụng. Mục đích:
- đảm bảo server nhận được ACK cuối (nếu ACK mất, server retransmit FIN, client trong TIME_WAIT có thể trả ACK lại)
- đảm bảo packets cũ từ connection trước không được nhầm cho connection mới
Vấn đề thực tế: server với nhiều short-lived connections (HTTP/1.1) có thể bị exhausted ephemeral ports do quá nhiều TIME_WAIT sockets. Giải pháp: tcp_tw_reuse=1 (Linux, reuse TIME_WAIT sockets cho outgoing connections), HTTP/2 multiplexing, keep-alive connections.
TCP uses a 4-way handshake (FIN/ACK/FIN/ACK) to close a connection; the initiator then enters TIME_WAIT (2×MSL ≈ 60s) to ensure the final ACK is received.
TCP connection teardown requires 4 steps because each direction closes independently:
- Client sends FIN — signals it wants to close
- Server sends ACK — acknowledges, but the server can still send data (half-close)
- Server sends FIN — server also signals it wants to close
- Client sends ACK — acknowledges
TIME_WAIT state: after the client sends the final ACK, it enters TIME_WAIT for 2*MSL (Maximum Segment Lifetime, typically 60 seconds) before the port can be reused. Purposes:
- ensures the server receives the final ACK (if the ACK is lost, the server retransmits FIN and the client in TIME_WAIT can respond)
- ensures old packets from the previous connection are not misidentified as belonging to a new connection
Practical issue: servers handling many short-lived connections (HTTP/1.1) can exhaust ephemeral ports due to too many TIME_WAIT sockets. Solutions: tcp_tw_reuse=1 (Linux, allows reuse of TIME_WAIT sockets for outgoing connections), HTTP/2 multiplexing, and keep-alive connections.