Lecture 1 · Introduction: what is a distributed system, and why is it hard?

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

课程源码 ZIP ↓

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

本篇目录

Maps to: CMU 15-440/640 Spring 2026, first week — the course overview and its list of major themes. Readings (optional, from the course list): H. A. Simon, The Architecture of Complexity (1962); A. Singla, B. Chandrasekaran, P. B. Godfrey, B. Maggs, The Internet at the Speed of Light (HotNets 2014). Project: P1 (Transparent Remote File Operations) is handed out this week. Sources: the public course page (overview, themes, learning outcomes, readings, project handouts, problem sets). The slides are not public, so this lecture is not a transcript of the class; it is built from those materials and the classic literature cited in each section. All six experiments and every number labelled “measured” or “simulated” come from code written for these notes and run on the author’s machine (Apple M4 Pro, macOS, Python 3.13 and 3.9). Code: code/lecture01/. Reading time: ~80 minutes for the prose; ~30 more if you run and read every demo.


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Define a distributed system in two complementary ways — by its goal (it should look like one coherent computer) and by its reality (independent machines, independent failures, messages only).
  2. Give the main reasons to distribute (sharing, scale, availability, proximity to users, inherent distribution, cost), and for each the price it brings.
  3. Explain the four realities that make distributed systems hard, each with a runnable example: (1) communication is slow and finite; (2) failure is partial and ambiguous; (3) agreement over an unreliable network can never be made certain; (4) there is no global clock and no global state.
  4. Recite the eight fallacies of distributed computing and say which later lecture repairs each one.
  5. Use three pieces of back-of-the-envelope arithmetic that recur all semester: T = latency + size / bandwidth, availability of series / replicated / majority systems, and the expected cost of restarting work after a failure.
  6. Explain why abstraction and modularity (Simon’s watchmakers) are not just good taste but a quantitative defence against failure.
  7. Place each later part of the course on this map.

0.2 Prerequisites and scope

  • Prerequisite: 15-213 (or its equivalent): processes, threads, virtual memory, sockets, and “the network can return fewer bytes than you asked for”. You do not need any networking course: Lecture 2 builds the network model you need.
  • Scope of this lecture: a map of the territory. Each reality below is the subject of several later lectures; today we only make each one concrete enough that you will want the solution.
  • Not in scope today: how RPC is implemented (Lectures 3–4), how caches stay consistent (Lecture 7), how Paxos works (Lecture 20). When this lecture mentions them, it is a forward pointer.

0.3 Section → code map

SectionIdeaDemo in code/lecture01/
§2.4, §3.2latency is not zero; light is slow; latency- vs bandwidth-bound01_latency_is_not_zero.py (real loopback timings)
§3.3partial failure: a timeout means “I don’t know”02_partial_failure.py
§3.4certain agreement over a lossy link is impossible03_two_generals.py
§3.5no global clock: replicas diverge, timestamps lie04_no_global_clock.py
§2.2–2.3, §3.6availability and fleet-failure arithmetic; bottlenecks05_why_distribute.py
§4.1modularity contains failure (Simon’s watchmakers)06_watchmakers.py
allthe simulator every later lecture reusesdsim.py (run it for its self-test)

0.4 Notation and units

  • Times are in milliseconds (ms) unless stated; 1 ms = 1000 µs (microseconds) = 10⁶ ns.
  • SI units, as in the course’s problem sets: 1 KB = 10³ bytes, 1 MB = 10⁶ bytes, 1 Gbps = 10⁹ bits per second, and a byte is still 8 bits.
  • RTT = round-trip time (there and back); one-way latency is half of a symmetric RTT.
  • p99 = the 99th percentile: 99% of the samples are at or below it.
  • c = the speed of light in vacuum, ≈ 300 km per ms. In optical fiber light travels at about c/1.47 ≈ 204 km per ms, roughly two-thirds of c.

1. What is a distributed system?

1.1 Two definitions: the goal and the reality

There are two famous definitions, and they are worth holding side by side because they pull in opposite directions.

The goal. Tanenbaum and van Steen (the course’s first reference book) define a distributed system as a collection of autonomous computing elements that appears to its users as a single coherent system. The emphasis is on “appears”. When you open a file under /afs/andrew.cmu.edu/ you do not want to know which of dozens of file servers holds it, whether it was cached on your laptop, or whether the server you talked to yesterday was replaced overnight. The system should hide all of that and behave like one big, reliable computer.

The reality. Leslie Lamport, in a 1987 email that has been quoted ever since, offered the practitioner’s definition: a distributed system is one where the failure of a computer you didn’t even know existed can render your own computer unusable. The emphasis is on failure and on not knowing. The very thing the first definition hides — that there are many machines — comes back to bite you exactly when one of them misbehaves.

The whole course lives in the gap between these two sentences. Every technique we study (RPC, caching, transactions, replication, consensus) is a way of keeping the appearance of a single coherent system while the reality is many independent machines that fail, slow down and disagree.

1.2 What precisely makes a system “distributed”?

A shared-memory multicore laptop also has many processors working together. Why is it not a distributed system in this course’s sense? Three properties separate the two, and each one is the root of one of the hard problems in §3:

PropertyOne computer (even multicore)Distributed systemConsequence (§)
Communicationshared memory: a store is visible to other cores in ~100 nsmessages only, over a network: µs to hundreds of ms, may be lostcommunication is slow and unreliable (§3.2)
Failureone failure domain: when it crashes, everything stops togetherindependent failures: one node or link fails, others keep runningpartial failure (§3.3), agreement is hard (§3.4)
Timeone clock (or tightly synchronized ones)no global clock: each node has its own, driftingno global order or global state (§3.5)

Lamport’s 1978 paper on time and clocks gives a useful quantitative version of the first row: a system is distributed when the time to send a message is not negligible compared with the time between events inside one process. By that yardstick even a large multiprocessor is “a little bit distributed” (cache coherence is a message protocol in hardware), which is why ideas from this course reappear in computer architecture. But the multiprocessor still fails as a unit and shares a clock, so it escapes the two hardest problems.

1.3 Distributed systems you used today

