Lecture 2 · Communication: latency, bandwidth and the network stack

Distributed Systems · Lecture 02。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: CMU 15-440/640 Spring 2026, the course theme “communication latency and bandwidth” and the first block of lectures before Problem Set 1. Reading (optional, course list): A. Singla et al., The Internet at the Speed of Light (HotNets 2014). Problem set: PS1 (assigned after Lecture 4) has latency/bandwidth and protocol-design questions; this lecture gives the tools, not the answers. Project: P1 (in progress) talks over TCP sockets. Sources: the public course page and project/problem-set handouts; standard networking material (Kurose & Ross, Computer Networking; Peterson & Davie, Computer Networks), RFC 896 (Nagle’s algorithm), RFC 6928 (initial window of 10 segments), J. Dean and L. A. Barroso, The Tail at Scale (CACM 2013). The slides are not public; this lecture is not a transcript. Every number labelled “measured” or “simulated” comes from the code in code/lecture02/, run on the author’s machine (Apple M4 Pro, macOS, Python 3.13). Code: code/lecture02/. Reading time: ~75 minutes, plus ~25 to run the demos.


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Split the one-way delay of a packet into processing, queueing, transmission and propagation, and say which one dominates on a given link — and therefore which fix helps.
  2. Compute the delivery time of a message across several store-and-forward hops, with and without packetization, and explain why packets make it faster (pipelining) but not arbitrarily small packets (headers).
  3. Compute the bandwidth-delay product and use it to predict the throughput of stop-and-wait and sliding-window protocols.
  4. Explain what layering buys and costs, and what IP, TCP and UDP each promise.
  5. Estimate what a new TCP connection costs (handshake, slow start, TLS) and why short transfers over long paths never reach the link’s bandwidth.
  6. Recognize three practical TCP traps — small writes, Nagle + delayed ACK, and lost message boundaries — and their fixes.
  7. Explain why fan-out turns a rare slow server into a common slow request, and what hedged requests and partial answers buy.

0.2 Prerequisites and scope

  • Prerequisite: Lecture 1 (the T = L + 8S/B model, dsim), and 15-213-level sockets (socket, connect, send, recv).
  • Scope: the network as a distributed-systems programmer needs it: a model precise enough to predict how long messages take and how protocols behave. Routing algorithms, link-layer details and congestion-control theory belong to a networking course (15-441); we touch them only where they change what a distributed program sees.

0.3 Section → code map

SectionIdeaDemo in code/lecture02/
§2the four components of delay01_delay_components.py Part A
§3store-and-forward, pipelining, the best packet size01_delay_components.py Parts B–C (formula vs dsim)
§4layering and header overhead03_tcp_model.py Part A
§5bandwidth-delay product, stop-and-wait vs windows, queues02_windows.py
§6handshake, slow start, Nagle, framing, system calls03_tcp_model.py Parts B–C, 04_loopback_tcp.py (real)
§7the tail at scale05_tail_at_scale.py
allevery formula as a tested functionnetcalc.py (python3 netcalc.py runs its self-test)

dsim.py (Lecture 1) gained two knobs for this lecture: a link bandwidth (a message occupies the link for 8·size/bandwidth, and later messages queue behind it) and an optional queue limit. Without them it behaves exactly as before; Lecture 1’s outputs are unchanged.

0.4 Notation and units

  • S message size (bytes), B bandwidth (bits/s), d propagation delay (ms), RTT round-trip time, W window (bytes or packets), h number of hops, H header bytes per packet.
  • SI units: 1 KB = 10³ B, 1 Mbps = 10⁶ bit/s. Times in ms; µs = microseconds.
  • “Packet” means a unit that a switch forwards as a whole; “segment” is TCP’s name for its packets; “MSS” (maximum segment size) is the payload of a full TCP packet, 1448 bytes on standard Ethernet with timestamps.

1. Why a distributed-systems course needs a network model

In Lecture 1 we treated the network as a box that delays messages by L + 8S/B and sometimes loses them. That model already explained a lot: small messages are latency-bound, big ones bandwidth-bound; light is slow. But it is too crude to answer the questions you will meet in Project 1 and Problem Set 1:

  • A message crosses five switches. Is the delay five times the single-link delay?
  • My protocol sends a packet and waits for an acknowledgment. Why does it use 4% of a 10 Mbps link?
  • My RPC server is on a 1 Gbps network 80 ms away. Why does fetching 1 MB take 640 ms instead of 8?
  • I wrote two small send() calls and a recv(). Why is that slower than one send()?
  • Each of my back ends is fast 99% of the time. Why are most of my user requests slow?

