TCP Connection Lifecycle
AdvancedBy the AiCanCode.org team · How we write and check our content
The 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.
A connection from open to close: the 3-way handshake, a burst of data, the 4-way FIN teardown and TIME_WAIT. Press Play, or step through with Next.
- Client sends SYN to Server. Opening: the client sends its random initial sequence number (ISN).
- Server sends SYN-ACK to Client. The server sends its own ISN and acknowledges the client's.
- Client sends ACK to Server. Both sides know both ISNs: the connection is open in both directions.
- Client sends Data, 1500 bytes to Server. Every byte has a sequence number. This segment carries bytes 1001 to 2500.
- Server sends ACK to Client. A cumulative ACK: "I have everything up to 2500; send 2501 next." Had a segment been lost, the ACK would stay at the gap and the sender would retransmit.
- Client sends FIN to Server. Closing starts. The client is the active closer: it has nothing more to send, so it closes its half of the connection.
- Server sends ACK to Client. The server acknowledges the FIN but may still send data. It waits in CLOSE_WAIT until its application calls close(). A server piling up CLOSE_WAIT sockets is an app that forgets to close them.
- Server sends FIN to Client. The server application closes its side, so the server sends its own FIN. That is why teardown takes four steps: each direction closes on its own.
- Client sends ACK to Server. The last ACK. The server is done and frees the socket; the client, as the active closer, has to wait.
- Client sends 2×MSL timer expires to Client. TIME_WAIT lasts twice the Maximum Segment Lifetime, so a late duplicate from this connection cannot be mistaken for data on a new one using the same 4-tuple (source IP and port, destination IP and port).
// 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 ask a question — Aria answers, and so do other students.