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.
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
| Feature | How |
|---|---|
| Process-to-process delivery | Ports (16-bit): a connection is identified by the 4-tuple (src IP, src port, dst IP, dst port) |
| Reliability | Sequence numbers, acknowledgements, retransmission |
| Ordering | Receiver reorders by sequence number |
| Integrity | Checksum on every segment |
| Flow control | Receiver advertises a window, so a fast sender can't overwhelm a slow receiver |
| Congestion control | Sender limits itself so it doesn't overwhelm the network (Congestion control) |
The segment header
| Field | Purpose |
|---|---|
| Source / destination port | Which processes |
| Sequence number | Position of this segment's first byte in the stream |
| Acknowledgement number | Next byte expected from the other side (cumulative) |
| Flags | SYN, ACK, FIN, RST, PSH, URG |
| Window size | How many more bytes the receiver can accept |
| Checksum | Error detection |
| Options | MSS, window scaling, SACK, timestamps |
The three-way handshake
Both sides pick a random initial sequence number (ISN) and must learn each other's:
- Client → server:
SYN, seq = x("I want to connect; my bytes start at x"). - Server → client:
SYN-ACK, seq = y, ack = x + 1("OK; mine start at y; I expect your x + 1"). - 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).
- 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.
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):
- A → B:
FIN("I'm done sending"). - B → A:
ACK. B can still send remaining data (half-close). - B → A:
FIN. - 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
| State | Meaning |
|---|---|
| LISTEN | Server waiting for connections |
| SYN_SENT / SYN_RECEIVED | Handshake in progress |
| ESTABLISHED | Data flowing |
| FIN_WAIT_1/2, CLOSE_WAIT, LAST_ACK | Closing |
| TIME_WAIT | Closed, waiting out old packets |
ss -tan state established | wc -l # how many established connections
ss -tan | awk '{print $1}' | sort | uniq -c # count by stateSocket 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());
}import socket
# Server
with socket.create_server(("0.0.0.0", 8080)) as srv:
conn, addr = srv.accept()
with conn:
data = conn.recv(4096) # may return fewer bytes than sent!
conn.sendall(data)
# Client
with socket.create_connection(("localhost", 8080)) as s:
s.sendall(b"hello")
print(s.recv(4096))import net from "node:net";
net.createServer((sock) => sock.on("data", (d) => sock.write(d))).listen(8080);
const c = net.connect(8080, "localhost", () => c.write("hello"));
c.on("data", (d) => console.log(d.toString()));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).
- 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.
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.