Each answer is a small model with a formula, and each formula is a function in netcalc.py that the demos test against the simulator or against real sockets. We build them in order of scope: one link (§2), a path of links (§3), the protocol stack (§4), a protocol keeping a link busy (§5), TCP specifically (§6), and many servers at once (§7).


2.1 Intuition: cars on a toll road

Picture a convoy of cars (the bits of a packet) leaving a city on a toll road to the next city.

  • Processing: the toll booth inspects the convoy’s ticket — a router reads the packet’s header, checks it, looks up where it goes. Microseconds.
  • Queueing: if other convoys are already waiting at the on-ramp, ours waits its turn. Zero on an idle link, unbounded on a busy one; the only delay that depends on other traffic.
  • Transmission (serialization): the on-ramp admits one car at a time; a convoy of 8S cars on a ramp admitting B cars per second needs 8S/B seconds just to get onto the road. It depends on the packet’s size and the link’s bandwidth — not on the distance.
  • Propagation: driving to the next city, at the speed limit — in fiber about 204 km per ms (two-thirds of c). It depends on the distance — not on the packet’s size — and no amount of money makes it faster.

dlink=dproc+dqueue+8SB+distancespeed.d_{\text{link}} = d_{\text{proc}} + d_{\text{queue}} + \frac{8S}{B} + \frac{\text{distance}}{\text{speed}}.

2.2 Which one dominates?

Demo 01_delay_components.py, Part A, evaluates the four parts for one 1500-byte packet (processing assumed 5 µs, an idle link):

linkprocessingtransmissionpropagationdominant
same rack, 10 Gbps, 2 m5.0 µs1.2 µs10 nsprocessing
campus Ethernet, 1 Gbps, 1 km5.0 µs12.0 µs4.9 µstransmission
home uplink, 10 Mbps, 10 km5.0 µs1.2 ms49 µstransmission
Pittsburgh → London, 10 Gbps, 5,979 km5.0 µs1.2 µs29.3 mspropagation
geostationary satellite, 50 Mbps, 71,572 km up and down5.0 µs240 µs238.7 mspropagation

The lesson is that “make the network faster” is not one fix:

  • where transmission dominates (slow access links), more bandwidth helps directly;
  • where propagation dominates (long distances), bandwidth is irrelevant; only moving the endpoints closer helps — caching, replication and edge computing (Part II);
  • where processing dominates (inside a data center), the software stack is the bottleneck. This is why data-center RPC systems fight for every microsecond in the kernel and the NIC, and why, in Lecture 1, a loopback RPC already cost ~15 µs with no wire at all.

And queueing — zero in this table — is the wild card. Because it depends on load, it is what makes latency a distribution rather than a number (§7), and it can exceed all the others (§5.3; Lecture 9’s buffer bloat).


3.1 Store-and-forward

A packet switch (router, Ethernet switch) must receive a whole packet before forwarding it: it needs the full packet to verify its checksum and to read the header that says where it goes. So if a message of S bytes is sent as one packet over h hops, every hop pays the full transmission time:

Tone packet=∑i=1h(8SBi+di).T_{\text{one packet}} = \sum_{i=1}^{h}\left(\frac{8S}{B_i} + d_i\right).

Demo 01, Part B: 1 MB over 5 hops of 100 Mbps with 1 ms of propagation each takes 405 ms this way — five times the 80 ms it takes to transmit 1 MB once.

3.2 Packetization pipelines the hops

Cut the message into n packets of p bytes (each with an H-byte header, so q = p + H bytes on the wire). Now while switch 2 forwards packet 1, switch 1 is already receiving packet 2: the hops work in parallel on different packets, like stations on an assembly line. The first packet pays every hop; each further packet adds only the transmission time of the slowest hop:

Tpackets=∑i=1h(8qBi+di)+(n−1) max⁡i8qBi.T_{\text{packets}} = \sum_{i=1}^{h}\left(\frac{8q}{B_i} + d_i\right) + (n-1)\,\max_i \frac{8q}{B_i}.

how 1 MB is sent (5 hops, 100 Mbps, 1 ms each, 40 B header)formuladsim
one 1 MB packet405.016 ms405.016 ms
100 KB packets117.045 ms117.045 ms
10 KB packets88.533 ms88.533 ms
1460 B packets87.672 ms87.672 ms

The dsim column is not the formula re-typed: it is four simulated switch nodes forwarding 685 packet objects through links with bandwidth and queues, and it agrees with the closed form exactly. Packetization makes the transfer 4.6× faster on this path. This pipelining effect is one of the two reasons the Internet is packet-switched (the other is statistical multiplexing: many conversations share each link, using it only when they have something to send, instead of reserving a circuit).