SystemWhat is distributedWhy it is distributed
A web searchthe index is split over thousands of servers; your query fans out to all of them and the answers are mergedno single machine can hold the index or answer fast enough (scale)
A bank transferyour bank, the other bank, a clearing house — different organizations with different computersthe parties are inherently separate; the transfer must be atomic anyway
AFS at CMUfiles live on servers; laptops cache whole filessharing among thousands of users; servers can be maintained without users noticing
A multiplayer gameclients on consoles, servers in several regionsplayers are far apart; latency must be low for everyone
An LLM chat serviceload balancers, front ends, a request database, GPU model servers, streaming tokens backGPUs are scarce and expensive; one request touches several tiers
Your phone’s photo backupphone, cloud storage, edge cachesthe phone is small and often disconnected; storage is cheap in the cloud

Notice two things. First, each system was distributed on purpose, for a reason in the last column — distribution is a response to a need, never a goal in itself. Second, each must still behave correctly when one component is slow or broken: a search that waits for the slowest of a thousand servers is slow; a bank that debits one side but not the other loses money; a phone that uploads a photo twice wastes space, and one that thinks it uploaded when it did not loses a memory.

A small irony to remember. The slides for this very course are distributed through AFS — the Andrew File System built at CMU in the 1980s by a team that included one of the course’s instructors, and still in use today. Several of the readings (Morris 1986, Howard 1988, Satyanarayanan 1990) are about it, and Lecture 5 dissects its design.


2. Why distribute at all?

If distribution makes everything harder, why do it? Because some goals cannot be met by one machine, however large. Each goal below comes with its price, and the price is the reason for a later part of the course.

2.1 Sharing

The oldest reason: people want to share data (files, a calendar, a database) and expensive resources (a printer in the 1980s, a GPU cluster today). A shared resource must live somewhere, and its users are elsewhere, so access is remote.

Price: every access is now a message, so it is slow (§3.2); and if users keep local copies to go faster, the copies can disagree (Part II, caching and consistency).

2.2 Scale: more work than one machine can do

One server can handle some number of requests per second; a popular service needs a hundred times more. The natural answer is scale out: run many servers and spread the requests among them (Lecture 11). But almost every service has some component that is shared by all requests — a database, a lock service, a metadata server — and that component does not get faster when you add web servers.

Demo 05_why_distribute.py, Part C, uses the bottleneck law to make this exact. Each request needs 1 ms of web-server CPU (one server handles 1,000 requests/s) and D ms of time on one shared database. With N web servers the system can do at most

Xmax⁡=min⁡(N1 ms, 1D)X_{\max} = \min\left(\frac{N}{1\ \text{ms}},\ \frac{1}{D}\right)

requests per second. The demo prints:

ND = 0D = 0.02 msD = 0.1 ms
11,000 (web)1,000 (web)1,000 (web)
1010,000 (web)10,000 (web)10,000 (both)
2020,000 (web)20,000 (web)10,000 (DB)
5050,000 (web)50,000 (both)10,000 (DB)
100100,000 (web)50,000 (DB)10,000 (DB)

With a database that costs only 0.02 ms per request, the 51st web server adds nothing but cost; with 0.1 ms, the 11th. Scaling is the art of moving the bottleneck, and Project 3 is built around exactly this: find which tier is the bottleneck now, scale it, and watch the bottleneck move elsewhere.

Price: coordination among the servers, and a performance behaviour that is surprisingly hard to predict (Part III).

2.3 Availability: surviving the failure of parts

A single machine that is up 99% of the time is down about 3.65 days a year — unacceptable for a bank or a hospital. With several machines we can keep replicas (copies) so that the service survives the loss of some of them. Whether this helps or hurts depends entirely on what the system needs to keep working. Demo 05, Part A, computes it for machines that are each up 99% of the time (failures independent):

n machinesneeds all n upneeds any one upneeds a majority up
12.0 nines (4 days down/yr)2.0 nines2.0 nines
31.5 nines (11 days)6.0 nines (31.6 s)3.5 nines (2.6 hours)
51.3 nines (18 days)10.0 nines (3 ms)5.0 nines (5.2 minutes)
1000~0 nines (up 0.0043% of the time)astronomically availableastronomically available

(“k nines” means unavailability 10⁻ᵏ: 99.9% available = 3 nines.)

Three lessons, each a later lecture:

  • Naive distribution makes availability worse. If the service needs every machine (data split across them with no copies), 1000 machines that are each 99% up give a system that is up 0.99¹⁰⁰⁰ ≈ 0.0043% of the time. This is Lamport’s definition as arithmetic.
  • Redundancy turns unreliable parts into a reliable whole. Three copies, any one of which suffices, give six nines.
  • Consistency costs availability. “Any one copy” works only if the copies never need to agree (read-only data). If they must agree on updates, the standard trick is to require a majority (a quorum): two majorities always share at least one member, so no two conflicting decisions can both be made. The price is visible in the table: a majority of 5 gives 5 nines, an “any one of 5” system 10. Lectures 19–21 build replication on exactly this majority-intersection idea.

The independence assumption is optimistic: real failures are correlated (shared power, a bad software release, one operator’s mistake). Lecture 13 looks at what real failure data says.

2.4 Geography: being close to users

The speed of light is a hard floor on latency. Demo 01_latency_is_not_zero.py, Part B, computes the round-trip time from Pittsburgh at the speed of light along the great-circle path:

todistanceRTT at c (vacuum)RTT in fiber (~2/3 c)
New York507 km3.4 ms5.0 ms
San Francisco3,637 km24.3 ms35.6 ms
London5,979 km39.9 ms58.6 ms
Beijing10,928 km72.9 ms107.0 ms
Sydney15,482 km103.3 ms151.6 ms

Real paths are longer than great circles, and protocols need several round trips. Singla et al. (2014, a course reading) measured that fetching web pages takes, in the median, 34× the speed-of-light round-trip time, and 169× at the 90th percentile; even the router-level path is 2.3× inflated in the median, and fiber alone costs 1.5×. So a service that must answer a user in Sydney within 50 ms cannot run only in Pittsburgh, no matter how fast its servers are. It must place servers — or at least caches — near users: content delivery networks, regional data centers, and edge computing (Lecture 10; Satyanarayanan 2017 is a course reading).

Price: data now lives in several places at once, and keeping those places consistent across a 100-ms ocean is the replication problem again.

2.5 Inherent distribution and cost

Some systems are distributed because the world is: a bank transfer involves two banks; a phone and a cloud server are physically separate; sensors are where the phenomena are. And some are distributed because it is cheaper: many commodity machines plus clever software beat one enormous, ultra-reliable machine on price, which is the founding bet of every cloud.

