TCP Connection State Transitions
TCP connections progress through specific states during establishment and termination. The protocol defines 11 distinct states:
State Categories
- Client-specific states: SYN_SENT, FIN_WAIT1, FIN_WAIT2, CLOSING, TIME_WAIT
- Server-specific states: LISTEN, SYN_RCVD, CLOSE_WAIT, LAST_ACK
- Shared states: CLOSED, ESTABLISHED
Connection Establishment Flow
- Both endpoints start in CLOSED state
- Server transitions to LISTEN after binding and listening
- Client sends SYN packet, enters SYN_SENT
- Server responds with SYN+ACK, enters SYN_RCVD
- Client sends ACK, enters ETSABLISHED
- Server receives ACK, enters ESTABLISHED
Connection Termination Flow
- Client sends FIN, enters FIN_WAIT1
- Server sends ACK, enters CLOSE_WAIT
- Client receives ACK, enters FIN_WAIT2
- Server sends FIN after completing data transmission, enters LAST_ACK
- Client sends ACK, enters TIME_WAIT
- After 2MSL timeout, client enters CLOSED
- Server receives ACK, enters CLOSED
The CLOSING state occurs when a client receives a FIN while in FIN_WAIT1, typically due to ACK packet loss.
TIME_WAIT State Optimization
Parameter Tuning Considerations
Client-side recommendations:
- Enable
tw_reuseto handle port exhaustion issues - Avoid
tw_recycleas it provides minimal benefits with potential risks - Design services to have servers initiate connection closure when possible
Server-side recommendations:
tw_reusehas no effect on servers- Disable
tw_recyclein production environments - NAT envrionments may nullify
tw_recycleeffectiveness
TIME_WAIT Mitigation Strategies
- Expand port range:
sysctl -w net.ipv4.ip_local_port_range="2048 65000" - Utilize additional virtual IP addresses
- Implement persistent connections to reduce connection frequency