3.3 Why not tiny packets? Headers

Every packet carries a header. With a 40-byte header, 50-byte packets spend 44% of the wire on headers. Part C sweeps the payload size:

payload per packetpacketsheader sharetime (ms)
5020,00044.4%149.03
2005,00016.7%101.08
1,4606852.7%87.67
3,0003341.3%87.04
100,000100.0%117.04
1,000,00010.0%405.02

There is a sweet spot. On h equal hops, ignoring propagation, T·B/8 ≈ (h−1)(p+H) + S + S·H/p: the first term (pipeline fill) grows with p, the last (headers) shrinks. Setting the derivative to zero:

p∗=S Hh−1  =  106⋅404≈3162 bytes,p^* = \sqrt{\frac{S\,H}{h-1}} \;=\; \sqrt{\frac{10^6 \cdot 40}{4}} \approx 3162 \text{ bytes},

and an exhaustive search in the demo finds 3,180 B. In practice the link layer decides for you: standard Ethernet carries at most 1,500-byte IP packets (the MTU, maximum transmission unit), which is near enough to the optimum for typical paths.


4. Layering: what each layer promises, and what it costs

4.1 Why layers

Communication is split into layers, each using only the service of the one below it:

layerunitwhat it promisesexample
applicationmessagewhatever the application definesHTTP, your RPC protocol (P1), DNS
transportsegment / datagramTCP: a reliable, ordered byte stream between two processes. UDP: individual datagrams, best effortTCP, UDP, QUIC
networkpacketbest effort delivery of a packet to a host anywhere: may lose, duplicate, reorder, delayIP
linkframedelivery to the next hop on one physical networkEthernet, Wi-Fi

This is the course theme “abstraction and modularity” applied to networks: a web browser does not care whether the bits travel over Wi-Fi or fiber, and a new link technology does not require new applications. Each layer adds a header in front of the data it receives from above (encapsulation), and the matching layer on the receiving host removes it.

Two consequences matter for us:

  1. IP promises almost nothing. Loss, reordering, duplication and delay are normal at the network layer. Anything stronger — reliability, ordering, exactly-once — must be built above it, by TCP or by the application. (The end-to-end argument, Lecture 4, explains where it should be built.)
  2. Headers cost bandwidth, and they cost most for small messages. Demo 03_tcp_model.py, Part A, counts TCP (20 B) + the common timestamp option (12) + IPv4 (20) + Ethernet framing on the wire (14 header + 4 checksum + 8 preamble + 12 inter-frame gap = 38): 90 bytes per packet.
payload per packetshare of the wire that is datagoodput on 1 Gbps
1 B1.1%11 Mbps
100 B52.6%526 Mbps
1448 B (full MSS)94.1%941.5 Mbps

The 941.5 Mbps for full packets is the well-known practical ceiling of TCP over gigabit Ethernet, and netcalc.py’s self-test checks it. A protocol that sends one tiny packet per small RPC wastes the network before latency is even counted.

4.2 TCP vs UDP in one table

TCPUDP
connectionyes: a handshake before data (§6.1)none
reliabilityretransmits lost segmentsnone: a lost datagram is gone
orderingbytes delivered in orderdatagrams may arrive in any order
message boundariesnone: a byte stream (§6.4)kept: one send = one datagram
flow / congestion controlyes: sender slows down for a slow receiver or a congested networknone
head-of-line blockingone lost segment delays all later bytesnone
typical usesRPC, web, files (P1, P2)DNS, real-time media, games, and new transports built on it (QUIC)

UDP is not “TCP but worse”: it is the right choice when the application has its own idea of what to do about loss (a video frame that arrives late is useless anyway), or when it wants to build its own reliability with different trade-offs.


5. Keeping the pipe full: the bandwidth-delay product and windows

5.1 Intuition: a pipe full of water

A link is a pipe. Its bandwidth is the pipe’s cross-section; its round-trip time is the time for water to go to the far end and for a message (“got it”) to come back. The volume of water in flight when the pipe is full is

BDP=B×RTT,\text{BDP} = B \times RTT,

the bandwidth-delay product. A sender that waits for acknowledgments can only keep the pipe full if it is allowed to have at least a BDP of unacknowledged data outstanding. With a window of W bytes, it sends W per round trip:

throughput=min⁡ ⁣(B, WRTT).\text{throughput} = \min\!\left(B,\ \frac{W}{RTT}\right).

5.2 Stop-and-wait vs sliding windows (simulated)