Summary of §2. We distribute for sharing, scale, availability, proximity, inherent distribution and cost. Every one of these benefits is bought with the same currency: messages between independent machines. The next section is about why that currency is so expensive.


3. Why is it hard? Four realities

3.1 The eight fallacies

In the 1990s engineers at Sun Microsystems (usually credited: Peter Deutsch, with James Gosling adding the last) collected the assumptions that newcomers to distributed programming make — and that turn out false in production. They are a good checklist for this course:

#FallacyRealityWhere this course repairs it
1The network is reliablemessages are lost, duplicated, reorderedRPC semantics (4), transactions (16–18), consensus (20–21)
2Latency is zeroµs on a LAN, 100+ ms across oceans, never below ccommunication (2), caching (6–10)
3Bandwidth is infinitelinks saturate; queues build upcommunication (2), buffer bloat (9), mobile (10)
4The network is secureanyone on the path can read or forgesecurity (26)
5Topology doesn’t changemachines join, leave, movenaming (5), DHTs (25), mobile (10)
6There is one administratormany organizations, many policiesblockchains (23), security (26)
7Transport cost is zeromarshalling, copying, system calls cost CPURPC (3)
8The network is homogeneousdifferent byte orders, word sizes, languagesmarshalling (3)

The rest of this section turns the deepest of these into four realities you can run.

3.2 Reality 1 — Communication is slow, and the floor is physics

Intuition. A function call inside your program is a jump to another address: a few nanoseconds in C, tens in Python. A remote call has to package the arguments into bytes, ask the operating system to send them, cross the network, wake up a process on the other side, unpack, compute, and do it all again in reverse. Each of those steps is far more expensive than the call it replaces.

Measurement. Demo 01_latency_is_not_zero.py, Part A, performs the same trivial operation — add(x, 1) — five ways on one machine and times each (Python 3.13, Apple M4 Pro; medians over thousands of trials; five runs gave the ranges shown):

operationmedianvs. local call
local function call25 ns1×
hand to another thread and back (two queues)7.3–8.4 µs~290–330×
UDP over loopback to a server thread13–16 µs~520–630×
TCP over loopback to a server thread13–15 µs~530–610×
TCP over loopback to a server process14.5–15.7 µs~575–630×

Nothing here left the computer — 127.0.0.1 is the loopback interface, handled entirely inside the kernel — and yet a “remote” call is already ~600× a local one. Most of that cost is software: system calls, copying through the kernel’s network stack, and above all waking up a sleeping thread on the other side (the thread-to-thread handoff alone is ~300×). On a real network you add the wire, the switches and the distance.

(Two side lessons the demo’s comments explain: an early version measured UDP slower than TCP, because Python implements settimeout() with an extra poll() system call per receive, and because an unconnected sendto() processes the destination address on every call. Measuring communication is itself a skill — Lecture 12.)

The floor. Part B (the table in §2.4) shows that across the planet the speed of light alone costs tens to hundreds of milliseconds per round trip. The demo also prints how many local function calls fit into one such round trip: from 1.3 × 10⁵ (New York) to 4.1 × 10⁶ (Sydney). That ratio is the single most important number in distributed systems design: every message you avoid is worth a hundred thousand to a million local operations. That is why caching (Part II) exists, why RPC interfaces should be “chunky” (few calls carrying a lot) rather than “chatty”, and why we will count messages in almost every protocol we study.

Latency is a distribution, not a number. Part A also prints the 99th percentile: in five runs it was 1.4–5× the median for the message-passing rows (UDP’s p99 was consistently around 72 µs against a 13–16 µs median). A request that fans out to 100 servers waits for the slowest of them, so its typical latency is close to a single server’s p99. Tail latency is a recurring theme (Lectures 2 and 12).

Latency vs. bandwidth. The time to deliver a message of S bytes over a link with one-way latency L and bandwidth B bits/s is, to first order,

T=L+8SB.T = L + \frac{8S}{B}.

The first term is paid once per message, the second per byte. Part C evaluates it for five links and five sizes; an excerpt:

link (one-way latency, bandwidth)100 B1 MB1 GB
datacenter rack (0.05 ms, 10 Gbps)50.1 µs L850 µs B0.8 s B
home Wi-Fi → cloud (15 ms, 100 Mbps)15.0 ms L95 ms B80 s B
cellular → cloud (40 ms, 20 Mbps)40.0 ms L440 ms B400 s B
trans-Pacific fiber (80 ms, 1 Gbps)80.0 ms L88 ms L8.1 s B

(L = the latency term dominates; B = the bandwidth term dominates.) A 100-byte RPC is latency-bound on every link; a 1 TB transfer is bandwidth-bound on every link. This matters because the two have different cures: latency-bound workloads need fewer round trips (batching, caching, pipelining, moving closer); bandwidth-bound workloads need fatter pipes or less data (compression, deduplication). The size at which the two terms are equal is L × B / 8 — for the trans-Pacific link, 10 MB — which is closely related to the bandwidth-delay product you will meet in Lecture 2.

And a classic reminder about bandwidth: a courier carrying a full 20 TB disk overnight delivers an effective 1.85 Gbps with 24 hours of latency, beating 4 of the 5 network links in the table at moving 20 TB. (Cloud providers really do sell “data transfer appliances” shipped by truck.)

3.3 Reality 2 — Failure is partial, and a timeout means “I don’t know”

Intuition. On one computer, when something goes badly wrong, the whole program (or machine) crashes, and you know it. In a distributed system one part fails while the others keep running, and the survivors have no direct way to see what happened. All a client can observe is the absence of a reply. Silence has many causes.

Experiment. Demo 02_partial_failure.py scripts six worlds on the simulator. A client asks a bank server to withdraw $100 and waits 10 ms; a normal round trip takes 5 ms. (The server executes the withdrawal on receipt and sends the reply 1 ms later — that gap stands for real work such as writing a log.)

worlddid the money move?what the client observed
everything worksyesreply at 5.0 ms
request lost in the networknoTIMEOUT
server down before the request arrivesnoTIMEOUT
server crashes after withdrawing, before replyingyesTIMEOUT
reply lost in the networkyesTIMEOUT
server is slow (overloaded)yesTIMEOUT (reply shows up at 19 ms)

