The internet may drop, reorder or copy any packet, and it never says so. TCP numbers every byte and resends what goes missing, so the app reads every byte, in order. Each repair costs a round trip.
Send the payment message through raw IP, then through TCP. Drag the loss rate and send again. Then we build TCP piece by piece: numbers and ACKs, timers, windows, congestion control, TLS and QUIC.
You need to know that computers have addresses and ports and a little Python. We build the rest from zero.
Illustrative toy: each packet is lost at random with the rate you set. Raw IP may also swap two packets or copy one. Here TCP resends each lost packet one round trip later; real TCP finds losses with duplicate ACKs and timers (Chapters 1 and 2).
Chapter 0
See what raw IP does to your packets, and which layer has to fix it
Your app sends "PAY 100 TO ALICE" to a bank server. The message crosses Wi-Fi, copper, fiber and a dozen routers. Any router with a full queue drops the packet and tells no one.
The Internet Protocol (IP) moves packets from one address to another. It makes one promise: best effort. A packet may be lost, copied, reordered, delayed for seconds or damaged. Run the hero at 20% loss with raw IP. The bank reads holes and swapped pieces.
So each host runs a stack of layers. Each layer adds a header, a few bytes of labels in front of the data. The app writes the request. TCP adds port numbers, a sequence number and a checksum. IP adds the two addresses. The link layer (Ethernet or Wi-Fi) adds the hardware addresses for one hop.
The bar is one real packet: four parts, drawn to scale by bytes. Pick a reader and see which part it opens.
Real sizes: Ethernet header 14 bytes (the 4-byte frame check is left out), IP header 20 bytes and TCP header 20 bytes with no options, and the 37-byte request "GET / HTTP/1.1", "Host: example.com" with its line breaks.
A router reads only the IP header. It never sees TCP's numbers, so it cannot resend or reorder anything. All repair happens at the two ends. This is the end-to-end principle: keep the middle simple, put the intelligence at the edges.
TCP (Transmission Control Protocol) is that repair layer. It gives the app a byte stream: every byte arrives once, in order, or the connection reports an error. It also slows down for a slow receiver and a busy network. UDP is the other common transport. It adds ports and a checksum, and nothing more.
Chapter 1
Number every byte, let the receiver say which byte it needs next, and resend the gap
TCP gives every byte a number, the sequence number. A segment (one TCP packet) carries the number of its first byte. The receiver answers with an ACK that carries the number of the next byte it expects. This is a cumulative ACK: "I have everything before this byte."
The numbers start at a hard-to-guess initial sequence number (ISN), so each side must learn the other's ISN first. That is the three-way handshake. The SYN flag uses up one sequence number, so data starts at ISN + 1 (RFC 9293).
Why a third message? A SYN from an old, dead attempt can arrive late. With two messages the server would open a connection that no client wants. The client's final ACK names the server's fresh ISN, so a stale SYN cannot complete.
Now the client sends five segments of 500 bytes: bytes 1001 to 3500. If segment 2 (bytes 1501 to 2000) is lost, segments 3, 4 and 5 still arrive. Each makes the receiver repeat "ACK 1501". These are duplicate ACKs. The receiver keeps the later bytes in a buffer while it waits.
Blue arrows carry data, teal arrows carry ACKs. Pick the segment the network drops, then press Play or Step.
Illustrative trace with 500-byte segments and a client ISN of 1000. The rule is RFC 5681: resend after the third duplicate ACK. With too few later segments, only the retransmission timer can find the loss.
After the third duplicate ACK the sender resends the missing segment at once. This is fast retransmit (RFC 5681). The repaired gap lets the ACK jump past all the buffered bytes, from 1501 to 3501. Lose the last segment and no later segment arrives to cause duplicates. Then only a timer helps (Chapter 2).
The ACK jump is still a cumulative ACK. SACK (selective acknowledgment, RFC 2018) is a separate option. With it, the receiver also lists the byte ranges it holds past the gap. The sender then resends only what is missing.
Chapter 2
Track the average round trip and its wobble, and wait a little longer than both
When no duplicate ACKs come, the sender waits for a timer. Wait too short, and it resends segments that were only slow. Wait too long, and a real loss stalls the connection. The right wait depends on the path: 1 ms in a datacenter, 150 ms across an ocean.
The round-trip time (RTT) is the time from sending a segment to receiving its ACK. TCP measures it on every round trip. It keeps a smoothed average, SRTT, and an average of how far each new sample falls from it, RTTVAR. The wait is the retransmission timeout, RTO.
R-T-O equals S-R-T-T plus four times R-T-T-var.
For each new sample R, first move RTTVAR a quarter of the way toward the gap between R and SRTT. Then move SRTT an eighth of the way toward R. Wait SRTT plus four RTTVARs.
With made-up numbers: SRTT = 100 ms, RTTVAR = 10 ms, and a new sample R = 140 ms. RTTVAR = 0.75 × 10 + 0.25 × 40 = 17.5 ms. SRTT = 0.875 × 100 + 0.125 × 140 = 105 ms. RTO = 105 + 4 × 17.5 = 175 ms. One slow sample raised the wait by 35 ms.
Two rules sit on top. RFC 6298 says to round an RTO below 1 second up to 1 second; Linux uses a 200 ms floor instead. After each timeout the sender doubles the RTO, exponential backoff, so a dead path does not get a flood of copies.
Blue dots are RTT samples. The purple line is SRTT and the yellow line is RTO. A red dot is a sample slower than the RTO: a timer that fired too early. Drag the jitter and add a route change.
Illustrative samples around a 100 ms path, from a fixed seed. The update rules and the factor 4 are RFC 6298; the first sample sets SRTT = R and RTTVAR = R/2.
Failure. Symptom: throughput drops in bursts with no real loss. Measure: retransmissions marked spurious in ss -ti or nstat. Cause: the RTT jumped faster than RTTVAR could follow. Fix: keep the floor; never set the RTO by hand.
Chapter 3
Close each direction on its own, then hold the port long enough for old packets to die
A connection is two one-way streams. Each side closes its own stream with a FIN flag, and the other side ACKs it. So a close takes four messages, and each side walks through named states. You can list them with ss -tan.
The side that closes first lands in TIME_WAIT. It waits twice the maximum segment lifetime (MSL), the longest a packet may live in the network. There are two reasons. If the last ACK is lost, B resends its FIN, and A must still be there to answer. And a late packet from this connection must die before a new connection reuses the same ports.
RFC 9293 takes MSL as 2 minutes, so TIME_WAIT lasts 4 minutes. Linux uses a fixed 60 seconds. During that time the socket holds its ephemeral port, the client-side port the system picks for each outgoing connection. How many new connections a second can one client make to one server address and port?
R-max equals P over T.
Each closed connection keeps one of the P ports for T seconds. So at most P ports free up every T seconds. Divide P by T.
P = 28,232 and the Linux T = 60 s give R-max = 470 connections a second. With the RFC's T = 240 s it is 117. A proxy that opens a fresh connection per request runs out of ports at about 470 requests a second to one backend.
Each cell is about 280 ports. Pink cells hold sockets in TIME_WAIT. Drag the rate of new connections, then turn on a pool.
One client address to one server address and port. The steady count of sockets in TIME_WAIT is the rate times T (Little's law). The pool reuses its connections, so almost none close.
CLOSE_WAIT is the other state to watch. It means the peer sent FIN, and your app has not called close(). Thousands of them point to a leak in your code, usually an error path that forgets to close the socket.
Failure. Symptom: connect() fails with "Cannot assign requested address" (EADDRNOTAVAIL). Measure: ss -tan state time-wait | wc -l against the port range. Fix: pool and reuse connections; net.ipv4.tcp_tw_reuse helps outgoing connections when TCP timestamps are on.
Chapter 4
Put the free buffer space in every ACK, and let the sender never exceed it
A server can send far faster than a busy phone app reads. TCP holds the arrived bytes in a receive buffer until the app reads them. If the sender keeps going, the buffer fills and new segments have nowhere to go.
So every ACK carries the free space in that buffer: the receive window, rwnd. The sender counts its bytes in flight: sent, but not yet ACKed. Call the number of the last byte sent S and the last byte ACKed A. Call what the sender may still send right now U, the usable window.
U equals r-wind minus the quantity S minus A.
Subtract A from S to count the bytes in flight. Subtract that from rwnd. What is left, U, is all the sender may add.
With made-up numbers: a 64 KB buffer holds 40 KB the app has not read, so rwnd = 24 KB. The sender has 20 KB in flight. U = 24 − 20 = 4 KB. It may send one 4 KB burst and then must wait for an ACK.
Top: the sender's stream of 24 segments. Teal segments have their ACK, blue ones are in flight, and the outline marks the window. Bottom: the receiver's 8-segment buffer in purple. Drag the read speed, then press Play.
Illustrative toy in whole segments, one round trip per step, no congestion limit. A real rwnd is in bytes and arrives in every ACK.
Set the read speed to 0. The buffer fills, and the receiver advertises rwnd = 0: stop. Later the app reads and the receiver sends a window update. If that update is lost, both sides would wait forever. So a stopped sender sends a 1-byte zero-window probe now and then, and each reply carries the current rwnd (RFC 9293 requires it).
The window field in the header has 16 bits, so it can say at most 65,535 bytes. The window scale option, agreed in the SYN, shifts it left by up to 14 bits, for windows up to 1 GiB (RFC 7323). Chapter 5 shows why that matters.
Chapter 5
Find how many bytes must be in flight to use a link, and what a small window costs
A sender may have at most one window of bytes in flight. Then it waits for ACKs, and the first ACK returns one round trip after the first byte left. So one window per round trip is the most it can move. Call the window W in bytes and the throughput X.
X is at most W over R-T-T.
The sender moves one window W, then waits one RTT. Divide W by RTT. No link speed beats that limit.
W = 65,535 bytes, the most the bare 16-bit field allows, and RTT = 0.1 s across the Atlantic. X = 655,350 bytes a second, 5.2 Mbps. On a 10 Gbps link that is about one two-thousandth of the speed.
How big must the window be to use the whole link? Multiply the link's bandwidth B, in bytes a second, by the RTT. The result is the bandwidth-delay product, BDP: the bytes the pipe holds while the first ACK travels back.
B-D-P equals B times R-T-T.
Convert the link speed B to bytes a second. Multiply by the RTT. A window W smaller than the BDP leaves the link idle part of each round trip.
B = 10 Gbps = 1.25 GB a second and RTT = 0.1 s. BDP = 125 MB. A 64 KiB window fills 0.05% of it. A window scale of 11 gives 65,535 × 2,048 = 134 MB, enough to fill it.
The pipe's area is the BDP. Blue is the window in flight. Change the link, the round trip and the window.
X = min(link, W / RTT), with no loss and no congestion limit. 16 MiB is a common Linux tcp_rmem maximum.
A worked case: copy 500 GB across that 10 Gbps, 100 ms path. At full speed it takes 400 seconds, under 7 minutes. With a 64 KiB window it runs at 5.2 Mbps and takes about 212 hours. A 16 MiB buffer reaches 1.34 Gbps, about 50 minutes.
Failure. Symptom: a long-distance copy crawls on a fast, idle link. Measure: ss -tin shows the window and the RTT; divide one by the other. Fix: raise net.ipv4.tcp_rmem and tcp_wmem maximums and keep window scaling on.
Chapter 6
Grow the sending window until a loss, cut it in half, and share the link with no coordinator
In October 1986 the link between Lawrence Berkeley Laboratory and UC Berkeley, 400 yards apart, fell from 32,000 to 40 bits a second. Every sender resent its lost packets at once, which filled the router queues and caused more loss. Van Jacobson called it congestion collapse. His 1988 fix still runs in every TCP stack.
Each sender keeps a second window, the congestion window, cwnd: its own guess of what the network can carry. It may send min(cwnd, rwnd). Counts below are in segments of one MSS (maximum segment size, often 1,460 bytes).
A new connection does not know the path. It starts with an initial window IW and grows cwnd by one segment per ACK. Each round trip ACKs a whole window, so cwnd doubles every round trip. This phase is slow start, a poor name for doubling. Call the round trips so far k.
c-wind sub k equals I-W times two to the k.
Start at IW. Double it once for each round trip k with no loss. Stop doubling at the threshold ssthresh or at the first loss.
A 100 KB page is 69 segments. With IW = 10, the first three round trips carry 10, 20 and 40 segments: 70, so the page needs 3 round trips. With IW = 3 it needs 5. On a 100 ms path that is 300 ms against 500 ms, before any link speed matters.
Above the slow-start threshold, ssthresh, growth turns gentle: one segment per round trip, additive increase. A loss means a queue overflowed somewhere. The response is multiplicative decrease. Together they are AIMD. The rules from RFC 5681:
The purple line is cwnd, the dashed line is ssthresh, and the yellow line is what the link holds. Press Play. Inject a loss, or let the link overflow by itself.
Illustrative Reno in whole segments, one point per round trip. The first ssthresh is 64. Fast recovery's short inflation to ssthresh + 3 is left out.
Why halve and not subtract? Two senders share a 100-segment link with cwnd 80 and 40. At each overflow both halve, which keeps their ratio. Between overflows both add the same 1 a round trip, which shrinks it. The ratio goes 2, then 1.49, 1.22 and 1.10. They meet in the middle with no message between them.
Linux's default today is CUBIC (since 2006), which regrows cwnd along a cubic curve after a loss. Google's BBR (2016) measures the bottleneck bandwidth and the shortest RTT instead of waiting for loss. The window and the BDP stay the same ideas.
Chapter 7
Agree on a key that no listener can compute, and prove who holds the other end
TCP sends plain text. Anyone on the path can change "PAY 100 TO ALICE" to "PAY 900 TO MALLORY". TLS (Transport Layer Security) adds three things. Encryption stops reading. Integrity catches any changed byte. Authentication proves who is at the other end.
Fast encryption needs one shared key. Two strangers agree on it in public with Diffie-Hellman. Both use a public prime p and a public base g. The client picks a secret a and sends A = ga mod p. The server picks a secret b and sends B = gb mod p. ("mod p" means the remainder after dividing by p.) Call the shared secret s.
s equals B to the a, mod p, which equals A to the b, mod p.
The client raises the server's share B to its secret a. The server raises the client's share A to its secret b. Both get g to the a-times-b, mod p, the same s. A listener sees A and B but neither secret.
A toy: p = 23, g = 5, a = 6, b = 15. A = 56 mod 23 = 8 and B = 515 mod 23 = 19. The client computes 196 mod 23 = 2. The server computes 815 mod 23 = 2. Real TLS often uses X25519, an elliptic-curve version with 255-bit numbers, so no one can work back from A to a.
A listener cannot get s. But an attacker in the middle can swap B for its own share, and the client then shares a key with the attacker. Authentication stops this. The server sends its certificate, a signed statement "this public key belongs to bank.example", in a chain up to a root the client already trusts. Then it sends CertificateVerify: a signature over the whole handshake so far, made with that certificate's private key.
Warm boxes are the two hosts; purple numbers are what each one keeps secret. The middle lane is the open wire. Change the secrets, then let an attacker swap the server's share.
Toy numbers: p = 23 and g = 5, so there are only 22 possible secrets. The attacker's secret is m = 3. The signature check stands for CertificateVerify in RFC 8446.
The full TLS 1.3 handshake takes one round trip (RFC 8446):
Finished is a MAC (a keyed checksum) over the handshake, made with keys from s. It proves both sides derived the same keys. The secrets a and b are fresh for each connection and deleted after it. A thief who later steals the server's private key can sign, but cannot decrypt recorded traffic. That is forward secrecy. TLS 1.3 removed static RSA key exchange, which lacked it.
Chapter 8
Count the handshakes in front of a request, and price them in round trips
Light in fiber covers about 200,000 km a second, 5 microseconds per kilometre. New York to London is about 5,570 km, so one round trip takes at least 56 ms. No protocol beats that. What a protocol controls is how many round trips it spends before useful bytes flow.
Count the round trips of handshake before the client may send its request. Call that number h. The request then needs one more round trip to bring back the first byte of the answer. Call the wait for that first byte T.
T equals h plus one, times R-T-T.
Add the handshake round trips h to the one round trip of the request. Multiply by the RTT. That is the wait T before the first byte.
RTT = 100 ms. TCP + TLS 1.3: h = 2, so T = 300 ms. TCP + TLS 1.2: T = 400 ms. QUIC: T = 200 ms. A pooled connection: T = 100 ms. Reuse saves two thirds of the wait on every request after the first.
Each yellow block is one handshake round trip; the blue block is the request and its answer. Drag the round trip.
Round-trip counts from RFC 9293, RFC 5246 (TLS 1.2), RFC 8446 (TLS 1.3) and RFC 9000. Transmission time, DNS and server work are left out.
Where do the counts come from? TCP's SYN and SYN-ACK take one round trip. TLS 1.3 takes one more, because the client must see the server's share before it encrypts. TLS 1.2 took two. QUIC runs the transport and TLS handshakes in the same packets, so both fit in one.
0-RTT lets a returning client send its request in the first flight, encrypted with a key from a ticket it got last time. TLS 1.3 and QUIC both offer it. RFC 8446 warns of two limits: 0-RTT data is not forward secret, and an attacker can replay it. Use it only for requests that are safe to run twice, like a GET.
Chapter 9
See one lost packet stall every stream on TCP, and only its own stream on QUIC
TCP's promise is one ordered stream. If segment 5 is lost, segments 6 to 10 wait in the buffer until 5 returns, one round trip or more later. The app reads nothing in the meantime. This is head-of-line blocking.
For a file, waiting is right. But HTTP/2 sends many requests as separate streams over one TCP connection. One lost packet of an image then stalls the script and the stylesheet too. In a video call, a late frame is worse than a missing one.
Four streams take turns on one connection. Packet 3 of stream 2 is lost and resent one round trip later. Green means the app has read it, pink means it waits in a buffer, and red means it is missing.
Illustrative: one packet leaves every tick, round robin over the streams, and a resend arrives 8 ticks after the loss. The read-out adds up the waiting ticks of every packet.
UDP (User Datagram Protocol) has an 8-byte header: two ports, a length and a checksum. Each datagram stands alone. A game sends its player position 60 times a second over UDP and keeps only the newest by sequence number. A resent old position would be useless.
QUIC (RFC 9000), the transport under HTTP/3, runs on UDP and rebuilds what it needs. Each stream has its own byte offsets, so a gap blocks only its own stream. Every packet gets a new packet number that is never reused, even for resent data, so each ACK is clear. QUIC carries TLS 1.3 inside its own handshake. A connection ID of up to 20 bytes names the connection, so a phone keeps it when it moves from Wi-Fi to cellular.
Why build on UDP? Firewalls and NAT boxes pass TCP and UDP and drop most other protocol numbers. UDP gets QUIC through. And QUIC runs in user space, so it can change without an operating system update.
Chapter 10
Find the hidden stall between Nagle and delayed ACKs, and set the few options that matter
A 1-byte write sent alone costs a 41-byte packet: 20 bytes of IP header, 20 of TCP and 1 of data. Nagle's algorithm (RFC 896) avoids that. While any sent data is still unACKed, it holds new small writes and sends them together when the ACK comes.
The receiver has its own saving. It may wait before it ACKs, hoping to send the ACK with its reply. This is a delayed ACK. RFC 9293 caps the wait below 0.5 s. Linux waits at least 40 ms, and some systems wait up to 200 ms. Now let a client write one request in two pieces.
The path's round trip is 1 ms. Pick how the client writes its request, drag the server's delayed-ACK timer, and turn TCP_NODELAY on.
Illustrative: 1 ms round trip, both writes smaller than one MSS, server replies 0.5 ms after the full request. The server only answers a complete request.
The first piece goes out at once. The second waits for an ACK under Nagle. The server waits for the rest of the request before it replies, so its ACK waits for the timer. Nothing moves for 40 ms on a 1 ms path. Setting TCP_NODELAY turns Nagle off; most RPC libraries set it.
Three more settings matter. Keep-alive probes find a peer that died without a FIN. Linux's defaults wait 7,200 s, then send 9 probes 75 s apart: 2 hours 11 minutes to notice. Many services use 60, 10 and 6: 2 minutes. Connection pools keep connections open, which skips the handshakes, slow start and TIME_WAIT. And every socket needs a connect timeout and a read timeout.
| Symptom | Measure | Likely cause |
|---|---|---|
| 40 to 200 ms on tiny requests | packet capture: second write waits for an ACK | Nagle with delayed ACK; set TCP_NODELAY |
| connect() times out | tcpdump: SYN out, no SYN-ACK back | firewall drop, full listen backlog, or host down |
| Slow copy on a fast link | ss -tin: cwnd, rwnd, rtt, retrans | window below the BDP, or loss keeping cwnd small |
| EADDRNOTAVAIL | TIME_WAIT count near the port range | a connection per request; pool instead |
| Sockets pile up in CLOSE_WAIT | ss -tan state close-wait | the app never calls close() on an error path |
Chapter 11
Keep the numbers, the checklist and the code for the next service you put on a network
One request travels like this. TCP spends a round trip agreeing on sequence numbers. TLS spends one more agreeing on a key and proving the server's name.
Then data flows, numbered and ACKed, with at most min(cwnd, rwnd) bytes in flight. The sender resends after three duplicate ACKs or a learned timeout, and halves cwnd on each loss. At the end, the closer holds its port in TIME_WAIT.
| Term | What it is | This lesson's number |
|---|---|---|
| Cumulative ACK | the next byte the receiver wants | ACK 1501 three times, then 3501 |
| RTO | SRTT + 4 · RTTVAR, doubled per timeout | 105 + 4 × 17.5 = 175 ms; floor 1 s (RFC), 200 ms (Linux) |
| TIME_WAIT budget | Rmax = P / T | 28,232 / 60 s = 470 connections a second |
| Usable window | U = rwnd − (S − A) | 24 − 20 = 4 KB |
| Window limit | X ≤ W / RTT | 64 KiB / 100 ms = 5.2 Mbps |
| BDP | B · RTT | 10 Gbps × 100 ms = 125 MB |
| Slow start | cwnd = IW · 2k | 100 KB in 3 round trips at IW 10, 5 at IW 3 |
| AIMD | +1 a round trip, halve on loss | cwnd 40 → 20 after 3 duplicate ACKs |
| Diffie-Hellman | s = Ba mod p = Ab mod p | p 23, g 5, a 6, b 15 → s = 2 |
| First byte | T = (h + 1) · RTT | 300 ms TCP + TLS 1.3, 200 ms QUIC at 100 ms |
with or finally).python# a careful client socket: TLS, no Nagle, timeouts, keep-alive, always closed import socket, ssl ctx = ssl.create_default_context() # verifies the certificate chain and the host name ctx.minimum_version = ssl.TLSVersion.TLSv1_3 def fetch(host, path="/"): raw = socket.create_connection((host, 443), timeout=3) # connect timeout: 1 RTT handshake raw.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) # no Nagle stall raw.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) # find dead peers with ctx.wrap_socket(raw, server_hostname=host) as tls: # TLS 1.3: 1 more RTT tls.settimeout(10) # read timeout tls.sendall(f"GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n".encode()) return tls.version(), tls.recv(4096) # closed on exit, even on error
Now press Present or Teach and explain five things from memory. Explain cumulative ACKs and fast retransmit, the RTO, TIME_WAIT and the port budget, the BDP, and the sawtooth. Then go back to the hero, set the loss to 40% and compare raw IP with TCP.