Demo 02_windows.py transfers a 500 KB file in 1000-byte packets over a 10 Mbps link with 10 ms of propagation each way (RTT including transmission: 20.85 ms; BDP = 26,064 bytes ≈ 26.1 packets). The sender keeps at most W unacknowledged packets in flight; the receiver acknowledges each packet; each packet has a 100 ms retransmission timer (a simplified selective-repeat protocol, close to TCP with selective acknowledgments but without congestion control).

window Wmodel Mbpsdsim Mbpsspurious retransmissionsmean RTTMbps with 1% loss each way
1 (stop-and-wait)0.380.38020.9 ms0.35
41.531.54020.9 ms1.40
166.146.06021.0 ms4.99
269.989.73021.4 ms7.40
6410.009.76050.5 ms9.61
12810.005.4955660.1 ms4.85

Read it row by row:

  • Stop-and-wait wastes 96% of the link. It transmits for 0.8 ms and then waits 20 ms for the acknowledgment: the link is busy 3.8% of the time. On the satellite link of §2 the same protocol would use 0.05% of it (Exercise 4).
  • Throughput grows linearly with the window up to the BDP, then saturates; up to W = 64 the simulator stays within 2.4% of min(B, W/RTT) (the gap is the start-up and the final round trip).
  • A window larger than the BDP buys nothing but a queue. At W = 64, 38 extra packets sit in the sender’s link queue, and the mean RTT more than doubles (20.9 → 50.5 ms) for zero extra throughput. That is pure queueing delay — the mechanism behind buffer bloat (Lecture 9).
  • At W = 128 the network collapses with no loss at all. 102 packets queued × 0.8 ms each = 82 ms of queueing; adding the base RTT, packets wait longer than the 100 ms retransmission timer. Timers fire for packets that are merely waiting, the sender retransmits them (556 spurious retransmissions), the copies take up link time, the queue grows further, and goodput falls to 5.49 Mbps. A fixed timeout combined with a big queue is a self-inflicted congestion collapse. Two cures appear later: timeouts that adapt to the measured RTT (Lecture 4) and senders that shrink their window when the network signals congestion (TCP’s congestion control; Lecture 9).
  • Windows make loss cheap. With 1% loss in each direction, stop-and-wait loses 8% of its (already tiny) throughput because every loss stalls the link for a whole timeout; W = 64 still achieves 9.61 Mbps because other packets keep flowing while one waits to be resent.

The same “keep W requests outstanding” idea applies above the transport layer: an RPC client that issues one call, waits, then issues the next is a stop-and-wait protocol over a WAN, and pipelining or batching calls is the fix (Lecture 3).


6. TCP in practice: what a connection costs

6.1 The handshake

Before any data flows, TCP exchanges SYN, SYN-ACK and ACK so that both sides agree on initial sequence numbers and know the other is there. The client can send its request right after the third message, so a new connection costs one extra RTT before the first request leaves. TLS (encryption) adds one more RTT in TLS 1.3 (two in TLS 1.2).

6.2 Slow start

A new connection does not know how much bandwidth the path has — sending a BDP’s worth at once into a slower bottleneck would overflow its queue. So TCP starts with a small congestion window (today usually 10 segments, ≈ 14.5 KB; RFC 6928) and doubles it every round trip until it sees loss or reaches the path’s capacity. A transfer of S bytes therefore needs about log₂(S / (10·MSS)) round trips before the connection is even running at full speed.

Demo 03_tcp_model.py, Part B, models a fetch on a 1 Gbps path (best case: no loss, instant server):

RTTobjectslow-start roundsreused conn.new conn.new + TLS 1.3throughput (new conn.)
1 ms1 MB711.7 ms12.7 ms13.7 ms632 Mbps
20 ms1 KB120.0 ms40.0 ms60.0 ms0.2 Mbps
20 ms1 MB7140.8 ms160.8 ms180.8 ms49.8 Mbps
80 ms1 KB180.0 ms160.0 ms240.0 ms0.05 Mbps
80 ms1 MB7560.8 ms640.8 ms720.8 ms12.5 Mbps
80 ms100 MB131.60 s1.68 s1.76 s475 Mbps

and Part C counts the round trips slow start needs to open the window to the BDP: 4 at 1 Gbps × 1 ms, 8 at 1 Gbps × 20 ms, 10 at 1 Gbps × 80 ms (800 ms of ramp-up), 13 at 10 Gbps × 80 ms.

The conclusion is striking: over long paths, transfers are bound by round trips, not by bandwidth. A 1 MB fetch across a continent achieves 1.25% of a gigabit link; the same fetch inside a data center achieves 63%. This is the quantitative reason for three design rules you will see all semester: keep connections open and reuse them; send fewer, larger messages; and move data close to where it is used (caching, edge servers).