Five different worlds produce exactly the same observation. In three of them the money moved; in two it did not. No amount of cleverness inside the client can distinguish them, because the information simply did not reach it. And the last row shows something subtle: “slow” and “dead” are indistinguishable until it is too late. A timeout is not a failure detector; it is a guess about how long is too long. Choose it short and you declare live servers dead; choose it long and you wait forever for dead ones.

So the client needs a policy. Part B of the demo runs 2,000 withdrawals per policy on a network that loses every message with probability 0.2:

policyexecuted 0×exactly 1×2× or moreclient got a reply
A: send once, never retry4391,56101,242
B: retry up to 8×, server executes every copy01,588412 ($53,000 double-debited)2,000
C: retry + server remembers request ids02,00002,000
  • Policy A never does anything twice, but loses 22% of the withdrawals and leaves the client unsure in 38% of cases. This is at-most-once behaviour.
  • Policy B always gets an answer, but every time a reply was lost, the retry executes the withdrawal again. This is at-least-once behaviour — fine for “read my balance” (an idempotent operation, one whose repetition is harmless), disastrous for “withdraw $100”.
  • Policy C combines retries with duplicate detection: every request carries a unique id, and the server keeps a table of ids it has executed and the replies it sent. A repeat gets the remembered reply instead of a second execution.

But Part C of the demo crashes the server once, mid-way, and restarts it 3 ms later. If the table of executed ids lived in memory, the restarted server has forgotten it, and 410 of 2,000 withdrawals are executed twice again; with the table kept on disk (stable storage), 0. “Exactly once” therefore needs three things together: retries, unique request ids, and a memory of them that survives crashes — and, in a real system, an atomic way to “do it and record that I did it” (Lectures 16–17). Lecture 4 turns these policies into the named RPC semantics; Project 1 lives right at this boundary.

3.4 Reality 3 — Certain agreement over an unreliable network is impossible

The two generals. Two generals on hills on either side of a valley will win only if they attack together. Their only channel is a messenger through the valley, who may be captured. General A sends “attack at dawn”. A cannot attack until A knows B got it, so B sends an acknowledgment. But B cannot attack until B knows the acknowledgment arrived — otherwise A, not knowing, will not attack and B will attack alone. So A acknowledges the acknowledgment. And so on. How many messengers are enough?

This puzzle (Akkoyunlu, Ekanadham and Huber 1975; named by Jim Gray in 1978) has a crisp answer: no finite number of messages makes agreement certain.

The proof idea, in one paragraph. Number the messages 1, 2, 3, …; odd ones go A→B, even ones B→A, and each is sent only if the previous one arrived. A run of the protocol is described by which message is lost first. Now line the runs up: “message 1 lost”, “message 2 lost”, …, “nothing lost”. Neighbouring runs differ in a single message, so the general who would have received it cannot tell them apart and must decide the same way in both. If A has nothing to say, B hears nothing — exactly as when message 1 is lost — so B must retreat in run 1. A cannot tell run 1 from run 2 (both: A heard nothing back), so A retreats in run 2 as well; agreement then forces B to retreat in run 2; B cannot tell run 2 from run 3, … The “retreat” decision propagates along the chain all the way to the run in which no message was lost. So any protocol that always agrees never attacks. The flaw is always the last message: whoever sends it cannot know it arrived, and acknowledging it merely creates a new last message.

Checking it exhaustively. Demo 03_two_generals.py, Part A, does not trust the argument; it tries every deterministic decision rule — every assignment of attack/retreat to “how many messages I received” — for handshakes of length 1 to 8: 2,040 rule pairs in all. The number that always agree and attack when nothing is lost is 0. (The only rule pair that always agrees is “never attack”.)

If certainty is impossible, how small can the risk be? Part B makes each message lost independently with probability p = 0.1 and computes exact probabilities. For the natural rule “attack iff I received every message meant for me”:

messages kP(both attack)P(disagree)ratio
10.90000.10000.1111
40.65610.07290.1111
80.43050.04780.1111

More messages reduce the probability of disagreeing — but only by making the generals attack less often. The ratio is stuck at p/(1−p) = 0.1111, and the demo confirms that no rule pair, for any k ≤ 8, does better. The reason is a quantitative version of the chain argument: let run j₀ be the first run in which both attack. Run j₀−1 differs from it in one message, so one general decides “attack” there too, and the other must retreat (otherwise j₀ would not be first) — a disagreement. Hence

P(disagree)P(both attack) ≥ P(run j0−1)P(run≥j0)=(1−p)j0−2 p(1−p)j0−1=p1−p.\frac{P(\text{disagree})}{P(\text{both attack})} \ \ge\ \frac{P(\text{run } j_0-1)}{P(\text{run} \ge j_0)} = \frac{(1-p)^{j_0-2}\,p}{(1-p)^{j_0-1}} = \frac{p}{1-p}.

Part C runs the k = 4 protocol 20,000 times as real message-passing nodes on the simulator and gets P(disagree) = 0.0736 against the exact 0.0729.

Why this matters. The two generals problem is the simplest of the impossibility results of distributed computing, and its lesson shapes the whole field: you cannot make two parties certain over an unreliable channel, so systems are designed to (a) make the risk small and quantified, and (b) let the unsure party find out later — by keeping a log, asking a coordinator, or retrying an idempotent step. That is exactly how two-phase commit (Lecture 18) works, and why TCP’s connection close ends with a TIME_WAIT state in which one side lingers, unsure whether its last acknowledgment arrived. (Lynch’s Distributed Algorithms, a course reference, proves the general deterministic impossibility and analyses randomized versions in its chapter on consensus with link failures.)

3.5 Reality 4 — No global clock, no global order, no global state

Intuition. On one machine, “which happened first?” has an answer: the instruction executed earlier, or the earlier timestamp on the one clock. In a distributed system, each node sees only its own events and the messages that reach it, each after its own random delay. There is no shared memory to inspect and no shared clock to read.

Experiment 1: replicas that receive the same updates can disagree. Demo 04_no_global_clock.py keeps two replicas of an account holding 100.Twoclientsconcurrentlysendeachreplicaoneupdate:"deposit100. Two clients concurrently send each replica one update: "deposit 50” and “add 10% interest”. Each replica applies updates in the order they arrive.

variantruns (of 1000) where the replicas disagreefinal balances
deposit + interest, sent to both replicas499160.00or160.00 or 165.00
deposit + deposit (operations commute)0$160.00
deposit + interest, through a sequencer0160.00or160.00 or 165.00 (but equal within each run)

