Network Foundations

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.

Send a message through a lossy network

20%

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

The Network Promises Nothing

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.

Read one packet as each hop reads it

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.

  1. Sequence numbers and ACKs: how the receiver says which bytes it has.
  2. Timers: how long to wait before resending.
  3. Opening and closing: the handshake, the close and TIME_WAIT.
  4. Flow control: the receiver sets the pace.
  5. The pipe: window, round trip and bandwidth.
  6. Congestion control: slow start and the sawtooth.
  7. TLS 1.3: a shared secret over an open wire.
  8. Round trips: what each handshake costs before the first byte.
  9. UDP and QUIC: escaping head-of-line blocking.
  10. TCP in production: Nagle, delayed ACKs, keep-alive and pools.
  11. The field guide: numbers, checklist, code and links.
You send packets 1, 2, 3 and 4 over raw IP. The receiver gets 3, 1, 1. Which problems happened?

Chapter 1

Sequence Numbers and Acknowledgments

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).

client → server SYN seq = 1000 "my bytes start after 1000" server → client SYN-ACK seq = 5000, ack = 1001 "mine start after 5000; send 1001 next" client → server ACK ack = 5001 "send 5001 next"

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.

Lose a segment and watch the ACKs

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.

A receiver holds bytes 1 to 1000 and 2001 to 3000. Bytes 1001 to 2000 were lost. Which ACK number does it send?

Chapter 2

Timeouts That Learn the Round Trip

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.

Say it aloud

R-T-O equals S-R-T-T plus four times R-T-T-var.

RTO
R-T-O the retransmission timeout: how long the sender waits for an ACK before it resends.
SRTT
S-R-T-T the smoothed round-trip time. Each new sample R moves it one eighth of the way: SRTT ← 7/8 · SRTT + 1/8 · R.
4
four the safety factor K from RFC 6298.
RTTVAR
R-T-T-var the round-trip variation: the smoothed gap between samples and SRTT. Each sample moves it one quarter of the way: RTTVAR ← 3/4 · RTTVAR + 1/4 · |SRTT − R|, computed before SRTT changes.
In plain words

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 numbers

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.

Track a noisy round trip

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.

±20 ms

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.

SRTT is 50 ms and RTTVAR is 10 ms. With no floor, what is the RTO, and what is it after two timeouts in a row?

Chapter 3

Opening, Closing and TIME_WAIT

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.

A → B FIN A: FIN_WAIT_1 "I have nothing more to send" B → A ACK A: FIN_WAIT_2 B: CLOSE_WAIT (B may still send) B → A FIN B: LAST_ACK (B's app called close()) A → B ACK A: TIME_WAIT B: CLOSED

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?

Say it aloud

R-max equals P over T.

Rmax
R-max the most new connections a second that one source address can open to one destination address and port, without running out of ports.
P
P the ephemeral ports available. Linux's default range 32768 to 60999 holds 28,232.
T
T how long each closed connection holds its port in TIME_WAIT, in seconds.
In plain words

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.

With numbers

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.

Run out of ports

Each cell is about 280 ports. Pink cells hold sockets in TIME_WAIT. Drag the rate of new connections, then turn on a pool.

300

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.

A server shows 30,000 sockets in CLOSE_WAIT. What does that mean?

Chapter 4

Flow Control: The Receiver Sets the Pace

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.

Say it aloud

U equals r-wind minus the quantity S minus A.

U
U the usable window: new bytes the sender may put on the wire now.
rwnd
r-wind the receive window from the latest ACK: free bytes in the receiver's buffer.
S
S the number of the last byte sent.
A
A the number of the last byte ACKed. S minus A is the bytes in flight.
In plain words

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 numbers

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.

Slow the reader, shrink the window

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.

2 segments

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.

The receiver advertises rwnd = 30 KB. The sender has 20 KB in flight and 100 KB waiting. How much more may it send now?

Chapter 5

Fill the Pipe: Window, Round Trip and Bandwidth

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.

Say it aloud

X is at most W over R-T-T.

X
X the throughput of one connection, in bytes a second.
W
W the window in bytes: the smaller of rwnd and the congestion window.
RTT
R-T-T the round-trip time in seconds.
In plain words

The sender moves one window W, then waits one RTT. Divide W by RTT. No link speed beats that limit.

With numbers

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.

Say it aloud

B-D-P equals B times R-T-T.

BDP
B-D-P the bandwidth-delay product: the bytes in flight that keep the link busy.
B
B the link bandwidth in bytes a second. Divide bits by 8.
RTT
R-T-T the round-trip time in seconds.
In plain words

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.

With numbers

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.

Fill the pipe

The pipe's area is the BDP. Blue is the window in flight. Change the link, the round trip and the window.

10 Gbps
100 ms

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.

A 1 Gbps link has a 40 ms round trip. What is the BDP?

Chapter 6

Congestion Control: Slow Start and AIMD

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.

Say it aloud

c-wind sub k equals I-W times two to the k.

cwndk
c-wind sub k the congestion window after k round trips of slow start, in segments.
IW
I-W the initial window: 3 segments of 1,460 bytes under RFC 5681, 10 under RFC 6928 (the Linux default).
2k
two to the k one doubling per round trip, k round trips in a row.
In plain words

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.

With numbers

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:

each round trip, cwnd ≥ ssthresh: cwnd = cwnd + 1 3 duplicate ACKs: ssthresh = max(flight / 2, 2); cwnd = ssthresh fast recovery timeout: ssthresh = max(flight / 2, 2); cwnd = 1 back to slow start

Draw the sawtooth

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.

A Reno sender has cwnd = 40 segments in congestion avoidance. Three duplicate ACKs arrive. What happens?

Chapter 7

TLS 1.3: A Shared Secret Over an Open Wire

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.

Say it aloud

s equals B to the a, mod p, which equals A to the b, mod p.

s
s the shared secret. Both sides feed it into a key function (HKDF) to make the encryption keys.
B
capital B the server's public share, g to the b mod p. It travels in the clear.
a
a the client's secret number. It never leaves the client.
p
p the public prime. "mod p" keeps the remainder after dividing by p.
A
capital A the client's public share, g to the a mod p.
b
b the server's secret number.
p
p the same public prime on the server's side.
In plain words

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.

With numbers

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.

Agree on a secret in public

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.

6
15

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):