6.3 Real costs on one machine (measured)

Demo 04_loopback_tcp.py measures TCP and UDP over 127.0.0.1. Loopback has no wire and no distance, so these are the costs of the software. Ranges over five runs:

Part A — the size of each send() matters. Over one connection:

bytes per send()throughputtime per send() call
11.2–1.4 MB/s~0.8 µs
1617–21 MB/s~0.8–0.9 µs
256~190 MB/s~1.4 µs
4,096~2.1 GB/s~2 µs
1 MB17.4–19.1 GB/s~55–60 µs

A send() system call costs about a microsecond however little it carries, so small writes are bound by system calls: 1 MB writes move about 1,000× more data per second than 16-byte writes over the same connection. Batching — building a whole message in memory and sending it in one call — is the fix.

Part B — a new connection per request costs 52–55 µs vs 15–16 µs on a reused one (~3.4×), even with zero distance. Over a WAN the difference is a whole extra RTT (§6.1).

6.4 Two traps that bite RPC protocols

Nagle’s algorithm and delayed ACKs (Part C). To avoid flooding the network with tiny packets, TCP by default applies Nagle’s algorithm (RFC 896): while any sent data is still unacknowledged, small writes are held back and coalesced. Many receivers, meanwhile, delay their ACKs briefly (on Linux typically up to 40 ms), hoping to piggyback them on a reply. Now consider the common pattern write(header); write(body); read(reply): the header goes out; the body is held until the header is acknowledged; the receiver withholds the ACK hoping to reply — but cannot reply until the body arrives. On Linux this classically costs ~40 ms per exchange. On this macOS loopback the measured cost is smaller but real: 21.5–22.8 µs with Nagle vs 16.0–17.4 µs with TCP_NODELAY (~1.35×): the body waits for one ACK. The fixes: assemble the whole request and write it once (the better fix), or set TCP_NODELAY for latency-sensitive request/response protocols.

TCP has no message boundaries (Part D). The demo sends 1,000 separate 10-byte messages; the receiver gets all 10,000 bytes in 2 recv() calls (in all five runs). The sender’s 1,000 boundaries simply do not exist on the receiving side. The opposite also happens: one large send() can arrive in many pieces, and one recv() can return half of a message. UDP is different: 200 datagrams arrived as 200 datagrams of exactly 10 bytes each. Every protocol over TCP must therefore define its own framing — typically a fixed-size length prefix before each message, or a delimiter — and the receiver must loop until it has a whole message (recv_exact in the demos). Lecture 3 builds this, and Project 1’s client–server protocol needs it.


7. The tail at scale

7.1 Intuition: waiting for the slowest of many

Lecture 1 showed that latency is a distribution with a tail. Now suppose a service answers each user request by asking n servers in parallel — a search over a sharded index, an LLM request that touches several tiers, a page that calls a dozen microservices — and must wait for all of them. The request is as slow as the slowest server. If each server is slow with probability q, independently, then

P(request hits at least one slow server)=1−(1−q)n.P(\text{request hits at least one slow server}) = 1 - (1-q)^n.

With q = 1%: n = 10 → 9.6%; n = 100 → 63%; n = 1000 → essentially always. A rare event per server becomes the common event per request.

7.2 The numbers (exact, checked by simulation)

Demo 05_tail_at_scale.py gives each leaf server a latency of 0.5–1.5 ms 99% of the time and 20–80 ms 1% of the time (a “hiccup”: a garbage-collection pause, a busy disk). The request latency is the max over n leaves, whose distribution is exactly F(x)^n; the demo inverts it by bisection, and a 5,000-request Monte Carlo run agrees (median 38.36 vs 38.55 ms at n = 100).

fan-out nP(any hiccup)plain medianplain p99hedged medianhedged p99wait-for-99% medianwait-for-99% p99
11.0%1.011.501.011.501.011.50
109.6%1.4473.971.442.87(= plain)
10063.4%38.5579.402.272.961.4971.05
50099.3%71.6979.882.8353.821.5058.51
1000100.0%75.8479.942.9061.691.5051.30

(milliseconds). Note the first row: the hiccups do not show even in a single leaf’s p99, because they are the slowest 1%. Measuring each server in isolation would say “p99 = 1.5 ms, all good”, while 63% of user requests at fan-out 100 take 20–80 ms.