Deposit-then-interest gives 165;interest−then−depositgives165; interest-then-deposit gives 160; each replica sees its own order, so half the time they diverge. Two cures appear, each the seed of a later lecture:

  • Make operations commute. If the order does not matter, the replicas cannot diverge (two deposits). Designing state and operations so that concurrent updates merge cleanly is the idea behind conflict-free replicated data types and Coda’s automatic directory merges (Lecture 22).
  • Impose one order. Route every update through a single sequencer that numbers them; replicas apply strictly in number order (holding back any that arrive early). Divergence disappears — but the sequencer did not find the “true” order (both outcomes still occur across runs); it only made everyone use the same order. The price: an extra hop (mean completion 14.4 ms instead of 8.3 ms) and a single node everybody depends on. Making that node fault-tolerant is exactly what consensus protocols do (Lectures 20–21).

Experiment 2: why not just timestamp everything with the local clock? Because clocks disagree. Part B gives each machine a clock offset by a random amount and sends one message across a network with 1–10 ms of delay. If the receiver’s clock is behind the sender’s by more than the delay, the message appears to be received before it was sent:

clocksmessages that look received before sent
unsynchronized, within ±50 ms44.19%
NTP over the Internet, within ±5 ms13.79%
good LAN sync, within ±1 ms0.39%
Lamport logical clocks0.00%

Better synchronization helps, but violations remain as long as the clock error can exceed the network delay — and clocks also drift (a quartz clock off by 50 parts per million gains or loses 4.3 s per day), so synchronization never ends. Lamport clocks sidestep physical time entirely: every message carries a counter, and the receiver sets its own counter past it. The result orders events consistently with could-have-caused (“happened-before”), which is what correctness usually needs (Supplement S1).

No global state either. The same problem in another form: you cannot “take a photo” of all nodes at the same instant, because there is no common instant. A naive snapshot can count money that is in flight twice, or not at all. Consistent snapshots are possible, but only with a protocol (Lecture 15).

3.6 And then there is scale, heterogeneity and security

  • Scale makes failure the steady state. Demo 05, Part B: if each machine fails on average once every 3 years, a fleet of 1,000 sees a failure about every 26 hours; a fleet of 100,000 sees one every 15.8 minutes. At that scale “handle failures” is not an error path; it is the main path (Lecture 13).
  • Heterogeneity. Machines differ in byte order, word size, alignment rules, programming language and operating system. Sending “the bytes of a struct” from a 32-bit little-endian device to a 64-bit server silently produces garbage; RPC must marshal data into an agreed format (Lecture 3; Problem Set 1 opens with a case like this).
  • Security. Messages cross networks owned by others; anyone on the path may read, modify, replay or forge them, and the parties belong to different administrations (Lecture 26).

4. How do we cope? The course’s toolbox

The course page lists its major themes: resource scarcity, scheduling and concurrency; communication latency and bandwidth; naming; abstraction and modularity; imperfect communication and other types of failure; protection from accidental and malicious harm; optimism; consensus; and instrumentation, monitoring and debugging. Read them as the toolbox for the four realities.

4.1 Abstraction and modularity — and their limits

Transparency is the classic statement of the goal in §1.1: hide from the user (and the programmer) where a resource is (location transparency), that it moved (migration), that it is copied (replication), that others use it concurrently (concurrency), and ideally that parts of the system failed (failure transparency). RPC (Lectures 3–4) is the purest example: a remote service looks like a function call. Project 1 does this literally: unmodified programs (440cat, 440ls) read remote files because the C library calls they make are intercepted and turned into RPCs.

But §3 shows why transparency can never be complete: a remote call is ~600× slower even on one machine, and it can fail in ways a local call cannot (“did it happen?”). An abstraction that hides those facts invites programmers to write code that is slow and wrong. A well-known paper (Waldo, Wyant, Wollrath and Kendall, A Note on Distributed Computing, 1994) argues exactly this: latency, memory access, partial failure and concurrency make local and remote objects fundamentally different, and an interface should expose the difference. Good distributed abstractions therefore hide mechanism but expose consequences — timeouts, error codes, consistency guarantees.

Why modularity, quantitatively: Simon’s watchmakers. Herbert Simon’s 1962 essay (a course reading) tells of two watchmakers, Hora and Tempus, whose watches have about 1,000 parts. Customers phone them constantly. Tempus builds each watch as one assembly; when he puts it down to answer the phone, it falls apart and he starts over. Hora builds stable subassemblies of 10 parts, combines ten of them into larger subassemblies, and ten of those into a watch — 111 assemblies of 10 parts each. An interruption costs Hora only the subassembly in his hands. Simon estimates that with a 1-in-100 chance of interruption per part added, Tempus takes “about four thousand times” as long.

Demo 06_watchmakers.py computes this exactly. If each part-addition is interrupted with probability p and an interruption destroys the assembly in progress, the expected number of additions to finish an assembly of m parts (m successes in a row) is

E(m)=(1−p)−m−1p.E(m) = \frac{(1-p)^{-m} - 1}{p}.

At p = 0.01: Tempus needs E(1000) ≈ 2,316,257 additions per watch; Hora needs 111 × E(10) ≈ 1,174; the ratio is 1,974. (Simon’s back-of-the-envelope 4,000 counts only the wasted work per interruption, 100 parts vs 5; counting whole attempts — Hora’s successful ones are 10 parts long — gives 1,974. Same moral: three orders of magnitude.) The ratio is only 1.5× at p = 0.001, but 10⁴³ at p = 0.1: monolithic designs collapse exponentially as the interruption rate grows. A simulation of 400 watches each agrees with the formula (Tempus within 1.8 standard errors — his time has a standard deviation as large as its mean).

Replace “watchmaker” with “a long computation” and “phone call” with “machine failure”, and you have the checkpointing problem (Lecture 15): a 1,000-unit job on machines that fail with probability 0.01 per unit, restarting from scratch after any failure, takes 2.3 million units. Part B of the demo inserts a checkpoint every m units, each costing 1 unit:

checkpoint every m1513 (best)50100never
expected time2,0101,2311,1511,3261,7422,316,258

The best interval, found by exhaustive search, is 13; Young’s classic rule of thumb √(2c/p) gives 14.1. Stable intermediate states turn an exponential cost into a linear one. Checkpoints, transactions, logs and per-component restarts — all of Part IV — are ways of building Hora’s subassemblies.

