TCP Connection Lifecycle
AdvancedThe full TCP connection lifecycle — establishment (3-way handshake), data transfer with sequence numbers and acknowledgements, flow control, and graceful teardown (4-way FIN handshake) — underpins every reliable network communication.
Overview
TCP provides reliable, ordered, byte-stream delivery over an unreliable IP network. It achieves this through sequence numbers (detect loss and reorder), acknowledgements (confirm receipt), retransmission timers (recover lost segments), flow control (receiver's window), and congestion control (network capacity estimation). Understanding the full connection lifecycle — SYN, ESTABLISHED, FIN_WAIT, TIME_WAIT — is essential for diagnosing connection issues, tuning server performance, and answering transport-layer interview questions.
3-Way Handshake in Detail
The three-way handshake establishes initial sequence numbers (ISNs) for both directions and confirms both sides can send and receive. ISNs are randomised to prevent sequence number prediction attacks (TCP hijacking).
// 3-Way Handshake:
//
// Client (10.0.0.1:54321) Server (10.0.0.2:443)
// │ │
// │── SYN ──────────────────────────▶│ seq=1000, ack=0
// │ "I want to connect, │ Client: SYN_SENT
// │ my ISN is 1000" │ Server: LISTEN → SYN_RCVD
// │ │
// │◀─ SYN-ACK ───────────────────────│ seq=5000, ack=1001
// │ "OK, my ISN is 5000, │ (ack = client ISN + 1)
// │ I received your SYN" │
// │ │
// │── ACK ──────────────────────────▶│ seq=1001, ack=5001
// │ "Got it, connection open" │ Both: ESTABLISHED
//
// Why random ISNs?
// Prevents TCP hijacking: attacker cannot guess seq numbers to inject dataSequence Numbers & Reliable Delivery
Every byte in a TCP stream is assigned a sequence number. The receiver sends cumulative ACKs (ACK = next expected byte). If a segment is lost, the retransmission timer fires and the sender retransmits. Modern TCP uses SACK (Selective Acknowledgement) to tell the sender exactly which segments arrived, avoiding retransmission of already-received data.
// Data transfer — sequence and acknowledgement numbers:
// Client sends 3 segments of 500 bytes each:
// Seg 1: seq=1001, len=500 → data bytes 1001–1500
// Seg 2: seq=1501, len=500 → data bytes 1501–2000 (LOST)
// Seg 3: seq=2001, len=500 → data bytes 2001–2500
// Without SACK (cumulative ACK):
// Server receives seg1, seg3 (not seg2)
// Server ACKs: ack=1501 "I have up to 1500, send from 1501"
// Client must retransmit seg2 AND seg3 (cannot know server has seg3)
// With SACK (RFC 2018):
// Server: ack=1501, SACK: [2001–2500]
// "I need 1501–2000, but I already have 2001–2500"
// Client retransmits ONLY the missing segment 1501–2000
// Check SACK support:
sysctl net.ipv4.tcp_sack // should be 1
// Retransmission timer (RTO):
// RTO = SRTT + 4 × RTTVAR (exponential backoff on failure)
// SRTT: smoothed RTT estimate; RTTVAR: RTT variance4-Way FIN Handshake & TIME_WAIT
TCP connection teardown is four steps because each direction closes independently. After the active closer sends FIN and receives the final ACK, it enters TIME_WAIT for 2×MSL (Maximum Segment Lifetime, typically 60s). TIME_WAIT prevents delayed packets from a previous connection being misinterpreted by a new connection on the same 4-tuple.
// 4-Way FIN Handshake:
// Client initiates close (active closer)
//
// Client Server
// │── FIN ──────────────────────▶│ seq=2500 Client: FIN_WAIT_1
// │◀─ ACK ───────────────────── │ ack=2501 Client: FIN_WAIT_2
// │ │ Server: CLOSE_WAIT
// │ │ (server finishes sending data)
// │◀─ FIN ───────────────────── │ seq=8000 Server: LAST_ACK
// │── ACK ──────────────────────▶│ ack=8001 Client: TIME_WAIT (2MSL)
// Server: CLOSED
// TIME_WAIT (typically 60s):
// Why: ensures late duplicate segments from this connection don't contaminate
// a new connection that reuses the same 4-tuple (src IP, src port, dst IP, dst port)
//
// Problem: high-throughput servers (HTTP/1.1 short connections) accumulate
// tens of thousands of TIME_WAIT sockets → port exhaustion
//
// Solutions:
sysctl -w net.ipv4.tcp_tw_reuse=1 // reuse TIME_WAIT sockets for outbound
# HTTP Keep-Alive: reuse connections, avoid teardown per request
# HTTP/2: one persistent connection per originTCP State Machine
TCP defines 11 states. Understanding which state a socket is in helps diagnose connection issues. ss -tan or netstat -tan shows socket states on Linux.
// TCP state summary:
// LISTEN — server waiting for incoming SYN
// SYN_SENT — client sent SYN, waiting for SYN-ACK
// SYN_RCVD — server received SYN, sent SYN-ACK, waiting for ACK
// ESTABLISHED — connection open, data transfer in progress
// FIN_WAIT_1 — active closer sent FIN
// FIN_WAIT_2 — active closer received ACK of FIN, waiting for server FIN
// CLOSE_WAIT — passive closer received FIN, app needs to close
// LAST_ACK — passive closer sent FIN, waiting for final ACK
// TIME_WAIT — active closer waiting 2MSL before CLOSED
// CLOSED — no connection
// Diagnose on Linux:
ss -tan state established # all established connections
ss -tan state time-wait | wc -l # count TIME_WAIT sockets
ss -tan state close-wait # stuck CLOSE_WAIT = app not calling close()
// CLOSE_WAIT accumulation = bug: server app not closing socket after EOFKey Points to Remember
- 1The 3-way handshake exchanges random ISNs in both directions — randomisation prevents TCP sequence number prediction attacks.
- 2SACK (Selective Acknowledgement) allows the sender to retransmit only lost segments, not everything from the loss point forward.
- 3TIME_WAIT (2×MSL ≈ 60s) on the active closer prevents late duplicate segments contaminating a new connection on the same 4-tuple.
- 4CLOSE_WAIT accumulation on a server indicates the application is not calling close() after the remote side closes — a common bug.
- 5HTTP Keep-Alive and HTTP/2 multiplexing reduce the TCP handshake tax by reusing connections across multiple requests.
Interview Questions
Sign in to ask AriaWhy does the TCP handshake use random initial sequence numbers?
What is the purpose of the TIME_WAIT state and why is it 2×MSL?
What does it mean when a server has thousands of CLOSE_WAIT connections?
What is SACK and how does it improve TCP retransmission efficiency?
Why is TCP teardown 4 steps but establishment is only 3?
Ask Aria about TCP Connection Lifecycle
Your personal AI tutor — ask anything about this concept
Revision Status
Personal Notes
Sign in to save personal notes for this topic.
Discussion
Sign in to join the discussion.