7.3 Two remedies, two prices

  • Hedged requests (Dean & Barroso): if a leaf has not answered by its 95th percentile (1.46 ms here), send the same request to a second replica and use whichever answers first. The extra load is only 5%, yet the n = 100 median drops from 38.55 to 2.27 ms and the p99 from 79.40 to 2.96 ms. Hedging has its own tail: a leaf whose primary and backup both hiccup has probability ~10⁻⁴, and with 500 leaves 4.9% of requests contain one, so the p99 climbs back to 53.8 ms. (Hedging is safe only for requests that can be executed twice without harm — idempotent ones, Lecture 4.)
  • Good-enough answers: return once 99% of the leaves have answered (a search result missing one shard is usually acceptable). No extra load; the median is fixed (1.49 ms at n = 100), but the p99 is not (71.05 ms), because 26% of requests see two or more hiccups.

The general lesson, which recurs in Lectures 11–12 and in Project 3: composition moves you to the tail of the distribution, so engineer and measure for the tail, not the mean.


8. Putting it together: a latency budget

A user in Pittsburgh taps “send” in a chat app. The request (2 KB) goes over Wi-Fi (15 ms one way, 100 Mbps) to a regional server, which makes an RPC to a database 20 ms round trip away, and replies (1 KB). What dominates?

  • Wi-Fi uplink: 15 ms + 2·10³·8 / 10⁸ s = 15.16 ms; downlink similar: 15.08 ms.
  • If the app opens a new TLS connection: +2 round trips over Wi-Fi ≈ 60 ms more.
  • Server → database: one RTT (20 ms) on a reused connection; on a new one, 40 ms.
  • If the server’s request fans out to 100 shards with 1% hiccups: +~37 ms in the median (§7).

So a carelessly built path costs ~170 ms; a careful one (reused connections, one round trip to the database, hedged shard reads) ~55 ms — and none of the difference is about bandwidth. That is the shape of nearly every performance question in this course.


Summary

  • One-way delay = processing + queueing + transmission (8S/B) + propagation (distance/speed). Transmission ignores distance; propagation ignores size; queueing depends on everyone else. Find the dominant term before choosing a fix.
  • Store-and-forward makes a single big packet pay every hop in full (1 MB over 5 hops: 405 ms); packetization pipelines the hops (87.7 ms). Headers bound how small packets should be: p* = √(SH/(h−1)) (≈3.2 KB here; Ethernet’s 1500-byte MTU in practice).
  • Layering gives modularity at a cost of ~90 bytes of headers per packet on TCP/IP/Ethernet: 94% efficiency for full packets, 1% for 1-byte ones. IP is best effort; TCP gives a reliable ordered byte stream; UDP gives datagrams.
  • Bandwidth-delay product = how much must be in flight to fill the pipe. Throughput = min(B, W/RTT): stop-and-wait used 3.8% of a 10 Mbps × 21 ms link; a window above the BDP only builds a queue — and with a fixed timer, an oversized window caused 556 spurious retransmissions and halved goodput with zero loss.
  • New TCP connections pay a handshake RTT (+1 for TLS 1.3) and slow start (window doubling from 10 segments): over long paths, transfers are bound by round trips, not bandwidth (1 MB at 80 ms RTT: 12.5 Mbps on a 1 Gbps link).
  • Measured on loopback: each send() costs ~1 µs however small (batch your writes); a new connection costs ~3.4× a reused one; Nagle + small writes add an ACK wait (one write per message, or TCP_NODELAY); TCP loses message boundaries (1,000 sends → 2 recvs), so protocols need framing.
  • Fan-out turns rare slowness into common slowness: 1 − (1−q)^n; at n = 100, 1% hiccups make the median request 38.6 ms. Hedged requests (5% extra load) and partial answers trade load or completeness for the tail.

Common pitfalls

  • Mixing bits and bytes (B is in bits per second; sizes are in bytes): a factor-of-8 error. Write the 8 explicitly.
  • Treating bandwidth as the fix for latency. On a long path, a 10× faster link barely changes a 100-byte RPC or even a 1 MB fetch.
  • Ignoring the hop count: a single large message over h store-and-forward hops pays its transmission time h times.
  • Assuming one send() = one recv() on TCP. Always frame messages and loop on reads.
  • Writing a request in several small pieces (header, then body) with Nagle on: an extra ACK wait per request.
  • Opening a connection per request across a WAN: an extra RTT (two or three with TLS) every time.
  • Sizing windows or buffers “as big as possible”: beyond the BDP they only add queueing delay — and with fixed timers can trigger spurious retransmissions.
  • Reporting the mean or a single server’s p99 for a fan-out service: the request sees the max.