4.2 Caching and replication

Since every message costs 10⁵–10⁶ local operations, the most powerful optimization is not to send it: keep a copy of the data close to where it is used. Caching (Part II) and replication (Part V) are the same idea serving different goals — caching for performance, replication for availability — and they share the same price: copies can disagree. Most of the course’s intellectual content is about managing that disagreement: one-copy semantics (make the copies look like one), and the protocols that approximate it at acceptable cost (check-on-use, callbacks, leases, quorums, consensus).

4.3 Optimism versus pessimism

A pessimistic design prevents conflicts before they happen (locks, a sequencer, waiting for a majority); it is safe but pays in latency and availability. An optimistic design lets operations proceed, assuming conflicts are rare, and detects and repairs them afterwards (Coda’s disconnected operation, Lecture 22). Demo 04 showed both: the sequencer is pessimistic; commuting operations make optimism free. Choosing between them by asking “how often do conflicts really occur, and how bad is a repair?” is a recurring design move.

4.4 Logs, transactions and consensus

Two generals cannot become certain, but systems still need to commit transfers and elect leaders. The way out is to change the problem: write intentions to stable storage before acting (so a crashed node can find out later what it promised), group actions into atomic transactions (all or nothing), and decide with majorities (which always overlap) rather than unanimity where possible. Lectures 16–23 develop this from write-ahead logs to two-phase commit, Paxos and blockchains.

4.5 Measure, don’t assume

Distributed systems are nondeterministic: the same code gives different timings and even different interleavings from run to run (Project 3 says so explicitly). Averages hide tails, and intuitions about bottlenecks are often wrong. The habits of this course: measure distributions (median and p99), find the bottleneck before optimizing, and reproduce rare interleavings deliberately — which is why most of our demos run on a deterministic simulator.

4.6 The end-to-end argument (a preview)

Where should reliability live — in every network hop, or at the endpoints? Saltzer, Reed and Clark (1984, a course reading) argue that a function such as “the file arrived intact” can only be guaranteed completely by the endpoints that care about it; hop-by-hop checks can improve performance but cannot replace the end-to-end check. Demo 02 is a small instance: even a “reliable” network could not have saved the withdrawal from a server that crashed before replying; only the client’s retry-with-id plus the server’s durable memory could. Lecture 4 makes the argument in full.


5. A tour of the course

PartThe question it answersLecturesProject
I · FoundationsHow do programs on different machines talk, and what can go wrong when they do?1–5P1: RPC for remote file operations, in C, via library interposition
II · CachingHow do we avoid talking — and what does it cost to keep copies consistent?6–10P2: a whole-file caching proxy with session semantics and LRU, in Java RMI
III · ScaleHow do we serve more load at lower cost, and how do we know where the bottleneck is?11–12P3: scale out a simulated multi-tier cloud web store
IV · FailuresWhat fails, how do we detect it, and how do we make work survive it?13–18P4: two-phase commit with logging and crash recovery, in Java
V · Replication & consensusHow do many copies stay one, and how do many nodes agree?19–23—
VI · At scaleWhat do the big systems (MapReduce, GFS, Ceph, DHTs) do, and how do we defend them?24–26—

The problem sets track the same order: PS1 (RPC, marshalling, latency and bandwidth, exactly-once), PS2 (caching and consistency), PS3 (scaling, failures, transactions), PS4 (2PC, Paxos, paradigms, DHTs, storage systems).


6. Using these notes alongside the course

  • Projects are individual and must be your own work. The course forbids copying solutions from any source and strongly discourages generative AI for coursework (see its AI policy page). These notes therefore contain no project code and no problem-set answers. The demos teach each mechanism with toy worlds (bank accounts, generals, watchmakers), in Python rather than the projects’ C and Java.
  • Run the demos, then change them. Each demo is short and seeded. The most useful exercise is to change one knob — the loss rate, the timeout, the number of replicas — predict the result, and run it.
  • The simulator is the course’s laboratory. dsim.py (run python3 dsim.py for its self-test) will host RPC retries, cache callbacks, two-phase commit, Paxos and Chord in later lectures. Read its header once; every later protocol is just a few Node subclasses with on_message and on_timer handlers.

Summary

  • A distributed system is a set of autonomous machines that communicate only by messages, fail independently and share no clock, built to appear as one coherent system.
  • We distribute for sharing, scale, availability, proximity to users, inherent distribution and cost — and pay for every one of these in messages.
  • Reality 1: communication is slow. On one machine a loopback RPC already costs ~600× a function call; across the planet the speed of light alone costs 10⁵–10⁶ local calls per round trip. T = L + 8S/B: small messages are latency-bound, big ones bandwidth-bound, and the cures differ.
  • Reality 2: failure is partial. Five of six failure worlds look identical to a client (a timeout), yet in three the action happened. Retrying gives at-least-once, not retrying gives at-most-once; exactly-once needs retries + request ids + memory that survives crashes.
  • Reality 3: certain agreement is impossible over a lossy channel (two generals). The best any deterministic rule achieves is P(disagree)/P(both act) ≥ p/(1−p); systems instead make risk small and let the unsure side find out later.
  • Reality 4: no global clock, order or state. Replicas that see the same updates in different orders diverge; physical timestamps can claim effects precede causes; commuting operations, sequencers and logical clocks are the remedies.
  • Scale makes failure the steady state, and requiring all parts makes a system worse than any part; redundancy and majorities make it far better.
  • Modularity contains failure (Simon): stable intermediate states turn an exponential restart cost into a linear one — the principle behind checkpoints, transactions and logs.

Common pitfalls

  • “A timeout means the server is down.” It means you did not get a reply in time. The request may have been executed, may still be executing, or may never have arrived.
  • “Just retry.” Retrying a non-idempotent operation without duplicate detection performs it twice (412 of 2,000 double withdrawals in demo 02).
  • “Duplicate detection solves it.” Only if the table of executed requests survives a server crash (410 double withdrawals with it in RAM, 0 on disk).
  • “Add another acknowledgment.” The last message is always unacknowledged; more rounds cannot create certainty (demo 03).
  • “Sort events by timestamp.” Clocks differ by more than message delays; timestamp order can contradict cause and effect (44% of messages with ±50 ms clocks).
  • “More servers, more throughput.” Only until a shared component saturates; after that, more servers add only cost (demo 05, Part C).
  • “More machines, more reliability.” Only with redundancy. A system that needs all of 1,000 machines is almost never up.
  • Quoting averages. Latency is a distribution; the tail (p99) dominates any request that fans out.

