TCP

How TCP turns an unreliable network into a reliable byte stream — ports, the three-way handshake, sequence numbers and ACKs, retransmission, flow control, connection teardown and TIME_WAIT.

Intermediate 5 min readLesson 6 of 15 Interview Q&A

IP delivers packets best effort: they can be lost, duplicated, reordered or corrupted. TCP (Transmission Control Protocol) builds on top of IP to give applications a reliable, ordered, bidirectional byte stream between two processes. HTTP/1.1, HTTP/2, SSH, database protocols, SMTP and most of the Internet's traffic run over TCP.

What TCP provides

FeatureHow
Process-to-process deliveryPorts (16-bit): a connection is identified by the 4-tuple (src IP, src port, dst IP, dst port)
ReliabilitySequence numbers, acknowledgements, retransmission
OrderingReceiver reorders by sequence number
IntegrityChecksum on every segment
Flow controlReceiver advertises a window, so a fast sender can't overwhelm a slow receiver
Congestion controlSender limits itself so it doesn't overwhelm the network (Congestion control)

The segment header

FieldPurpose
Source / destination portWhich processes
Sequence numberPosition of this segment's first byte in the stream
Acknowledgement numberNext byte expected from the other side (cumulative)
FlagsSYN, ACK, FIN, RST, PSH, URG
Window sizeHow many more bytes the receiver can accept
ChecksumError detection
OptionsMSS, window scaling, SACK, timestamps

The three-way handshake

Both sides pick a random initial sequence number (ISN) and must learn each other's:

InteractiveTCP: handshake → data → teardown
ClientSYN_SENT
ServerLISTEN
SYN seq=100
Client picks a random initial sequence number (ISN) and sends SYN.
1/9
  1. Client → server: SYN, seq = x ("I want to connect; my bytes start at x").
  2. Server → client: SYN-ACK, seq = y, ack = x + 1 ("OK; mine start at y; I expect your x + 1").
  3. Client → server: ACK, ack = y + 1. The connection is established; data can flow (and the client may send data with this ACK).

The handshake costs one round trip before any data is sent, plus TLS's own round trip(s) on top (HTTPS & TLS). That's why connection reuse (keep-alive, connection pools) matters so much, and why QUIC merges the two handshakes.

Reliable delivery

The receiver acknowledges the next byte it expects. If an ACK doesn't arrive before the retransmission timeout (RTO) — computed from a smoothed RTT estimate plus 4× its variance — the sender retransmits. Each timeout doubles the RTO (exponential backoff).

SenderReceiverseq 1000, 500 bytesseq 1500, 500 bytes (lost ✗)seq 2000, 500 bytesACK 1500 (duplicate)ACK 1500 (duplicate)fast retransmit seq 1500ACK 2500
  • Fast retransmit: three duplicate ACKs signal a lost segment, so retransmit immediately instead of waiting for the timeout.
  • Selective ACK (SACK): the receiver reports exactly which blocks it has, so only the missing ones are resent.
  • Delayed ACKs: receivers ACK every second segment or after ~40 ms to cut overhead.

Flow control: the sliding window

The receiver advertises its free buffer space (rwnd). The sender may have at most that many unacknowledged bytes in flight.

windowsent+acked0sent+acked1in flight2in flight3in flight4can send5can send6not yet7
The window slides right as ACKs arrive.

Maximum throughput ≈ window / RTT. With the original 64 KB maximum window and a 100 ms RTT, that's only ~5 Mbit/s, so the window scaling option allows windows up to 1 GB. The bandwidth–delay product (bandwidth × RTT) tells you how big the window must be to fill a link.

If the receiver's window drops to 0, the sender stops and probes periodically (zero window). This is what happens when an application stops reading from a socket.

Closing a connection

Each direction is closed separately with FIN (a four-way close; often 3 segments when combined):

  1. A → B: FIN ("I'm done sending").
  2. B → A: ACK. B can still send remaining data (half-close).
  3. B → A: FIN.
  4. A → B: ACK. A enters TIME_WAIT for 2 × the maximum segment lifetime (typically 60 s on Linux).

TIME_WAIT ensures delayed packets from the old connection can't be mistaken for a new one with the same 4-tuple, and that the final ACK can be resent if it's lost. A busy client opening and closing many short connections to the same server can run out of ephemeral ports because of it — another reason to reuse connections.

RST aborts a connection immediately: sent when a packet arrives for a port with no listener ("connection refused") or when an application aborts.

TCP connection states

StateMeaning
LISTENServer waiting for connections
SYN_SENT / SYN_RECEIVEDHandshake in progress
ESTABLISHEDData flowing
FIN_WAIT_1/2, CLOSE_WAIT, LAST_ACKClosing
TIME_WAITClosed, waiting out old packets
Shell
ss -tan state established | wc -l      # how many established connections
ss -tan | awk '{print $1}' | sort | uniq -c   # count by state

Socket programming

// Server
try (ServerSocket server = new ServerSocket(8080)) {
    while (true) {
        Socket s = server.accept();                 // completed handshakes
        Thread.ofVirtual().start(() -> handle(s));
    }
}
// Client
try (Socket s = new Socket("localhost", 8080)) {
    s.getOutputStream().write("hello".getBytes());
}

Nagle's algorithm

Nagle buffers small writes until earlier data is acknowledged, to avoid sending many tiny packets. Combined with delayed ACKs it can add ~40 ms latency to request–response traffic, so latency-sensitive apps set TCP_NODELAY (most HTTP clients and databases do).

Key takeaways
  • TCP gives a reliable, ordered byte stream over unreliable IP, identified by a 4-tuple.
  • The three-way handshake syncs sequence numbers and costs one RTT.
  • Cumulative ACKs, timeouts, fast retransmit and SACK provide reliability.
  • Flow control: the receiver's window limits data in flight; throughput ≈ window / RTT.
  • Closing uses FINs; TIME_WAIT protects against stale packets; CLOSE_WAIT leaks are app bugs.
  • TCP has no message boundaries — frame your messages.
Interview questions
QWhy is the TCP handshake three-way and not two-way?medium

Both sides must choose an initial sequence number and confirm the other received it. The SYN-ACK confirms the client's ISN and carries the server's; the final ACK confirms the server's ISN. With only two steps the server couldn't know whether its ISN arrived, and old duplicate SYNs could create bogus connections.

QWhat's the difference between flow control and congestion control?medium

Flow control protects the receiver: the advertised window keeps the sender from overrunning the receiver's buffer. Congestion control protects the network: the sender's congestion window limits data in flight based on signs of congestion such as loss or rising delay. The sender uses the minimum of the two.