Exercises

  1. Which delay dominates? A 64-byte and a 1500-byte packet each cross a 100 Mbps link of 2,000 km of fiber. Compute the transmission and propagation delays. Which dominates in each case, and would upgrading to 1 Gbps help?

    AnswerTransmission: 64·8/10⁸ s = 5.12 µs; 1500·8/10⁸ s = 120 µs. Propagation: 2000 km / 204 km/ms ≈ 9.79 ms for both. Propagation dominates both by a factor of 80–1,900. A 1 Gbps link would cut transmission tenfold (to 0.5 and 12 µs) and change the total by less than 1.2%: the fix for this link is distance, not bandwidth.
  2. Store-and-forward. A 10 MB file crosses 3 hops of 1 Gbps with 0.5 ms propagation each. How long does it take as one packet, and as 1460-byte payloads with 40-byte headers?

    AnswerOne packet: each hop takes 10⁷·8/10⁹ s = 80 ms + 0.5 ms, so 3 × 80.5 = 241.5 ms. Packets: q = 1500 B, transmission 12 µs per hop; n = ⌈10⁷/1460⌉ = 6,850 packets. T = 3 × (0.012 + 0.5) + 6,849 × 0.012 ≈ 1.536 + 82.19 ≈ 83.7 ms (`netcalc.store_and_forward_ms` gives 83.716 ms). Packetization saves almost two full transmission times.
  3. The classic 64 KB window. Without TCP’s window-scaling option, the receive window is at most 65,535 bytes. What throughput can a connection achieve on a 1 Gbps path with a 50 ms RTT? How large must the window be to fill the path, in bytes and in 1448-byte segments?

    AnswerThroughput ≤ W/RTT = 65,535·8 / 0.05 s ≈ 10.5 Mbps — about 1% of the link. To fill it the window must be ≥ BDP = 10⁹/8 × 0.05 = 6.25 MB ≈ 4,316 segments. This is why window scaling (RFC 7323) exists and why "long fat networks" need large buffers at both ends.
  4. Stop-and-wait over a satellite. Using Part A’s satellite link (50 Mbps, 238.7 ms each way up-and-down to the satellite), what fraction of the link does a stop-and-wait protocol with 1500-byte packets use? What window, in packets, would fill it?

    AnswerRTT ≈ 2 × 238.7 = 477.5 ms; transmission 0.24 ms. Efficiency = 0.24 / (0.24 + 477.5) ≈ 0.05%, i.e. ~25 kbps of a 50 Mbps link. BDP = 50×10⁶/8 × 0.4775 s ≈ 2.98 MB ≈ 1,990 packets of 1500 B must be in flight.
  5. Slow start. With an initial window of 10 segments of 1448 bytes and no loss, how many round trips does slow start need to deliver 2 MB? On an already-open connection with a 40 ms RTT and 100 Mbps, how long does the transfer take (use netcalc.tcp_fetch_ms), compared with 2 MB at full bandwidth?

    Answer2 MB = 1,382 segments; rounds send 10, 20, 40, 80, 160, 320, 640 (cumulative 1,270) and then the last 112: 8 rounds. The model gives ≈ 372.5 ms, versus 160 ms just to transmit 2 MB at 100 Mbps: more than half the time is round trips spent waiting for the window to grow.
  6. Framing. You frame messages on a TCP connection as a 4-byte big-endian length followed by the payload. (a) Your first recv(4) returns 2 bytes. What must your code do? (b) What goes wrong if a buggy sender writes a length of 1,000,000 but sends only 10 bytes and keeps the connection open? (c) Why can’t UDP have problem (a)?

    Answer(a) Keep reading until all 4 bytes of the length have arrived, then read exactly `length` more bytes, again looping (`recv_exact`). (b) The receiver waits forever for the remaining bytes (or allocates a huge buffer): a protocol must bound message sizes and use timeouts, and must treat a malformed length as an error rather than trusting it. (c) A UDP `recv` returns one whole datagram or nothing; a datagram never arrives in pieces (though it may not arrive at all, or arrive twice, or out of order).
  7. Fan-out. A request fans out to 200 leaves; each is slow with probability 0.5%. (a) What fraction of requests hit at least one slow leaf? (b) Hedging at the leaf’s p95 adds about 5% load. Why is that so much cheaper than sending every request to two replicas from the start? (c) Why is hedging unsafe for a request like “charge the customer $10”?

    Answer(a) 1 − 0.995²⁰⁰ ≈ 63.3%. (b) Duplicating everything doubles the load (and the extra load itself creates queueing and more slowness); hedging only duplicates the 5% of requests that are already late, which is where the benefit is. (c) The original and the hedge may both execute: the customer is charged twice. Only idempotent requests, or requests with duplicate suppression (Lecture 4), may be hedged.
  8. Nagle. Explain in three sentences why write(header); write(body); read(reply) can stall, and give two fixes. Which fix would you choose for an RPC library, and why?

    AnswerNagle holds the small second write until the first is acknowledged. The receiver may delay its ACK, hoping to piggyback it on the reply. But the reply cannot be produced until the body arrives, so both sides wait for a timer. Fixes: build the whole message in one buffer and issue a single write (or `writev`), or disable Nagle with `TCP_NODELAY`. For an RPC library, do both: always write each message in one call (which also saves system calls, §6.3) and set `TCP_NODELAY`, because RPC is latency-sensitive request/response traffic, exactly the case Nagle was not designed for.
  • Project 1: the client stub and server exchange messages over TCP. This lecture explains why your protocol needs framing (§6.4), why each RPC costs at least one round trip (§5–6), why a request should be written in one piece, and why reusing a single connection beats reconnecting per call. Choosing the actual message format is P1’s design work and is not done here.
  • Problem Set 1 asks latency/bandwidth and protocol questions of exactly the §2–§5 kind. Exercises 1–5 practise the method; they are deliberately not PS1’s questions.