Exercises

  1. Latency or bandwidth? A phone uploads a 4 MB photo. Over cellular the one-way latency is 40 ms and the bandwidth 20 Mbps; over Wi-Fi, 15 ms and 100 Mbps. (a) Using T = L + 8S/B, how long does each take? (b) For each link, at what message size are the two terms equal? (c) Which kind of optimization helps a 200-byte “like” request most, and which helps the photo most?

    Answer(a) Cellular: 40 ms + 4×10⁶×8 / 20×10⁶ s = 40 ms + 1.6 s = 1.64 s. Wi-Fi: 15 ms + 0.32 s = 0.335 s. (b) The terms are equal when 8S/B = L, i.e. S = L·B/8: cellular 0.04 × 20×10⁶ / 8 = 100 KB; Wi-Fi 0.015 × 100×10⁶ / 8 = 187.5 KB. (c) The 200-byte request is far below both crossover sizes, so it is latency-bound: fewer round trips (batching likes, reusing connections, a nearby edge server) help; more bandwidth does nothing. The 4 MB photo is bandwidth-bound: compression or a faster link helps; shaving latency barely matters.
  2. A floor for Tokyo. The great-circle distance from Pittsburgh to Tokyo is about 10,630 km. (a) What is the minimum possible round-trip time in vacuum and in fiber? (b) An interactive application needs a response within 50 ms of a user’s action. Can a server in Pittsburgh serve users in Tokyo? What would you do instead?

    Answer(a) In vacuum 2 × 10,630 / 299.8 ≈ 70.9 ms; in fiber (~204 km/ms) ≈ 104 ms. (b) No: even a perfect fiber path straight through the Earth's surface needs ~104 ms for one round trip, before any queueing, processing or the extra round trips of real protocols (Singla et al. measured ~34× the c-latency for web fetches in the median). The service must run, or at least cache data and handle the interactive part, close to the users — a regional data center or an edge site (Lecture 10).
  3. Partial failure with a naive retry. Take the six worlds of §3.3, but let the client retry once (same request) after its 10 ms timeout, and let the server execute every request it receives (no duplicate detection). Assume the retry itself is delivered normally and the server, if it crashed, has been restarted by then. In which worlds is the money withdrawn twice?

    AnswerThe withdrawal happens twice wherever the first attempt was already executed: "server crashes after withdrawing" (the restarted server executes the retry), "reply lost" (the server executed and then executes the retry), and "server slow" (the first request is still executed late *and* the retry is executed). It happens exactly once in "request lost" and "server down before the request arrives" (only the retry executes) — and in "everything works" there is no retry at all. Three of six worlds double-debit, which is why retries need request ids.
  4. Why not one more acknowledgment? For the two generals with k = 2 messages (order, ack), list the three runs (message 1 lost, message 2 lost, nothing lost), say what each general knows in each, and show that no decision rule satisfies all three requirements. Then explain in one sentence why adding message 3 does not help.

    AnswerRun 1 (order lost): A has received 0, B has received 0. Run 2 (ack lost): A 0, B 1. Run 3 (nothing lost): A 1, B 1. Validity forces B to retreat with 0 messages (it cannot tell "order lost" from "A chose to retreat"), so in run 1 both retreat. In run 2, A has the same view as in run 1 (0 messages) and so retreats; agreement forces B, with 1 message, to retreat. In run 3, B has the same view as in run 2 (1 message) and retreats; agreement forces A to retreat — so nobody attacks even though nothing was lost. Adding message 3 only adds a run 4 that looks to its *sender* exactly like run 3, so the same induction continues one step further.
  5. Three replicas. Each of three servers is up 99.9% of the time, independently. Compute the availability of a service that needs (a) all three, (b) any one, (c) a majority. (d) Now suppose that with probability 10⁻⁴ (at any given moment) a shared power failure takes down all three at once. Which of your answers changes most, and what does that tell you?

    Answer(a) 0.999³ ≈ 0.997003 (about 2.5 nines). (b) 1 − 0.001³ = 0.999999999 (9 nines). (c) P(at least 2 up) = 0.999³ + 3 × 0.999² × 0.001 ≈ 0.999997 (unavailability ≈ 3.0 × 10⁻⁶, about 5.5 nines). (d) The correlated failure adds about 10⁻⁴ of unavailability to every configuration. For (a) that is negligible next to 3 × 10⁻³; for (c) it raises unavailability from 3 × 10⁻⁶ to ~10⁻⁴ (from 5.5 to 4 nines); for (b) it dominates completely (from 9 nines to 4). The more redundancy you have, the more your availability is decided by correlated failures — which is why real systems spread replicas across power domains, racks and data centers.
  6. A fleet. A cluster has 20,000 machines, each with a mean time between failures of 5 years. (a) How many machine failures per day should the operators expect? (b) What is the mean time between failures anywhere in the cluster? (c) A job needs all 20,000 machines for 2 hours and must restart from scratch if any fails. Roughly how likely is a single attempt to finish?

    Answer(a) 20,000 / (5 × 365.25) ≈ 11 failures per day. (b) 5 years / 20,000 ≈ 2.2 hours (≈ 131 minutes). (c) With exponential failures, P(no failure in 2 h) = exp(−2 / 2.19) ≈ 0.40. Six in ten attempts fail, and the expected cost of restarting from scratch grows exponentially with the job's length — this job needs checkpoints (Lecture 15).
  7. Bigger subassemblies. In Simon’s model with p = 0.01, Hora switches to subassemblies of 100 parts: ten of them, then one final assembly of those 10. Using E(m) = ((1−p)^(−m) − 1)/p, how long does a watch now take, and how does it compare with his original design and with Tempus?

    AnswerE(100) = (0.99⁻¹⁰⁰ − 1)/0.01 ≈ 173.2 and E(10) ≈ 10.57, so a watch takes 10 × 173.2 + 10.57 ≈ 1,743 additions: about 1.5× his original 1,174, but still ~1,330× faster than Tempus's 2,316,257. Coarser modules lose more work per interruption; the sweet spot depends on the interruption rate — the same trade-off as choosing a checkpoint interval (where the optimum was 13 units).
  8. When can timestamps be trusted? Clocks are synchronized so that every clock is within ε of true time, and every message takes at least d_min to arrive. Show that if 2ε ≤ d_min, no message can ever appear to be received before it was sent. Use this to explain why demo 04’s “±1 ms” row still had violations.

    AnswerA message sent at true time t and delivered after delay d ≥ d_min is stamped t + o_s on sending (o_s = sender's clock error) and t + d + o_r on receipt. It looks received-before-sent iff t + d + o_r < t + o_s, i.e. o_s − o_r > d. Since |o_s|, |o_r| ≤ ε, the left side is at most 2ε ≤ d_min ≤ d — impossible. In demo 04, ε = 1 ms gives 2ε = 2 ms, but the minimum delay is only 1 ms, so a message with delay below 2 ms between a fast-clocked sender and a slow-clocked receiver can be stamped backwards. (Exactly: with offsets uniform in ±1 ms and delay uniform in 1–10 ms the probability is 1/216 ≈ 0.46%; the demo's 10,000 runs gave 0.39%.)
  • Project 1 (handed out this week) asks you to make remote files look local by interposing on C library calls and forwarding them as RPCs that you design and marshal yourself. Today’s lecture gave its two central difficulties: every call now costs a round trip (§3.2 — count your messages), and every call can fail in the ambiguous ways of §3.3. Lectures 2–5 give the tools. These notes do not provide P1 code.
  • Problem Set 1 (assigned after Lectures 2–4) exercises latency/bandwidth arithmetic, marshalling across heterogeneous machines and delivery semantics; §3.2–3.3 and Exercises 1–3 are the warm-up.