client → server ClientHello versions, cipher suites, key share A server → client ServerHello key share B; then encrypted: EncryptedExtensions, Certificate, CertificateVerify, Finished client → server Finished and the first request, encrypted

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.

The client sends its key share before it sees the certificate. Why can an attacker not swap the server's share unseen?

Chapter 8

Round Trips Before the First Byte

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.

Say it aloud

T equals h plus one, times R-T-T.

T
T the time from "connect" to the first byte of the response, with no server think time.
h
h the handshake round trips before the request may leave: TCP 1, TCP + TLS 1.3 2, TCP + TLS 1.2 3, QUIC 1, a resumed 0-RTT or a pooled connection 0.
1
one the round trip of the request and its answer.
RTT
R-T-T the round-trip time of the path.
In plain words

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.

With numbers

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.

Race to the first byte

Each yellow block is one handshake round trip; the blue block is the request and its answer. Drag the round trip.

100 ms

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.

The RTT is 50 ms. How long until the first response byte over a new TCP + TLS 1.3 connection, and over a reused one?

Chapter 9

UDP and QUIC: Escaping Head-of-Line Blocking

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.

Lose one packet, count who waits

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.

Four HTTP/2 requests share one TCP connection. A packet of request 3 is lost. What happens to requests 1, 2 and 4?

Chapter 10

TCP in Production

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.

Find the hidden stall

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.

40 ms

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.

SymptomMeasureLikely cause
40 to 200 ms on tiny requestspacket capture: second write waits for an ACKNagle with delayed ACK; set TCP_NODELAY
connect() times outtcpdump: SYN out, no SYN-ACK backfirewall drop, full listen backlog, or host down
Slow copy on a fast linkss -tin: cwnd, rwnd, rtt, retranswindow below the BDP, or loss keeping cwnd small
EADDRNOTAVAILTIME_WAIT count near the port rangea connection per request; pool instead
Sockets pile up in CLOSE_WAITss -tan state close-waitthe app never calls close() on an error path
Small RPCs take 40 ms on a 1 ms path. The client writes each request in two pieces and has not set TCP_NODELAY. What is happening?

Chapter 11

The Field Guide

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.

Terms and numbers

TermWhat it isThis lesson's number
Cumulative ACKthe next byte the receiver wantsACK 1501 three times, then 3501
RTOSRTT + 4 · RTTVAR, doubled per timeout105 + 4 × 17.5 = 175 ms; floor 1 s (RFC), 200 ms (Linux)
TIME_WAIT budgetRmax = P / T28,232 / 60 s = 470 connections a second
Usable windowU = rwnd − (S − A)24 − 20 = 4 KB
Window limitX ≤ W / RTT64 KiB / 100 ms = 5.2 Mbps
BDPB · RTT10 Gbps × 100 ms = 125 MB
Slow startcwnd = IW · 2k100 KB in 3 round trips at IW 10, 5 at IW 3
AIMD+1 a round trip, halve on losscwnd 40 → 20 after 3 duplicate ACKs
Diffie-Hellmans = Ba mod p = Ab mod pp 23, g 5, a 6, b 15 → s = 2
First byteT = (h + 1) · RTT300 ms TCP + TLS 1.3, 200 ms QUIC at 100 ms

Checklist

  1. Reuse connections through a pool; never open one per request.
  2. Set TCP_NODELAY on request-response sockets.
  3. Set a connect timeout and a read timeout on every call.
  4. Close sockets in every error path (with or finally).
  5. Size buffers to the BDP of your longest path; keep window scaling on.
  6. Verify certificates; never turn verification off in production.
  7. Use 0-RTT only for requests that are safe to replay.
  8. Watch TIME_WAIT and CLOSE_WAIT counts, retransmissions, and RTT.

The core as code

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

Keep going

The takeaway. TCP builds a reliable stream from numbers, ACKs and timers, at the price of round trips. A window caps each round trip, so W / RTT caps throughput. Congestion control and TLS each add rules on top, and QUIC rearranges them to spend fewer round trips and block fewer streams.

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.

Network Foundations
RFC 9293 · RFC 8446 · RFC 9000 · Back to Gleams