Further reading

  • J. F. Kurose and K. W. Ross, Computer Networking: A Top-Down Approach, chapters 1 (delay, throughput, layering) and 3 (TCP, reliable transfer, congestion control).
  • J. Dean and L. A. Barroso, “The Tail at Scale”, Communications of the ACM 56(2), 2013.
  • J. Nagle, “Congestion Control in IP/TCP Internetworks”, RFC 896, 1984; J. Chu et al., “Increasing TCP’s Initial Window”, RFC 6928, 2013.
  • A. Singla et al., “The Internet at the Speed of Light”, HotNets 2014 — latency inflation across the stack, including DNS and TCP handshakes (course reading).
  • J. Iyengar and M. Thomson (eds.), “QUIC: A UDP-Based Multiplexed and Secure Transport”, RFC 9000, 2021 — a transport that removes TCP’s head-of-line blocking and merges the transport and TLS handshakes.

Preview of Lecture 3 — Remote procedure call I

We now know what it costs to move bytes. Next we hide that cost behind the most familiar abstraction in programming: the function call. A remote procedure call turns result = add(2, 3) into a message to a server and a message back. Making that work requires stubs that marshal arguments into bytes and back — and immediately runs into the problems of Lecture 1: different machines lay out the same data differently (byte order, alignment, word size), pointers mean nothing on another machine, and a call that crosses the network is ~600× slower than a local one. We will write a marshalling library and a small working RPC system over real sockets, and measure what each piece costs.


术语表 (Glossary, English → 中文)

English中文
processing delay处理延迟
queueing delay排队延迟
transmission (serialization) delay传输(串行化)延迟
propagation delay传播延迟
one-way delay / round-trip time (RTT)单向延迟 / 往返时间
link / hop / path链路 / 跳 / 路径
packet / segment / datagram / frame分组(数据包) / 报文段 / 数据报 / 帧
store-and-forward存储转发
packet switching / circuit switching分组交换 / 电路交换
pipelining流水线化
statistical multiplexing统计复用
header / payload首部(报头) / 载荷
encapsulation封装
maximum transmission unit (MTU)最大传输单元
maximum segment size (MSS)最大报文段长度
layering / protocol stack分层 / 协议栈
application / transport / network / link layer应用层 / 传输层 / 网络层 / 链路层
best-effort delivery尽力而为交付
byte stream / message boundary字节流 / 消息边界
framing / length prefix / delimiter分帧 / 长度前缀 / 分隔符
goodput有效吞吐量(实际有用数据速率)
bandwidth-delay product (BDP)带宽时延积
stop-and-wait停等协议
sliding window滑动窗口
acknowledgment (ACK) / selective acknowledgment确认 / 选择确认
retransmission timeout (RTO)重传超时
spurious retransmission虚假重传
congestion collapse / congestion control拥塞崩溃 / 拥塞控制
flow control流量控制
three-way handshake三次握手
slow start / congestion window慢启动 / 拥塞窗口
window scaling窗口缩放
Nagle’s algorithm / delayed ACKNagle 算法 / 延迟确认
head-of-line blocking队头阻塞
system call系统调用
loopback回环
fan-out扇出
tail latency / percentile尾延迟 / 百分位数
hedged request对冲请求
partial (good-enough) result部分(足够好的)结果
latency budget延迟预算
buffer bloat缓冲区膨胀
← 返回课程目录