Further reading

  • H. A. Simon, “The Architecture of Complexity”, Proceedings of the American Philosophical Society 106(6), 1962 — the watchmakers parable and “nearly decomposable” systems (course reading).
  • A. Singla, B. Chandrasekaran, P. B. Godfrey, B. Maggs, “The Internet at the Speed of Light”, HotNets 2014 — how far today’s Internet is from the c-latency floor, layer by layer (course reading).
  • J. H. Saltzer, D. P. Reed, D. D. Clark, “End-to-End Arguments in System Design”, ACM TOCS 2(4), 1984 (course reading; Lecture 4).
  • L. Lamport, “Time, Clocks, and the Ordering of Events in a Distributed System”, CACM 21(7), 1978 — the definition by message delay and logical clocks (Supplement S1).
  • J. Waldo, G. Wyant, A. Wollrath, S. Kendall, “A Note on Distributed Computing”, Sun Microsystems Laboratories technical report SMLI TR-94-29, 1994 — why remote is not local.
  • A. S. Tanenbaum and M. van Steen, Distributed Systems, 3rd ed., chapter 1 (definitions, goals, transparency, pitfalls).
  • N. Lynch, Distributed Algorithms, the chapter on consensus with link failures — the formal two-generals (coordinated attack) impossibility and its randomized variants.

Preview of Lecture 2 — Communication: latency, bandwidth and the network stack

Today we treated “the network” as a box that delays and sometimes loses messages. Next we open the box just enough to reason precisely: the four components of delay (transmission, propagation, queueing, processing), store-and-forward across several hops, the bandwidth-delay product and why a protocol that waits for an acknowledgment after every packet can waste most of a fast link, how windows and pipelining fix it, what TCP and UDP really promise, and why the tail of the latency distribution — not its average — decides how fast a large service feels. We will measure real throughput over loopback and simulate transfers on dsim with link bandwidth added.


术语表 (Glossary, English → 中文)

English中文
distributed system分布式系统
autonomous computing element自治计算单元
single coherent system单一连贯的系统
node / host / process节点 / 主机 / 进程
message passing消息传递
shared memory共享内存
independent failure独立失效
partial failure部分失效
failure domain故障域
global clock / global state全局时钟 / 全局状态
latency / one-way latency / round-trip time (RTT)延迟 / 单向延迟 / 往返时间
bandwidth / throughput带宽 / 吞吐量
latency-bound / bandwidth-bound受延迟限制 / 受带宽限制
bandwidth-delay product带宽时延积
speed of light / propagation delay光速 / 传播延迟
latency inflation延迟膨胀
loopback interface回环接口
system call系统调用
percentile / median / tail latency (p99)百分位数 / 中位数 / 尾延迟
fan-out扇出
scale out / scale up横向扩展 / 纵向扩展
bottleneck / bottleneck law瓶颈 / 瓶颈定律
availability / “nines”可用性 / 几个”9”
redundancy / replica冗余 / 副本
majority / quorum多数派 / 法定人数(仲裁集)
correlated failure相关性故障
mean time between failures (MTBF)平均故障间隔时间
edge computing / content delivery network (CDN)边缘计算 / 内容分发网络
fallacies of distributed computing分布式计算的谬误
timeout / retry超时 / 重试
failure detector故障检测器
at-most-once / at-least-once / exactly-once至多一次 / 至少一次 / 恰好一次
idempotent operation幂等操作
duplicate detection / request id重复检测 / 请求标识
stable storage稳定存储
two generals problem (coordinated attack)两将军问题(协同攻击问题)
impossibility result不可能性结果
indistinguishable runs不可区分的执行
acknowledgment (ACK)确认(应答)
replica divergence副本分歧
commutative operation可交换操作
sequencer / total order定序器 / 全序
hold-back queue暂存队列
clock skew / clock drift时钟偏差 / 时钟漂移
clock synchronization (NTP)时钟同步(网络时间协议)
Lamport clock / happened-beforeLamport 逻辑时钟 / 先发生关系
consistent snapshot一致快照
heterogeneity / byte order (endianness)异构性 / 字节序
marshalling (serialization)编组(序列化)
transparency (location / migration / replication / failure)透明性(位置 / 迁移 / 复制 / 故障)
abstraction / modularity抽象 / 模块化
nearly decomposable system近可分解系统
subassembly子组件(部件组装体)
checkpoint / checkpoint interval检查点 / 检查点间隔
optimistic / pessimistic design乐观 / 悲观 设计
transaction / atomicity事务 / 原子性
consensus共识
end-to-end argument端到端原则
interposition插入(拦截)技术
discrete-event simulation / deterministic离散事件仿真 / 确定性的
nondeterminism非确定性
← 返回课程目录