Maps to: CMU 15-440/640 Spring 2026, the theme of naming and the learning outcome on client-server and peer-to-peer strategies. Problem set: PS4 asks for a Chord finger table and lookup on a given ring, and asks which of GFS and Ceph suits given applications. This lecture teaches the concepts and answers nothing there: its example ring has 6-bit identifiers and different nodes, no workload is matched to a system in PS4’s form, and the exercises have different shapes. Sources:
- S. Ghemawat, H. Gobioff and S.-T. Leung, The Google File System (SOSP 2003);
- M. K. McKusick and S. Quinlan, GFS: Evolution on Fast-forward (ACM Queue 2009);
- S. Weil, S. Brandt, E. Miller, D. Long and C. Maltzahn, Ceph: A Scalable, High-Performance Distributed File System (OSDI 2006);
- S. Weil, S. Brandt, E. Miller and C. Maltzahn, CRUSH: Controlled, Scalable, Decentralized Placement of Replicated Data (SC 2006);
- D. Karger et al., Consistent Hashing and Random Trees (STOC 1997);
- D. Thaler and C. Ravishankar, Using Name-Based Mappings to Increase Hit Rates (IEEE/ACM ToN 1998), the rendezvous (highest random weight) hash;
- J. Lamping and E. Veach, A Fast, Minimal Memory, Consistent Hash Algorithm (2014);
- V. Mirrokni, M. Thorup and M. Zadimoghaddam, Consistent Hashing with Bounded Loads (SODA 2018);
- I. Stoica, R. Morris, D. Karger, M. F. Kaashoek and H. Balakrishnan, Chord: A Scalable Peer-to-peer Lookup Service for Internet Applications (SIGCOMM 2001);
- G. DeCandia et al., Dynamo: Amazon’s Highly Available Key-value Store (SOSP 2007);
- A. Cidon et al., Copysets: Reducing the Frequency of Data Loss in Cloud Storage (USENIX ATC 2013);
- C. Blake and R. Rodrigues, High Availability, Scalable Storage, Dynamic Peer Networks: Pick Two (HotOS 2003);
- F. Dabek et al., Designing a DHT for Low Latency and High Throughput (NSDI 2004).
The slides are not public; this is not a transcript. Every number not attributed to a source comes from
code/lecture25/, run on the author’s machine (Apple M4 Pro, macOS, Python 3.13 and 3.9). Cluster and network time is simulated ondsim; everything is seeded. Code:code/lecture25/. Reading time: ~100 minutes, plus about half a minute to run the demos.
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- State the naming problem of large-scale storage, “where is object X?”, and its three answers: a directory, a computation, a route.
- Explain GFS’s design: one master holding all metadata in memory, 64 MB chunks, three replicas, data never passing through the master, and why each choice follows from the workload.
- Describe a GFS mutation: leases, the primary and its serial order, data flow decoupled from control flow; and what consistent, defined and inconsistent regions mean.
- Explain record append and its at-least-once semantics, and how applications live with padding and duplicates.
- Explain re-replication priorities, rack-aware placement, chunk version numbers and master recovery.
- Explain why hash mod N fails under change, and how consistent hashing, virtual nodes, rendezvous hashing, jump hashing and bounded loads trade balance, movement, state and work.
- Explain Ceph’s pipeline of objects → placement groups → CRUSH → OSDs: failure-domain rules, bucket algorithms, cluster maps and epochs; and why the number of distinct replica groups decides how often correlated failures lose data.
- Explain Chord: the identifier circle, successors, finger tables, O(log N) lookups, stabilization, successor lists and replication on successors.
- Say when peer-to-peer beats client-server and when it does not: aggregate capacity on one side, lookup latency, churn, availability and repair bandwidth on the other.
0.2 Prerequisites and scope
- Prerequisites:
- Lecture 5: naming in distributed file systems, location transparency, AFS volumes;
- Lecture 7: leases;
- Lecture 13: system failure rates grow with the number of components; correlated failures;
- Lecture 17: write-ahead logs and checkpoints;
- Lecture 19: primary-backup replication and quorums;
- Lecture 20–21: Paxos (Ceph’s monitors and Chubby use it);
- Lecture 23: Sybil attacks;
- Lecture 24: MapReduce, which reads its input from GFS.
- Scope:
- Covered: GFS, Ceph’s data placement and object replication (RADOS), consistent hashing and its relatives, Chord.
- Mentioned briefly: Ceph’s metadata servers, HDFS, Colossus, Dynamo, Kademlia, Pastry, CAN, BitTorrent.
- Not covered: erasure coding in depth, block storage and file system interfaces on top of RADOS, content delivery networks.
0.3 Section → code map
| Section | Idea | Demo in code/lecture25/ |
|---|---|---|
| §2.2 | one master, how much metadata | 01_gfs_basics.py Part A, gfs.py |
| §2.3 | leases, mutation order, consistent vs defined | 01_gfs_basics.py Parts B, C |
| §2.4 | data flow along a chain | 02_gfs_failures.py Part A |
| §2.5 | record append | 01_gfs_basics.py Part D |
| §2.6–2.8 | re-replication, stale replicas, master recovery | 02_gfs_failures.py Parts B–D |
| §3 | hash mod N, consistent hashing, rendezvous, jump, bounded loads | 03_consistent_hashing.py, hashing.py |
| §4 | Ceph: placement groups, CRUSH, map epochs, copysets | 04_crush_placement.py, crush.py |
| §5.2–5.3 | Chord finger tables and lookups | 05_chord_lookup.py, chord.py |
| §5.4–5.5 | joins, stabilization, failures, churn | 06_chord_dynamics.py |
| §6 | peer-to-peer vs client-server | 07_p2p_vs_cs.py |
All demos are built on rpcnode.py, which lets a dsim node be written as a straight-line program that makes remote calls: reply = yield ("call", dst, msg, timeout).
0.4 Notation
- N nodes (servers, chunkservers, OSDs or peers). r replicas of each item. K keys or objects.
- m bits of a Chord identifier; the circle has 2^m positions. succ(k) is the first node at or after k, clockwise.
- B bytes to transfer, T link throughput, L one-way latency.
- f the fraction of nodes that fail; u the probability that a node is up.
- “x × the mean” for load: the busiest node’s load divided by the average (1.00 is perfect balance).
1. Where is object X?
1.1 Naming, at scale
Lecture 5 met naming in a distributed file system: a client must turn a path name into “which server, which file”. AFS made that cheap with volumes and a small, replicated volume location database. Now scale it up by four or five orders of magnitude: billions of objects, thousands of storage machines, a few of which fail every day, and a membership that changes all the time. The question stays the same:
Given the name of an object, which machines hold it?
There are only three kinds of answer, and this lecture is organised around them.
| Answer | How a client finds X | Who knows the mapping | Example here |
|---|---|---|---|
| A directory | ask the directory, then go to the machine | one service keeps a table | GFS’s master |
| A computation | compute f(X, map) locally | everyone who has the (small) map | consistent hashing, Ceph’s CRUSH |
| A route | ask a node, which forwards you closer, until someone knows | nobody knows everything; each node knows a little | Chord and other DHTs |
An analogy. In a small library, a catalogue tells you the shelf of every book (a directory). A big warehouse may instead shelve books by a rule (“by the first letters of the title, in this aisle order”), so that anyone who knows the rule walks straight to the shelf (a computation). In a city with no catalogue, you ask a librarian who doesn’t know but knows someone in the right district, who knows someone in the right street (a route).
1.2 Why the choice is hard
Each answer pays somewhere else:
- A directory is simple and can make clever global decisions (where to put new data, what to re-replicate first). But it is one more service that must be fast, available and big enough for all the metadata. GFS’s bet is that with large chunks, one machine can do it.
- A computation needs no lookups at all. But the function decides where data lives, so a change in membership changes the function. The function must move only the data that has to move, and it must respect racks and power domains, which a plain hash knows nothing about.
- A route needs no global knowledge and no central service. But each lookup takes several network hops, and every node must keep its little piece of knowledge correct while nodes arrive and leave.
Two facts from earlier lectures make all of this urgent:
- Failures are routine. With N machines, failures arrive N times as often (Lecture 13). GFS’s paper opens with this: component failures are the norm, not the exception. A design that needs a human for each failure does not survive at scale.
- Membership changes. Machines are added for capacity, retired, or reimaged. In a peer-to-peer system, peers are someone’s laptop, and come and go every hour.
2. GFS: one master, big chunks
2.1 Assumptions, and why they matter
GFS (2003) was designed for Google’s data-processing workloads of the time: crawls, indexes, logs, MapReduce input and output (Lecture 24). The paper lists its assumptions explicitly, and the design follows from them; it is worth reading them as a list of decisions:
- The system is built from many inexpensive machines that fail often. Monitoring, detection and automatic recovery are part of the design, not an afterthought.
- A modest number of large files: a few million files, typically 100 MB or more, multi-GB files common. Small files must work, but need not be efficient.
- Reads are mostly large and streaming (hundreds of KB to MBs), plus some small random reads.
- Writes are mostly large appends. Once written, files are rarely modified. Random writes are supported, not optimized.
- Many clients append to the same file concurrently: files are used as producer-consumer queues and for merging results. Atomic appends with little synchronization are essential.
- Sustained bandwidth matters more than latency of an individual operation.
And one more, unusual for a file system paper: co-design. The same company wrote the applications and the file system, so GFS could relax the POSIX interface and its consistency model and let applications cope (§2.5). A general-purpose file system cannot do that.
Why this matters for the rest of the design. Big files → big chunks → few chunks → the metadata of the whole cluster fits in one machine’s memory → one master can decide everything with global knowledge. Append-mostly → the consistency model can be relaxed for random writes and made strong for appends. Streaming reads → no client data cache is worth having (no cache coherence problem, Lecture 7, at all).
2.2 Architecture: what the master knows (demo 01 Part A)
A GFS cell has one master, many chunkservers, and many clients (application processes linked with the GFS client library).
- A file is a sequence of fixed-size chunks of 64 MB. Each chunk has an immutable, globally unique 64-bit chunk handle given by the master.
- Each chunk is stored as an ordinary Linux file on (by default) three chunkservers.
- The master holds all metadata:
- the file namespace (with access control);
- for each file, the list of its chunk handles;
- for each chunk, its version number (§2.7) and the locations of its replicas.
- Data never flows through the master. A client translates (file, byte offset) into (file, chunk index), asks the master for that chunk’s handle and replica locations, caches the answer, and talks to a chunkserver directly. Many reads of a chunk then cost the master nothing; the client also asks for several chunks per request.
Two details show the thinking.
Not all metadata is persistent. The namespace and the file → chunks mapping are logged to an operation log (a write-ahead log, Lecture 17) and checkpointed. The replica locations are not: the master asks every chunkserver what it holds when it starts, and keeps up to date through regular heartbeats. The paper’s reason is a good general principle: the chunkserver has the final word on what is on its own disks. Disks fail, operators rename machines, chunks vanish; keeping a second, persistent copy of that fact on the master would only create a second copy that can be wrong.
Everything is in memory. That makes master operations fast and lets the master scan its whole state in the background (for garbage collection, re-replication and rebalancing). It also means the memory of one machine limits the cluster. How tight is that limit? The paper says the master keeps less than 64 bytes per chunk, and less than 64 bytes per file (prefix-compressed path names). Demo 01 Part A does the arithmetic:
| chunk size | chunks in 1 PB | master RAM at 64 B per chunk | master lookups to stream a 1 TB file |
|---|---|---|---|
| 64 MB (GFS) | 14,901,161 | 0.95 GB | 14,901 |
| 8 MB | 119,209,289 | 7.63 GB | 119,209 |
| 1 MB | 953,674,316 | 61.04 GB | 953,674 |
| 64 KB | 15,258,789,062 | 976.56 GB | 15,258,789 |
The paper’s own two clusters (its Table 2) had 992,000 and 1,550,000 chunks with 48 MB and 60 MB of metadata at the master: about 28 and 26 bytes per chunk or file, computed here. So big chunks make the single master possible. They also make it cheap to cache all locations of a multi-TB working set in a client, and they let a client keep one TCP connection to a chunkserver for a long time.
The price of big chunks, which the paper reports honestly: a small file is one chunk, so its three chunkservers become hot spots when hundreds of clients read it at once. This happened when an executable was stored in GFS and started on hundreds of machines; the fix was a higher replication factor for such files and staggered start times.
2.3 Mutations: leases and one order per chunk (demo 01 Parts B and C)
A write must reach all three replicas, and two concurrent writes must be applied in the same order everywhere, or the replicas diverge. Who chooses the order? Asking the master for every write would make it a bottleneck. GFS delegates it with a lease (Lecture 7):
- The master gives one replica a chunk lease for 60 seconds; that replica becomes the primary. While the chunk is being written, the primary renews the lease on its heartbeats.
- The primary chooses a serial order for all mutations to the chunk; the other replicas (secondaries) apply them in that order.
- So the global order is: by lease grant order (chosen by the master), and within a lease by the primary’s serial numbers.
- If the master loses contact with a primary, it can safely give the lease to another replica after the old lease expires. Two primaries at once is the one thing that must never happen, and a lease bounds it in time without any agreement protocol, as long as clocks run at about the same rate (Lecture 7, Supplement S1).
The write path, in the paper’s seven steps:
- The client asks the master which replica holds the lease, and where the others are. (If nobody holds it, the master grants one.)
- The master replies; the client caches it.
- The client pushes the data to all replicas, in any order (§2.4). Each holds it in a buffer.
- Once all replicas have the data, the client sends the write request to the primary. The primary assigns it the next serial number and applies it.
- The primary forwards the request to the secondaries, which apply it in serial-number order.
- The secondaries tell the primary they are done.
- The primary replies to the client, with any errors. If some secondary failed, the write may have been applied at the primary and some secondaries: the client is told it failed, and retries.
gfs.py implements exactly this. A real bug found along the way shows why “in serial-number order” is not a detail:
- The first version sent the primary’s “apply” messages over dsim’s default links, which can reorder messages.
- Two concurrent writes then reached one secondary in the other order, and 5 of 40 concurrent-write runs ended with replicas that differed byte for byte.
- GFS talks over TCP, which delivers in order; with FIFO links all 200 runs of demo 01 Part B end with identical replicas.
What does a region look like after mutations? GFS’s consistency model uses two words, defined per file region:
- consistent: all clients see the same data, whichever replica they read;
- defined: consistent, and clients see what one mutation wrote, in its entirety.
| situation | the region is |
|---|---|
| a write succeeds with no concurrent writer | defined |
| concurrent writes all succeed | consistent but undefined: identical replicas, but the bytes may be fragments of several writes |
| a write fails | inconsistent: replicas may differ, so different readers see different data |
| record append succeeds | defined (at the offset it returns), with possibly inconsistent padding or duplicates around it (§2.5) |
Demo 01 Part B makes “consistent but undefined” concrete. Two clients each write 300 bytes at offset 100 of a file with 256-byte chunks, so each write spans chunks 0 and 1, and the client library splits it into two mutations, one per chunk, each ordered by that chunk’s primary. Over 200 runs with random network delays:
| what the region holds | runs |
|---|---|
| all A | 93 |
| all B | 94 |
| mingled (A’s bytes in one chunk, B’s in the other) | 13 |
The replicas were byte-for-byte identical in all 200 runs (consistent). In 13 runs the region mixed the two writes, e.g. B × 156 in chunk 0 and A × 144 in chunk 1: two primaries ordered the two halves differently. And in the other 187 runs, one client’s whole write vanished under the other’s; neither client is told. That is “undefined” too, and it is why GFS applications do not overwrite shared regions concurrently.
Demo 01 Part C makes “inconsistent” concrete. One secondary misses the apply of a write (a dropped message); the primary reports failure to the client, which (configured not to retry) reports it to the application:
| replica | bytes 50.. after the failed write | after the application’s retry |
|---|---|---|
| cs00 (primary) | NNNNNNNNNNNN... | NNNNNNNNNNNN... |
| cs01 (missed the write) | oooooooooooo... | NNNNNNNNNNNN... |
| cs05 | NNNNNNNNNNNN... | NNNNNNNNNNNN... |
Two versions of the region on three replicas: a reader going to cs01 sees old data, a reader going elsewhere sees new. The retry makes the region defined again.
Why accept this? Strong consistency for overlapping concurrent writes would need the client to lock regions or the master to order writes across chunks. GFS’s applications almost never overwrite, and those that write a file from start to end use a simple discipline instead: write, then atomically rename the file to its final name (or checkpoint how far the file is valid), as Lecture 24’s MapReduce commits its output.
2.4 Data flow: push along a chain (demo 02 Part A)
Step 3 separates the data flow from the control flow. Control goes client → primary → secondaries. Data goes wherever the network makes it cheapest:
- Along a chain, not a star or a tree: the client sends to the closest replica, which forwards to the closest remaining replica, and so on. Each machine’s full outbound bandwidth carries the data once, instead of being divided among recipients.
- Closest first, using the network topology (in Google’s network, distances could be estimated from IP addresses), so data avoids crossing slow inter-switch links twice.
- Pipelined: a chunkserver forwards each piece as soon as it has received it.
Without congestion, the paper’s ideal time to push B bytes to R replicas is B/T + R·L, T being the throughput and L the latency of one link. With 100 Mbit/s links and L far below a millisecond, 1 MB takes about 80 ms.
rpcnode.py models a network card of finite speed (each machine sends one message at a time at nic_bps). Demo 02 Part A pushes 1 MB to three replicas at 100 Mbit/s with L = 0.5 ms:
| how the data flows | time until all 3 have it | × ideal (81.5 ms) |
|---|---|---|
| chain, whole 1 MB per hop (store and forward) | 243.0 ms | 2.98 |
| chain, 256 KB pieces | 125.0 ms | 1.53 |
| chain, 64 KB pieces (pipelined) | 93.7 ms | 1.15 |
| chain, 16 KB pieces | 86.2 ms | 1.06 |
| star: the client sends each piece to each replica | 241.0 ms | 2.96 |
Store-and-forward and the star both take about 3 × 80 ms: in one case each hop waits for the previous one, in the other the client’s card carries the data three times. The pipelined chain approaches the ideal; the remaining gap is the last piece’s trip down the chain, (R − 1) × piece / T, which shrinks with the piece size. (A fixed 100 ms time-out in the first version of gfs.py made the 1 MB store-and-forward push “fail” after 181 ms; time-outs now scale with the bytes in flight. A time-out shorter than the transfer it guards is a classic bug.)
2.5 Record append: at least once (demo 01 Part D)
Many GFS files have hundreds of producers appending to them at once: merged MapReduce output, logs, producer-consumer queues. With ordinary writes, each producer would have to find the end of the file and write there; two producers that find the same end overwrite each other. Avoiding that needs a distributed lock. GFS instead offers record append: the client gives only the data; GFS chooses the offset and returns it.
The mechanism adds a little logic at the primary:
- The client pushes the record to all replicas of the file’s last chunk, then asks the primary to append.
- The primary checks whether the record fits in the chunk (64 MB). If not, it pads the chunk to its full size, tells the secondaries to pad too, and tells the client to retry on the next chunk. (A record is at most 1/4 of a chunk, to bound the space wasted on padding.)
- Otherwise the primary appends at the current end of its replica, and tells the secondaries to write at exactly that offset.
- If any replica fails, the client retries. So a record can be written more than once, and replicas need not be byte-identical.
The paper states the guarantee precisely: the data is written at least once as an atomic unit. For the operation to report success, the record must have been written at the same offset on all replicas of some chunk; after that, every replica is at least that long, so later records get higher offsets even if another replica becomes primary.
What are applications left with? Padding, duplicates, and fragments of failed attempts. The paper’s answer is self-validating, self-identifying records: each record carries a checksum (to skip garbage and padding) and a unique id (to drop duplicates when the application cannot tolerate them). gfs.encode_record and gfs.scan_records are such a library.
Demo 01 Part D: four producers append 25 records each, one after another, while 5% of the primary’s “apply” messages to secondaries are lost.
| method | acknowledged | commit attempts | records read | duplicates | distinct records | bytes skipped |
|---|---|---|---|---|---|---|
| record append | 100 / 100 | 155 | 107 | 7 | 100 | 345 |
| find the end, write there | 100 / 100 | 113 | 29 | 0 | 29 | 106 |
- Every record was delivered. 155 attempts were needed: 10 failed at some replica and were retried, which left the 7 duplicates; 45 found the 256-byte chunk full and moved on (with GFS’s 64 MB chunks this is rare).
- Reading only the first, second or third replica of every chunk gives 110, 104 and 105 records, with 267, 421 and 395 skipped bytes. After de-duplication, each is the same set of 100 records, though the replicas differ byte for byte.
- The application-level append lost 71 of 100 records, though every write was acknowledged: producers chose the same offset. This is the race record append exists to remove.
The general lesson. GFS pushes part of the consistency problem up to the application, on purpose. It works because the applications are few, written by the same organization, and use a shared record library. Lecture 4’s end-to-end argument in action: the application must check its records anyway (disks corrupt data), so the file system need not guarantee exactly-once.
2.6 The master’s other jobs: placement, re-replication, garbage (demo 02 Part B)
With global knowledge, the master manages replicas:
- Placement. New replicas go to chunkservers with below-average disk use, limit the number of recent creations per server (a new chunk predicts heavy writes), and spread over racks, so that a rack’s power or switch failure leaves a replica alive. Reads can use several racks’ bandwidth; writes pay for crossing racks.
- Re-replication. When a chunk has fewer live replicas than its goal, the master clones it from a live replica. Chunks are prioritized: one that has lost two replicas before one that has lost one; chunks of live files before recently deleted ones; chunks blocking a client first. Clones are rate-limited, per cluster and per chunkserver, so that recovery does not swamp client traffic.
- Rebalancing. The master gradually moves replicas for disk-space and load balance, and fills a new chunkserver slowly instead of sending it all new writes at once.
- Garbage collection. A deleted file is only renamed to a hidden name with a timestamp, and removed after three days. Orphaned chunks are found in the master’s regular scan, and chunkservers learn through heartbeats which of their chunks the master no longer knows. Lazy deletion is simpler and more reliable than eager deletion in a system where creation or deletion messages can be lost, and it gives a safety net against accidental deletion.
Demo 02 Part B kills two chunkservers (in different racks) of a 24-server, 6-rack cell holding 1,200 chunks × 3 replicas. Clones take 10.24 s each (a 64 MB chunk at the paper’s 6.25 MB/s per clone); heartbeats arrive every second and 10 s of silence means dead (our assumptions).
| re-replication order | clones at once | chunks left with 1 replica | all ≥ 2 replicas after | all 3 replicas after | clones |
|---|---|---|---|---|---|
| fewest replicas first | 10 | 21 | 43 s | 340 s | 300 |
| chunk-handle order | 10 | 21 | 329 s | 340 s | 300 |
| fewest replicas first | 4 | 21 | 76 s | 835 s | 300 |
| fewest replicas first | 40 | 21 | 32 s | 175 s | 300 |
- Priorities change when the data is safe, not when the work is done. The same 300 clones in a different order make every chunk survivable against one more failure after 43 s instead of 329 s. The paper reports the same effect: when two chunkservers with about 16,000 chunks each were killed, 266 chunks were left with a single replica; cloned first, they were back to at least two replicas within 2 minutes.
- Clone limits trade recovery time against client traffic: 4 concurrent clones take 835 s to restore full replication, 40 take 175 s. (At 40, the per-server limit of 2 caps the parallelism.) The paper’s single-chunkserver experiment restored 15,000 chunks (600 GB) in 23.2 minutes, with 91 concurrent clones allowed (40% of the chunkservers) at 6.25 MB/s each: an effective 440 MB/s.
- Rack-aware placement: killing two servers in the same rack left 0 chunks with a single replica, because no chunk has two replicas in one rack.
A bug in the first version of this demo is worth knowing. Breaking ties in placement by server name put every chunk on the same few fixed groups of three servers. Two failures then left 150 chunks with one replica, all on the same survivor, and the clone limits had no effect, because every clone had to come from that one machine. Random tie-breaking gave 21 endangered chunks spread over many survivors. The number of distinct replica groups turns out to matter much more than it seems; §4.6 comes back to it.
2.7 Stale replicas and version numbers (demo 02 Part C)
A chunkserver that was down while a chunk was written comes back with an old replica. If a client reads it, it gets stale data, and nothing in the bytes says so. GFS catches this with a chunk version number:
- Whenever the master grants a new lease, it increments the chunk’s version and tells the up-to-date replicas, which record it persistently, before any client may write.
- A replica that was unreachable misses the increment. When its chunkserver restarts and reports (chunk, version), the master sees an older version and treats the replica as stale: it is never given to clients, and is garbage-collected.
- As a second check, the master includes the version in its replies, and the client or chunkserver verifies it before reading or cloning.
- If the master sees a newer version than its own, it concludes that it failed while granting a lease, and adopts it.
Demo 02 Part C crashes a replica holder, writes the chunk while it is down (the version goes from 2 to 3), restarts it, and has a client in the same rack read (so the stale replica is its closest):
| master checks versions | chunkserver checks versions | reader got |
|---|---|---|
| on | on | new-data |
| on | off | new-data |
| off | on | new-data |
| off | off | old-data: a stale read |
Either check alone prevents the stale read: defence in depth.
A subtle race in the first version of gfs.py deserves a note. A heartbeat sent just before a version increment can arrive just after it, reporting the old version for a replica that did receive the increment. The master took such replicas for stale and deleted them; in one run every replica of a file vanished within 100 ms. The rule must be: a replica is stale only if it reports an old version and the master had already dropped it from its list of up-to-date replicas (because it was unreachable during the increment). An old heartbeat from a replica still on the list is just old news.
2.8 When the master fails (demo 02 Part D)
The single master is a single point of failure, and GFS treats it as such:
- The operation log is replicated on several machines; a mutation is committed only after its log record is flushed locally and remotely. The master batches log records to reduce the cost.
- Checkpoints (a compact B-tree-like image that can be mapped into memory) keep recovery short: replay only the log after the last checkpoint. A new checkpoint is built in a background thread while a new log file takes mutations.
- If the master machine dies, monitoring outside GFS starts a new master elsewhere from the replicated log. Clients use a DNS alias for the master.
- Shadow masters replay the log a fraction of a second behind and serve read-only metadata while the primary master is down.
Demo 02 Part D crashes the master of a cell with 1,000 chunks and restarts it 13 ms later:
| checkpoints | log records | replayed at restart | chunk locations known after | no new leases for |
|---|---|---|---|---|
| none | 1,004 | 1,001 | 7.5 ms | 60 ms |
| every 100 records | 1,004 | 1 | 7.5 ms | 60 ms |
The metadata comes back from the log (with a checkpoint, from almost nothing). The locations come back from the next round of heartbeats, because they were never persisted. And the restarted master grants no lease for one lease period: it has forgotten which leases it granted, and a primary from before the crash may still be acting on one. (The GFS paper states the rule for a primary the master loses contact with; applying it after a restart is our model’s choice, and the same reasoning as Lecture 7’s reboot grace period.) A write issued immediately after the restart succeeded once that period had passed.
2.9 What became of the single master
GFS worked for years at a scale its designers had not imagined, and its successor tells you where the single master gave out. In a 2009 interview (McKusick and Quinlan, ACM Queue), Sean Quinlan, a GFS tech lead, explained:
- The number of files, not bytes, became the problem: applications other than batch processing stored many small files, and the master’s memory and its operation rate limited the cell. Google ran many cells and split namespaces across them.
- Latency-sensitive applications, such as Gmail, suffered from master failover times and from the 64 MB chunk size.
- A successor design (later known as Colossus) distributed the master’s metadata over many machines and used smaller chunks.
The lesson is not that the single master was a mistake. It was the right simplification for the workload of 2003, and the paper says plainly that a few million files was the design point. When the workload changed, the assumption broke first. Hadoop’s HDFS copied GFS’s design (a NameNode and DataNodes) and met the same limits, later addressed with federation (several NameNodes for different parts of the namespace).
3. Hashing instead of a directory
3.1 Why not hash mod N? (demo 03 Part A)
The simplest computation: put object X on server h(X) mod N. No master, perfect spread, one hash per lookup. It works until N changes. When an eleventh server joins ten, a key stays put only if h mod 10 = h mod 11, which happens for about 1 in 11 keys. Demo 03 Part A, with 30,000 keys:
| scheme | moved when an 11th server joins | of which between OLD servers | moved when one of 10 leaves |
|---|---|---|---|
| hash mod N | 90.9% | 81.8% | 90.0% |
| ring, 1 point per server | 14.1% | 0.0% | 11.1% |
| ring, 100 virtual nodes per server | 9.2% | 0.0% | 9.4% |
| rendezvous (HRW) | 9.3% | 0.0% | 10.0% |
| jump hash | 9.3% | 0.0% | (only the last server can leave) |
The minimum is 1/11 = 9.1% when a server joins (its fair share must come from somewhere) and 10% when one of ten leaves. Hash mod N moves almost everything, and most of the movement is between servers that did not change at all: wasted transfers and, for a cache, cache misses everywhere at once. The other three schemes move about the minimum, and every moved key goes to the new server. This property is called monotonicity.
3.2 Consistent hashing: the ring (demo 03 Part B)
Karger et al. (1997) introduced consistent hashing for web caches. Hash both servers and keys onto a circle of positions 0 … 2^64 − 1; a key belongs to the first server clockwise from it.
- A new server takes over only the arc between its predecessor and itself: keys from exactly one other server move, and only those.
- A departing server’s keys go to its successor.
- Lookup: binary search in the sorted list of server positions (
hashing.Ring.owner).
Balance needs virtual nodes. With one position per server, the arcs are the gaps between N random points on a circle, and those are very uneven: the largest is about (ln N)/N of the circle, ln N times the fair share. The fix is to give each server many positions (virtual nodes, or “tokens”), so that its share is the sum of many small arcs. Demo 03 Part B, 100 servers and 100,000 keys:
| points per server | ring entries | busiest / mean | largest arc × N | 99th pct / mean | 1st pct / mean | servers below half the mean |
|---|---|---|---|---|---|---|
| 1 | 100 | 4.91 | 4.92 | 4.62 | 0.02 | 37 |
| 4 | 400 | 2.57 | 2.52 | 2.53 | 0.12 | 13 |
| 16 | 1,600 | 1.60 | 1.61 | 1.56 | 0.42 | 2 |
| 64 | 6,400 | 1.39 | 1.35 | 1.35 | 0.70 | 0 |
| 256 | 25,600 | 1.17 | 1.14 | 1.15 | 0.84 | 0 |
With one point, the busiest server holds 4.91 × the mean (close to ln 100 = 4.6) and 37 of 100 servers hold less than half; the Chord paper’s simulations show the same picture, with some nodes storing no keys at all. 256 points bring the busiest to 1.17 ×, at the cost of a 25,600-entry ring. The “largest arc” column confirms that the imbalance is in the arcs, not in which keys happened to be drawn.
Virtual nodes buy two more things:
- Weights: a server with twice the disk gets twice the points (demo 03 Part C; §3.3).
- Spread on failure: when a server with 100 points dies, its keys go to about 100 different successors instead of all to one. With one point, the successor’s load suddenly doubles (exercise 4).
3.3 Rendezvous and jump hashing (demo 03 Parts C and E)
Two alternatives with no ring at all.
Rendezvous hashing (Thaler and Ravishankar 1998), also called highest random weight (HRW): for key X, every server s computes a score from hash(X, s); the highest score wins.
- A new server takes a key only if it beats the old winner: monotone, minimal movement.
- When the winner leaves, each of its keys goes to that key’s second-best server: the load spreads over all servers, without virtual nodes.
- Weights work exactly: with u = hash(X, s) in (0, 1), the score −w_s / ln u makes server s win with probability exactly w_s / Σw. (−ln u / w is exponentially distributed with rate w, and the minimum of independent exponentials falls on each with probability proportional to its rate.) This is precisely Ceph’s straw2 bucket (§4.3).
- The cost: one hash per server per lookup, O(N).
Jump consistent hashing (Lamping and Veach 2014) has neither a table nor O(N) work. It follows the key as the number of buckets grows 1, 2, 3, …; when growing to j + 1 buckets, the key “jumps” to the new bucket with probability 1/(j + 1), the share the new bucket needs, using a pseudo-random sequence seeded by the key. It can skip straight from one jump to the next, so the expected number of steps is the harmonic number H_N = 1 + 1/2 + … + 1/N ≈ ln N + 0.58: measured 7.46 steps at N = 1,000 (H_N = 7.49). The limitation is fundamental: buckets are numbered, and only the last one can be removed. It suits data-shard numbering (e.g. “shard 0 … N − 1 of a table”), not a set of named, failing servers.
| lookup cost | state | weights | remove any server | |
|---|---|---|---|---|
| hash mod N | 1 hash | N | no | moves ~everything |
| ring (V points each) | 1 hash + log₂(NV) comparisons | NV entries | via points | yes |
| rendezvous | N hashes | N | exact | yes |
| jump hash | H_N steps | none | no | only the last |
Demo 03 Part C gives servers weights 4, 2 and 1. A ring with 50 points per unit of weight had a worst server at 1.27 × its fair share; weighted rendezvous at 1.05 ×. Ignoring the weights loads the small servers 1.94 × their fair share (they hold 48.8% of the keys for 26.3% of the capacity).
3.4 A hard cap: bounded loads (demo 03 Part D)
Virtual nodes make the imbalance small on average; nothing guarantees it. Consistent hashing with bounded loads (Mirrokni, Thorup and Zadimoghaddam 2018) does: each server has capacity ⌈(1 + ε) K / N⌉, and a key that finds its server full walks on clockwise to the next server with room. It has been adopted in production load balancers (HAProxy implements it).
| scheme | busiest / mean | moved when a 101st server joins | × the minimum |
|---|---|---|---|
| ring, 1 point per server | 4.96 | 1.79% | 1.8 |
| ring, 64 points per server | 1.45 | 1.32% | 1.3 |
| bounded loads, ε = 0.5 | 1.50 | 4.21% | 4.2 |
| bounded loads, ε = 0.25 | 1.25 | 7.15% | 7.2 |
| bounded loads, ε = 0.1 | 1.10 | 12.58% | 12.7 |
The cap holds exactly (1.10 × at ε = 0.1), and the price is movement: a joining server changes the capacity of every server and shifts the overflow chains, so 12.7 × the minimum moved at ε = 0.1. The paper bounds this extra movement in terms of 1/ε², and its intended use, assigning requests (short-lived) rather than data (expensive to move), fits that price.
3.5 Balanced keys are not balanced requests (demo 03 Part F)
Hashing balances keys. If some keys are much more popular than others, no hash function can balance requests: all requests for a key go to its server. Demo 03 Part F puts Zipf-distributed popularity on 100,000 keys, 64 points per server:
| request popularity | share of the most popular key | busiest server / mean (requests) |
|---|---|---|
| uniform | 0.00% | 1.39 |
| Zipf, s = 0.8 | 2.19% | 2.93 |
| Zipf, s = 1.0 | 8.27% | 8.76 |
| Zipf, s = 1.2 | 19.64% | 19.87 |
With s = 1 one key draws 8.3% of all requests, so its server serves 8.8 × the mean however evenly keys are spread. This is Lecture 24’s hot key again, and the cures are the same in spirit: replicate hot items on several servers (and spread reads over them), or cache them in front (Facebook’s memcache deployment and many CDNs do both).
3.6 Where these appear
- Distributed caches: client libraries for memcached (such as ketama) map keys to cache servers with a ring, so that adding a cache server does not empty all caches at once.
- Dynamo-style key-value stores (Dynamo, Cassandra, Riak) put nodes on a ring with virtual nodes; a key’s preference list is the first r distinct nodes clockwise (
hashing.Ring.preference), and Lecture 19’s quorums run over that list. - Load balancers map connections to backends with consistent hashing, so that a backend change breaks few connections (Google’s Maglev uses its own table-based variant).
- Ceph places data with weighted rendezvous hashing on a hierarchy: §4.
4. Ceph: computing placement
4.1 Separating data from metadata
Ceph (Weil et al., 2006) was designed for petabyte-scale storage with no central lookup on the data path. Its file system layer separates two jobs:
- Metadata (the namespace, directories, permissions) is managed by a cluster of metadata servers (MDS) that partition the directory tree among themselves dynamically (dynamic subtree partitioning) and move hot subtrees between servers.
- Data lives in RADOS, a reliable object store made of thousands of object storage devices (OSDs): a disk (or SSD) plus a daemon that stores objects, replicates them, detects failures and recovers.
A file’s data is striped into objects whose names are computed from the file’s inode number and the stripe number. So the MDS need not store a block list, and nobody stores where the objects are: every client and every OSD computes it.
4.2 Objects → placement groups → OSDs (demo 04 Part A)
Placement happens in two steps:
- pg = hash(object name) mod pg_num: objects are grouped into a few thousand placement groups (PGs).
- [primary, replica, replica] = CRUSH(pg, cluster map, rule): each PG is mapped to an ordered list of OSDs.
Why the middle layer? Tracking replication state per object (billions) is too much; tracking it per OSD pair is too coarse. A PG is the unit that OSDs peer on (agree on its contents after a failure), log changes for, and recover. The paper chose about 100 PGs per OSD, trading the variance of OSD utilization against the per-PG metadata each OSD keeps. Demo 04 Part A shows the variance side, on 64 OSDs:
| PGs per OSD | busiest / mean OSD load | least loaded / mean |
|---|---|---|
| 1 | 3.05 | 0.00 |
| 10 | 1.80 | 0.30 |
| 100 | 1.22 | 0.81 |
The same lesson as virtual nodes on a ring: balance needs many small units. The rule “chooseleaf firstn 3 type host” was respected for every PG: no two replicas on one host. Three independent hashes mod 64, by contrast, put two replicas on the same OSD in 97 of 2,133 PGs, and in the same host in 361. A placement function must know the failure structure of the cluster.
4.3 CRUSH (demo 04 Part B)
CRUSH (Controlled Replication Under Scalable Hashing) is a deterministic, pseudo-random function of (PG, map, rule).
- The cluster map is a hierarchy: root → rooms or rows → racks → hosts → OSDs. Each OSD has a weight (usually its capacity); each inner bucket weighs the sum of its children.
- A rule says how to walk it. “chooseleaf firstn 3 type host” means: choose 3 distinct hosts under the root, then one OSD inside each. “choose firstn 1 type row; chooseleaf firstn 3 type rack” would keep all replicas in one row (to limit cross-row traffic) but in different racks (power and switch failures).
- At each bucket, CRUSH chooses a child pseudo-randomly from hash(pg, replica number r, child), in proportion to the children’s weights.
- Collisions and failures: if the chosen host was already used for another replica, or the chosen OSD is marked out, CRUSH retries with a modified r’ = r + f (f = failures so far). Out devices stay in the hierarchy (so the weights above them do not change), and only the PGs that touched them are remapped.
How a bucket chooses among its children is the bucket algorithm, and the paper compares four. crush.py implements three:
- uniform: child[(hash(pg) + r · p) mod m] for a prime p: fast, but weights are ignored, and any change of m reshuffles the bucket;
- list: walk from the newest child; take child i with probability w_i / (weight of it and all older children). Optimal when items are only added, poor when an old one is removed;
- straw2: every child draws ln(u)/w; the largest draw wins. It is weighted rendezvous hashing (§3.3): a child’s draw depends only on itself, so changing one child moves data only to or from that child. (The paper’s original straw bucket scaled straws with a procedure in which changing one weight could move data among the others; Ceph replaced it with straw2 in 2015.)
Demo 04 Part B1 measures one bucket of 16 OSDs and 4,096 PGs, one replica each. Each cell gives the replicas moved, and moved ÷ minimum, where the minimum is the change in the affected OSD’s load:
| bucket | add an OSD | remove the newest | remove the oldest | reweight one OSD 1 → 2 |
|---|---|---|---|---|
| straw2 | 5.6% (1.0 ×) | 6.5% (1.0 ×) | 5.5% (1.0 ×) | 6.1% (1.0 ×) |
| list | 5.8% (1.0 ×) | 7.1% (1.0 ×) | 16.6% (2.4 ×) | 11.0% (1.9 ×) |
| uniform | 93.8% (17.0 ×) | 93.4% (15.2 ×) | 93.5% (15.7 ×) | 0.0% (weights ignored) |
This is the CRUSH paper’s Table 2 (uniform: poor; list: optimal on additions, poor on removals; straw: optimal), measured.
Through a hierarchy, movement exceeds the minimum even with straw2. Demo 04 Part B2, 64 OSDs in 4 racks × 4 hosts × 4 OSDs, 4,096 PGs × 3 replicas:
| change | replicas moved | minimum | moved / minimum | PGs whose primary changed |
|---|---|---|---|---|
| add one OSD to a host | 4.07% | 1.72% | 2.4 × | 3.5% |
| add a host of 4 OSDs | 10.29% | 5.94% | 1.7 × | 9.1% |
| mark one OSD out | 1.70% | 1.70% | 1.0 × | 1.8% |
| reweight one OSD 1 → 0.5 | 2.03% | 0.89% | 2.3 × | 1.8% |
The added weight also changes the choices of the rack and the host, so some PGs move into the changed rack but onto its old disks. The paper bounds the movement by h·Δw/W for a hierarchy of height h. Marking a device out costs exactly the minimum, because the weights stay and only rejected choices change. This is why Ceph operators mark failed disks out (data moves off), and add new disks with gradually increasing weights.
4.4 Cluster maps, epochs and monitors (demo 04 Part C)
Everything a client needs to locate data is the cluster map: the hierarchy, the weights, the rules, the set of down or out OSDs, and an epoch number incremented by every change. Its size depends on the number of devices, not on the amount of data:
| what locates data | size | grows with |
|---|---|---|
| CRUSH map (Ceph) | 21 buckets + 64 OSD weights + rule + epoch (demo 04) | the number of devices |
| chunk table (GFS master) | one entry per chunk | the data: 14.9 million entries for 1 PB in 64 MB chunks |
But a computed placement is only as good as the map it is computed from. After a host was added, a client still on the old epoch would send 9.1% of its requests to an OSD that is no longer the PG’s primary. Ceph tags every request with the sender’s map epoch. An OSD that has a newer map does not serve the request; it sends the client the incremental map updates it is missing. OSDs exchange map updates the same way, piggybacked on their normal traffic. The map is thus spread lazily, by gossip along the paths that need it.
Who decides the map? A small cluster of monitors (typically 3 or 5). OSDs report failures of their peers; the monitors filter transient problems, decide, and publish a new epoch. Agreeing on the next map is a consensus problem. The 2006 paper describes monitors built from elections, leases and two-phase commits; production Ceph’s monitors use Paxos (Lectures 20–21). So Ceph’s design is a mix: consensus on a small map, plus computation for every data access.
4.5 Replication inside RADOS
Once CRUSH has named a PG’s OSDs, RADOS replicates primary-copy style:
- Clients send writes to the PG’s primary, which orders them, forwards them to the replicas, and answers.
- RADOS separates two acknowledgements: an ack when the write is applied in all replicas’ memory (enough for application-level synchronization, such as POSIX semantics), and a commit when it is on disk at all replicas (enough for safety). Clients keep buffered writes until the commit, so a power loss to all replicas of a PG at once does not lose acknowledged data.
- Failure detection is distributed: each OSD monitors the peers it shares PGs with (replication traffic doubles as heartbeats), and reports silence to the monitors.
- Ceph distinguishes down (not responding: the next OSD in the list takes over as primary, nothing moves) from out (removed from the data distribution: CRUSH remaps its PGs and recovery copies data). An OSD goes out only if it does not come back quickly. The monitors deliberately mark OSDs down but not out after systemic events, such as a power loss to half the cluster, to avoid a storm of re-replication.
- After a map change, the OSDs of each PG peer: the primary collects the PG’s version and recent change log from current and former members, decides the authoritative contents, and only then admits I/O. Objects missing at a replica are fetched in the background, or on demand if a client asks for them.
Compare GFS: there, the master decides everything about replicas; in RADOS, the OSDs do it themselves, coordinated by the map.
4.6 How placement decides data loss: copysets (demo 04 Part D)
Lecture 13 said that independent failures are the easy case and correlated ones the dangerous case. Cidon et al. cite operators’ reports that after a cluster-wide power outage about 0.5–1% of the nodes do not come back. The question: when 1% of nodes fail together, what is the chance that some data had all its replicas among them?
The answer depends on how many distinct replica groups the placement uses. Data is lost if any used group lies entirely inside the failed set.
- GFS / HDFS-style random placement: every chunk picks its own three servers, so with many chunks nearly every possible triple is in use somewhere.
- Ceph’s placement groups: only pg_num distinct groups, however much data there is.
- Copysets (Cidon et al. 2013): restrict placement to a small, deliberately chosen set of groups.
Demo 04 Part D, 1,000 nodes, 3 replicas, 10 random nodes (1%) failing at once, 20,000 trials:
| placement | distinct replica groups | P(data loss), simulated | formula | scatter width | recovery time vs random |
|---|---|---|---|---|---|
| random per chunk (GFS/HDFS), 200,000 chunks | 199,898 | 13.48% | 13.45% | 699 | 1 × |
| placement groups, ~100 per node (Ceph) | 33,329 | 2.34% | 2.38% | 181 | 4 × |
| copysets, scatter width 10 | 1,665 | 0.18% | 0.12% | 10 | 70 × |
| copysets, scatter width 2 (fixed triples) | 333 | 0.03% | 0.02% | 2 | 350 × |
The formula assumes the groups are independent random triples: P(loss) = 1 − (1 − G / C(1000, 3))^C(10, 3) for G groups. (The copyset rows rest on a handful of loss events, hence the gap.)
The trade-off is between frequency of loss and speed of recovery:
- Few groups make loss rare. But each node then shares data with only a few others (its scatter width), so when it fails, only those few can supply the data to rebuild it, and recovery is slow, which widens the window for a second failure.
- Many groups make recovery massively parallel (699 sources). But almost any combination of three failures destroys something. When data is lost under random placement, the amount lost is tiny (a chunk or two); under copysets, rare losses are large. Cidon et al. argue that many operators prefer rare, larger losses, since each loss event has a large fixed cost (restoring from backup, notifying customers).
Ceph’s PGs sit in between, and pg_num is a knob for exactly this. (This is also why the GFS placement bug of §2.6 was interesting: by accident, it was a copyset scheme.)
4.7 GFS and Ceph, side by side
The design choices, not a recommendation for any workload:
| GFS (2003) | Ceph / RADOS (2006) | |
|---|---|---|
| locating data | the master’s table (chunk → servers), cached by clients | computed by CRUSH from a small map |
| metadata service | one master (+ shadows); memory-bound | an MDS cluster for the namespace only; monitors (Paxos) for the map |
| unit of placement | a 64 MB chunk, placed individually | an object, grouped into PGs, placed by rule |
| failure domains | rack-aware placement by the master | arbitrary hierarchy in the map, enforced by rules |
| replication control | master grants leases; primary orders mutations | PG primary orders writes; OSDs peer and recover themselves |
| failure handling | master detects (heartbeats), prioritizes, clones | OSDs detect peers; monitors mark down/out; CRUSH remaps |
| consistency | relaxed: defined / consistent / inconsistent regions; record append at least once | strong per object (primary-copy, ack/commit), POSIX at the file layer |
| interface | GFS library (not POSIX), snapshots, record append | object, block and POSIX file interfaces on one store |
| designed for | huge files, appends, streaming reads, batch jobs | general-purpose storage at petabyte scale |
Both make the same fundamental move as AFS (Lecture 5): keep the data path away from the metadata service. They differ in how far they push it. GFS keeps a central directory and makes it cheap; Ceph replaces the directory with a function.
5. Distributed hash tables: Chord
5.1 From consistent hashing to routing
Consistent hashing assumes that every client knows every server (the whole ring). Inside a data center, with hundreds of servers and a coordination service, that is fine. Around 2000, peer-to-peer file sharing raised a different question: millions of machines owned by strangers, joining and leaving every hour, with no central party willing or able to keep the list.
- Napster (1999) kept a central index of who had which file; the transfers were peer-to-peer. One server answered every query, and when it was shut down (by a court), the system was gone.
- Gnutella (2000) had no index: a query was flooded to neighbours, their neighbours, and so on, up to a hop limit. No single point of failure, but every query costs a large part of the network, and rare items are not found.
- Distributed hash tables (2001: Chord, CAN, Pastry, Tapestry) asked for both: no central party and guaranteed lookups at a cost of O(log N) messages, with O(log N) state per node. The interface is that of a hash table: put(key, value), get(key). Every node is responsible for some keys, and any node can find the responsible node for any key.
5.2 The identifier circle and finger tables (demo 05 Part A)
Chord (Stoica et al. 2001) is consistent hashing plus routing:
- Nodes and keys get m-bit identifiers by hashing (SHA-1 of the node’s IP address, or of the key) onto a circle of 2^m positions.
- Key k is stored at succ(k): the first node whose identifier is ≥ k, clockwise. Exactly the ring of §3.2.
- Each node knows its successor. Following successors finds any key, but in up to N hops.
- Each node n also keeps a finger table: finger[i] = succ(n + 2^i) for i = 0 … m − 1. finger[0] is the successor; finger[m − 1] is the first node at least half the circle away.
Demo 05 Part A builds a 6-bit ring (positions 0–63) with 9 nodes: N2, N9, N17, N23, N30, N37, N44, N51, N58. Node N9’s finger table:
| i | start = 9 + 2^i | interval | finger[i] |
|---|---|---|---|
| 0 | 10 | [10, 11) | N17 |
| 1 | 11 | [11, 13) | N17 |
| 2 | 13 | [13, 17) | N17 |
| 3 | 17 | [17, 25) | N17 |
| 4 | 25 | [25, 41) | N30 |
| 5 | 41 | [41, 9) | N44 |
Six rows, but only three different nodes: the small fingers all point at the nearest successor.
Lookup(k) from node n:
- If k ∈ (n, succ(n)], the answer is succ(n).
- Otherwise, forward the query to the closest finger that precedes k: scan the fingers from the farthest down, and take the first f with f ∈ (n, k).
From N9, key 55: the farthest finger preceding 55 is N44; N44’s farthest finger preceding 55 is N51; and 55 ∈ (51, 58], so the answer is N58. The path N9 → N44 → N51 takes 2 hops; along successor pointers alone it takes 6.
Two conventions to note. Intervals on a circle wrap around: (58, 9) contains 60, 63, 0 and 5. Every comparison in chord.py goes through between(x, a, b) and between_right(x, a, b), which handle the wrap-around and the case a = b; getting these wrong is the most common Chord bug. And lookups can be iterative (the querying node contacts each hop itself, as in chord.py, so it notices dead hops) or recursive (each hop forwards the query, which is faster, since the answer can come straight back).
5.3 Why O(log N), and why ½ log₂ N (demo 05 Parts B–D)
The argument. Suppose the query is at node n and the target key k is at clockwise distance d from n, with 2^(i) ≤ d < 2^(i+1). Finger[i] is the first node at or after n + 2^i, which still precedes k (or is the answer), so forwarding to it covers at least half of d. Each hop at least halves the remaining distance. After log₂ N halvings, the distance is about 2^m / N, the average gap between nodes, and only a few nodes remain in it. So lookups take O(log N) hops with high probability (the paper’s Theorem 2).
Demo 05 Part B, 32-bit identifiers and 4,000 lookups per ring size:
| nodes N | mean hops | ½ log₂ N | 1st pct | 99th pct | max | successors only (mean) |
|---|---|---|---|---|---|---|
| 16 | 2.04 | 2.0 | 0 | 4 | 5 | 7 |
| 64 | 2.85 | 3.0 | 0 | 6 | 6 | 31 |
| 256 | 3.84 | 4.0 | 1 | 7 | 8 | 130 |
| 1,024 | 4.81 | 5.0 | 1 | 8 | 10 | 522 |
| 4,096 | 5.86 | 6.0 | 2 | 10 | 11 | – |
| 16,384 | 6.88 | 7.0 | 3 | 11 | 13 | – |
Why half? The Chord paper explains it with the binary representation of the distance. Write the distance from n to k in units of the average gap: it has about log₂ N significant bits. Following finger[i] clears bit i. When the next bit is already 0, no finger is needed for it. So the number of fingers followed is about the number of 1-bits, and a random number has half of its bits set. Demo 05 Part C checks this: at N = 4,096, 5.87 fingers were followed on average, against 6.00 one-bits in the distance.
How much state? A finger table has m rows (32 here, 160 with SHA-1), but at N = 16,384 they held only 14.4 distinct nodes on average (Part D): about log₂ N. A Chord node stays small even in a huge network.
5.4 Joining and stabilization (demo 06 Parts A and D)
Nodes arrive. A node n that wants to join must find its place, and the others must learn about it, without a global lock or a central coordinator, and while lookups keep running. Chord separates correctness (successor pointers) from performance (fingers), and repairs both lazily.
- join(n’): node n asks any member n’ to look up succ(n), and makes that its successor. It does not yet have a predecessor, and nobody points to it.
- stabilize(), run periodically by every node: ask your successor s for its predecessor x. If x lies between you and s, x is a closer successor (it joined recently): adopt it. Then notify your successor that you exist.
- notify(n): if you have no predecessor, or n lies between your predecessor and you, n becomes your predecessor.
- fix_fingers(), periodically: refresh one finger with a lookup, cycling through them.
- check_predecessor(), periodically: if your predecessor does not answer, forget it.
A newly joined node is found by lookups only after its predecessor’s next stabilize: until then, lookups for its keys still arrive at its successor. The paper proves that successor pointers become correct once joins stop, and that lookups stay correct (if slower) while fingers lag. When a node’s predecessor changes, the node hands over the keys that now belong to the newcomer.
Demo 06 Part A grows a ring to 40 nodes, one join per second, through random members, with lookups running every 50 ms:
| stabilize / fix one finger every | lookups correct while joining | wrong | all successors right after the last join | all fingers right after |
|---|---|---|---|---|
| 0.25 s / 0.05 s | 98.0% | 2.0% | 0.50 s | 1.7 s |
| 1.00 s / 0.20 s | 94.1% | 5.9% | 1.30 s | 5.0 s |
Of the 2.0% wrong answers, 1.4 percentage points returned the key’s successor from before a join in the last 3 s: the newcomer’s predecessor did not know it yet. Stabilizing more often shortens the window, at the price of more maintenance messages, a knob every DHT has.
Demo 06 Part D checks the hand-over: in a 100-node ring storing 5,000 keys, each of 10 joining nodes received exactly the keys it became responsible for, 60 on average (keys/N, as consistent hashing promises; between 0 and 185, because arcs vary). Hash mod N would have moved about 4,950 keys per join.
5.5 Failures: successor lists and replication (demo 06 Parts B and C)
Nodes also fail, without warning. If a node’s only successor fails, the ring is broken there. Chord’s defences:
- Successor lists: each node keeps its first r successors (refreshed by stabilize, which copies the successor’s list). When the first dies, the next takes over. If each node fails with probability 1/2, a list of length O(log N) keeps the ring connected with high probability (the paper’s Theorems 7–8).
- Routing around failures: an iterative lookup that times out on a hop backs up and asks the previous node for a different next hop (a farther-back finger, or a successor-list entry).
- Replication on successors: the node responsible for key k copies it to its r − 1 successors. If it fails, its successor, the new succ(k), already has the data. Data survives unless r consecutive nodes fail before repair: with independent failures of a fraction f, a key is lost with probability about f^r.
Demo 06 Part B: a stable ring of 200 nodes storing 2,000 keys; at t = 5 s a fraction of the nodes fails at once.
| r (successors, replicas) | failed at once | lookups correct 0–3 s after | hops then | correct 35–55 s after | keys still held | 1 − f^r |
|---|---|---|---|---|---|---|
| 1 | 25% | 69.3% | 4.92 | 100.0% | 71.7% | 75.0% |
| 3 | 10% | 98.7% | 4.16 | 100.0% | 100.0% | 99.9% |
| 3 | 25% | 95.3% | 5.37 | 100.0% | 99.0% | 98.4% |
| 3 | 50% | 68.7% | 6.39 | 100.0% | 90.8% | 87.5% |
| 6 | 50% | 95.3% | 6.60 | 100.0% | 99.0% | 98.4% |
- Successor lists keep lookups working while the ring repairs itself: in the first seconds after a quarter of the nodes failed, 95.3% of lookups were correct with three successors against 69.3% with one, at the cost of time-outs (5.37 hops instead of about 3.5).
- Repair is complete: 35 s later every configuration answered correctly.
- Data survives as 1 − f^r predicts: 90.8% of keys survived half the nodes failing with r = 3 (formula 87.5%), 99.0% with r = 6.
The repair path has a trap, which this lecture’s code fell into. What should a node do when all of its r successors are dead?
- The first version of
chord.pyfell back to “my successor is myself”. Stabilize then adopted its predecessor as its successor, and the next rounds walked it backwards around the ring, one predecessor per round. One such node out of 150 claimed 45% of the key space, and 38% of all lookups returned wrong answers, still 55 s after the failure. - The second attempt looked up “my identifier + 1”: the lookup came straight back to the node itself, because its predecessor still listed it as successor.
- What works: take the closest live finger clockwise as the new successor. Stabilize then walks back from it, one predecessor per round, to the true successor.
The general lesson is that self-stabilizing protocols must be checked from bad states, not only from good ones.
Churn. Demo 06 Part C keeps about 100 nodes with Poisson joins and failures at rate λ for 120 s:
| churn (joins + failures) | stabilize every | lookups correct | wrong | mean hops |
|---|---|---|---|---|
| 0.1 / s | 0.5 s | 100.0% | 0.0% | 2.96 |
| 0.1 / s | 2.0 s | 99.8% | 0.2% | 2.97 |
| 0.5 / s | 0.5 s | 99.9% | 0.1% | 2.98 |
| 0.5 / s | 2.0 s | 99.5% | 0.5% | 3.05 |
| 2.0 / s | 0.5 s | 99.1% | 0.9% | 3.14 |
| 2.0 / s | 2.0 s | 97.3% | 2.7% | 3.40 |
Errors grow with churn × stabilization period, the number of membership changes that happen between two repairs (the paper’s Figure 12 shows the same shape). Faster repair costs messages; §6.2 puts a price on that.
5.6 Other DHT geometries
Chord’s circle is one of several geometries, all with O(log N) state and hops:
- Kademlia (Maymounkov and Mazières 2002) measures distance as the XOR of identifiers. XOR is symmetric (d(a, b) = d(b, a)), so a node learns useful contacts from the queries it receives. Each node keeps k-buckets of up to k contacts per distance range, preferring long-lived contacts, and lookups query α contacts in parallel, so one slow or dead node costs no time-out. BitTorrent’s distributed tracker (the “Mainline DHT”, with millions of nodes) and IPFS use Kademlia.
- Pastry and Tapestry route by prefix: each hop matches one more digit of the key, which lets each routing-table entry be chosen among many candidates by network proximity.
- CAN places nodes in a d-dimensional torus; each node owns a zone, and lookups take O(d N^(1/d)) hops.
- One-hop DHTs keep the full membership at every node (Gupta, Liskov and Rodrigues 2004; Dynamo inside a data center): one hop per lookup, paid for by spreading every membership change to everyone (§6.2).
5.7 Security of open DHTs
An open DHT lets anyone join, and that is a problem (Lecture 23):
- Sybil: one attacker creates many identities. If identifiers are hashes of chosen names, the attacker can also choose where its nodes land, and surround a key.
- Eclipse: the attacker fills an honest node’s routing tables with its own nodes and controls everything that node sees.
- Routing and storage attacks: malicious nodes drop or misroute lookups, or deny holding data.
Defences known from the research literature include identifiers assigned by a certificate authority or derived from something costly (IP prefixes, proof of work), constrained routing tables whose entries can be checked, redundant routing along independent paths with checks of the results (Castro et al. 2002), and replication with majority answers. None is free, and fully open DHTs remain hard to secure; most production uses of DHT ideas run inside one organization’s data center, where every node is trusted.
6. Peer-to-peer or client-server?
6.1 Where the crowd wins: aggregate capacity (demo 07 Part A)
One server must send a file of F bits to N clients. With server upload u_s and client download d, client-server takes at least
D_cs = max(N F / u_s, F / d),
which grows linearly in N. If the clients forward pieces to each other (as in BitTorrent), the total upload capacity grows with the crowd. A lower bound (Kurose and Ross) is
D_p2p ≥ max(F / u_s, F / d, N F / (u_s + Σ u_i)):
the server must send at least one copy, each client must download one, and all N copies must be uploaded by someone.
Demo 07 Part A: a 1 GB file, server 1 Gbit/s up, peers 20 Mbit/s up and 200 Mbit/s down; the swarm simulation exchanges 200 pieces, rarest first.
| clients N | client-server | P2P lower bound | P2P swarm (simulated) | client-server / swarm |
|---|---|---|---|---|
| 10 | 80 s | 67 s | 68 s | 1.2 × |
| 100 | 800 s | 267 s | 280 s | 2.9 × |
| 1,000 | 8,000 s | 381 s | 424 s | 18.9 × |
With 1,000 clients, the swarm is 19 × faster than the server alone and close to its bound. With 10, P2P adds little: the server was not the bottleneck. P2P wins when the demand side brings the capacity (software updates, popular videos, large datasets sent to many machines; data centers use the same trick to distribute container images and model weights).
6.2 Where it loses: latency, churn, availability, repair (demo 07 Parts B and C)
Lookups across the wide area are slow. Each overlay hop goes to an arbitrary place on the Internet. Demo 07 Part B places 2,000 peers on a map with one-way latencies of 5–146 ms:
| how a key is found (and its data fetched) | messages | median | 95th pct | routing state |
|---|---|---|---|---|
| central directory (ask it, then the owner) | 2 round trips | 174 ms | 236 ms | 1 server |
| one-hop DHT (every peer knows every peer) | 1 round trip | 111 ms | 197 ms | 2,000 per peer |
| Chord, standard fingers | 6.34 hops | 412 ms | 614 ms | ~log₂ N per peer |
| Chord, nearest of 8 candidates per finger | 6.11 hops | 271 ms | 394 ms | ~log₂ N per peer |
Chord’s correctness only requires finger i to lie in [n + 2^i, n + 2^(i+1)), so each finger can be chosen among the nodes in that interval by network proximity (proximity neighbour selection, Dabek et al. 2004). That kept the hops but cut the median from 412 to 271 ms. A central directory is still faster, and a one-hop table faster still, if you can afford it.
Peers are not servers. Measurement studies of early file-sharing networks (Saroiu, Gummadi and Gribble 2002) found median session times of about an hour. If each replica is up with probability u, independently, an object with r replicas is available with probability 1 − (1 − u)^r (Part C):
| each replica up with probability | r = 1 | r = 3 | r = 6 | r = 10 |
|---|---|---|---|---|
| 0.5 (home peers) | 0.500000 | 0.875000 | 0.984375 | 0.999023 |
| 0.9 (lab machines) | 0.900000 | 0.999000 | > 0.999999 | > 0.999999 |
| 0.999 (data-center servers) | 0.999000 | > 0.999999 | > 0.999999 | > 0.999999 |
On peers that are up half the time, 3 replicas leave an object unavailable 12.5% of the time; even 10 leave 0.1%.
Repair bandwidth. Keeping r copies alive means re-creating the data of every node that leaves for good, and filling every node that joins. Blake and Rodrigues (2003) made the argument: per node, the repair traffic is about 2 × (data stored per node) / (node lifetime). For 10 GB per node:
| mean time a node stays | repair traffic per node |
|---|---|
| 1 hour | 44.4 Mbit/s |
| 1 day | 1.85 Mbit/s |
| 1 month | 0.0617 Mbit/s |
| 3 years (a server’s life) | 0.00169 Mbit/s |
With one-hour lifetimes, each peer would need 44 Mbit/s of upload, around the clock, just to stand still. Their title says it: high availability, scalable storage, dynamic peer networks: pick two. Routing state has a similar cost: a one-hop DHT with a million peers and one-hour sessions sees about 556 membership changes per second, all of which every peer must hear about (about 178 kbit/s at 40 bytes each). That is affordable for routing state, but not for data.
And everything from §5.7: strangers’ machines may lie, Sybils are cheap, NATs block incoming connections, and nobody can be called when it breaks.
6.3 Hybrids, and where DHT ideas live today
- BitTorrent finds peers through a tracker (a central directory) or the Kademlia DHT, and transfers peer-to-peer: centralized lookup where it is cheap, distributed capacity where it pays.
- Content delivery networks are “peer-to-peer among servers we own”: many machines close to users, with consistent hashing to pick the cache for each object.
- Data-center storage adopted the ideas and dropped the strangers: Dynamo, Cassandra and Riak use the ring, virtual nodes, preference lists and replication on successors. Membership is known (gossip within a few hundred trusted nodes), so lookups take zero or one hop.
- Ceph replaced the routing with a computation over a map agreed by consensus.
A fair summary: as a way to build storage with no trusted party, DHTs remained niche (BitTorrent’s DHT and IPFS are the big exceptions). As a set of ideas, consistent hashing, successor-list replication and self-stabilizing membership are everywhere.
6.4 Questions to ask
When choosing between a directory, a computation and a route, or between client-server and peer-to-peer, ask:
- Who owns the machines, and can they be trusted? Inside one organization, the hard parts of P2P (Sybils, NAT, lying peers) vanish.
- How fast does membership change? Hours (peers), days (VMs), years (servers)? Repair and routing maintenance scale with it.
- How much metadata is there per byte of data? Large objects make a central directory cheap; billions of small objects push toward computation.
- Is the bottleneck lookup or transfer? P2P helps with transfer capacity; it hurts lookup latency.
- What are the failure domains, and how correlated are failures? Placement must know racks and power; the number of distinct replica groups decides how often a correlated failure loses data.
- What consistency does the application need? GFS showed that relaxing it for a cooperative set of applications buys a lot of simplicity.
7. Design rules
- Keep the data path away from the metadata service. GFS’s clients cache locations and never move data through the master; Ceph’s clients compute locations. (AFS taught the same in Lecture 5.)
- Make the metadata small enough for its home. One master’s memory works with 64 MB chunks and a few million files; it fails with billions of small files.
- Delegate ordering with leases, and never grant a new lease before the old one has expired, including after a restart.
- Separate data flow from control flow, and push data along a pipelined chain chosen by topology.
- When you relax consistency, give applications the tools: self-identifying, checksummed records; atomic rename; record append.
- Version every replica, and check versions at more than one place.
- Re-replicate by danger, not by order, and rate-limit recovery.
- Never hash mod N for data that must stay put; use consistent or rendezvous hashing, with enough virtual nodes or placement groups for balance.
- Balance requests, not just keys: replicate or cache hot items.
- Teach the placement function the failure domains, and choose the number of distinct replica groups on purpose.
- Spread a changing map lazily, but tag every request with its epoch.
- Separate correctness state from performance state (Chord’s successors vs fingers), and repair both periodically, testing from bad states as well as good ones.
- Count the repair bandwidth before building storage on machines that come and go.
Summary
- Where is object X? Three answers: a directory (GFS), a computation (consistent hashing, CRUSH), a route (Chord).
- GFS: one master holds all metadata in memory, which is feasible because chunks are 64 MB.
- 1 PB needs about 1 GB of master memory; the paper’s clusters used about 27 bytes per chunk or file.
- Locations are not persisted; heartbeats report them.
- Leases give one primary per chunk, whose serial order every replica follows. Concurrent writes leave replicas identical but the region undefined (mingled in 13 of 200 runs); a failed write leaves it inconsistent.
- Data flows along a pipelined chain: 93.7 ms for 1 MB to 3 replicas, against 241 ms for a star; ideal 81.5 ms.
- Record append is atomic and at least once: all 100 records arrived, with 7 duplicates and 345 bytes of padding and garbage that self-identifying records let readers skip. Find-the-end-and-write lost 71 of 100.
- Re-replication by priority made all chunks survivable 43 s after a double failure instead of 329 s. Version numbers stop stale reads if either side checks them.
- The master restarts from its log and checkpoint and waits one lease period.
- The single master later hit limits in file counts and latency; its successor distributes metadata.
- Hashing:
- Hash mod N moved 91% of keys when one server joined ten.
- Consistent hashing, rendezvous and jump hashing move about the minimum (9.1%), and only to the new server.
- With one point per server, the busiest held 4.91 × the mean; virtual nodes fix that (1.17 × with 256).
- Rendezvous handles weights exactly; jump hash needs no state but only removes the last bucket; bounded loads guarantee a cap (1.10 ×) at the cost of extra movement (12.7 × the minimum).
- Hot keys defeat any hash: 8.8 × mean requests at Zipf s = 1.
- Ceph: objects → placement groups → CRUSH → OSDs, with no table anywhere.
- Rules respect failure domains; ~100 PGs per OSD balance the load (1.22 ×).
- straw2 buckets (weighted rendezvous) move exactly the minimum within a bucket; the hierarchy adds some (2.4 × for one added OSD).
- The cluster map is small and agreed by monitors (Paxos); requests carry epochs.
- RADOS: primary-copy replication, ack vs commit, down vs out, peering per PG.
- Copysets: the number of distinct replica groups decides how often 1% correlated failures lose data: 13.5% (random per chunk) vs 2.3% (PGs) vs 0.03% (fixed triples), traded against recovery parallelism.
- Chord: m-bit identifiers, succ(k), finger[i] = succ(n + 2^i).
- Lookups in ½ log₂ N hops (6.88 at 16,384 nodes) with about log₂ N distinct fingers (14.4).
- Joins through any member; stabilize/notify fix successors (0.5 s after the last join), fix_fingers the rest (1.7 s).
- Successor lists keep lookups working through mass failures (95% correct with r = 3 at 25% failed, against 69% with r = 1). Replication on successors keeps data with probability 1 − f^r.
- Errors grow with churn × stabilization period.
- P2P vs client-server: P2P wins on aggregate transfer capacity (19 × faster to 1,000 clients). It loses on lookup latency (412 ms vs 174 ms; proximity selection recovers part, 271 ms), availability on flaky machines, and repair bandwidth (44 Mbit/s per node at one-hour lifetimes). The ideas live on inside data centers.
Common pitfalls
- Assuming a central metadata server cannot scale, or that it always can: it is a matter of metadata per byte of data, and it changes when the workload does.
- Treating “consistent” as “correct”: GFS’s concurrent writes leave identical replicas holding fragments of different writes, and silently drop whole writes.
- Implementing append as “find the end, then write” with several writers.
- Expecting exactly-once from record append, or byte-identical replicas.
- Persisting facts that another component owns (replica locations), creating a second copy that drifts.
- Granting a new lease after a restart without waiting for the old ones to expire.
- Version checks in one place only, or a heartbeat-versus-version race that deletes live replicas.
- Hashing mod N for anything stateful; one point per server on a ring; using Python’s salted
hash()for placement. - Ignoring hot keys because the keys are balanced.
- Placement that ignores failure domains, or that uses so many distinct replica groups that any three failures lose data, or so few that recovery is slow.
- Getting circular interval comparisons wrong (wrap-around, a = b), the most common DHT bug.
- Repairing only from good states: a node whose whole successor list died must not point at itself.
- Building storage on peers without computing the repair bandwidth.
Exercises
-
A master’s memory budget. A GFS-like master has 64 GB of memory for metadata, with 64 bytes per chunk and 64 bytes per file. (a) How much file data (before replication) can it manage with 64 MB chunks, if files are large? (b) The cell’s new main user stores mail messages of 100 KB each, one per file. How many such files fit, and how much data is that? (c) Which of the master’s limits did (b) hit, and which two design changes would you consider?
Answer
(a) 64 GB / 64 B = 10⁹ chunks (ignoring the few files) × 64 MB = 64 PB. (b) Each file costs 64 B for its name and 64 B for its single, mostly empty chunk: 128 B per file, so 64 GB / 128 B = 5 × 10⁸ files. At 100 KB each that is only 50 TB: a thousand times less data than (a), in the same memory. Each file also costs master operations (create, open, lookup), so the operation rate may give out even before the memory does. (c) The limit is per-file metadata, not per-byte metadata: the number of files. Options: pack many small objects into large files (as Bigtable's SSTables do, so that GFS sees few files); smaller chunks would not help here (each file is one chunk anyway); distribute the namespace over several metadata servers (Colossus, HDFS federation, Ceph's MDS cluster); or put small objects in a different system, such as a key-value store. -
Pipelining, exactly. Data of B bytes is pushed along a chain of R replicas in pieces of p bytes, each link with throughput T and one-way latency L, and each machine forwarding a piece as soon as it has received it. (a) Show that the last byte arrives at about (B + (R − 1) p) / T + R L. (b) Evaluate for B = 64 MB, R = 3, T = 10 Gbit/s, L = 20 µs, with p = 64 MB and with p = 64 KB. (c) Why not make p as small as possible?
Answer
(a) The client sends the B bytes, which takes B/T, and the last piece reaches replica 1 after an extra L. Replica 1 forwards each piece as it arrives; its card sends the last piece p/T after receiving it, so the last piece reaches replica 2 at B/T + p/T + 2L, and replica R at B/T + (R − 1) p/T + R L. (b) B/T = 64 × 2²⁰ × 8 / 10¹⁰ ≈ 53.7 ms. With p = 64 MB: 53.7 + 2 × 53.7 + 0.06 ≈ 161 ms (store and forward). With p = 64 KB: 53.7 + 2 × 0.052 + 0.06 ≈ 53.9 ms. (c) Each piece costs per-message overhead (headers, interrupts, an RPC, an acknowledgement); tiny pieces turn the transfer into an overhead-dominated stream. The gain from shrinking p vanishes once (R − 1) p/T is small next to B/T, a few tens of KB at these rates. Demo 02 Part A shows the same curve: 125, 93.7 and 86.2 ms for 256, 64 and 16 KB. -
A record reader for an at-least-once file. You build a work queue on record append: producers append task records, one consumer reads the file sequentially. (a) What must each record contain so that the consumer can skip padding, fragments of failed appends and duplicates? (b) Two readers read the same file through different replicas. Can they see different sets of records? Different orders? (c) A task is “charge customer X €10”. What else is needed for exactly-once charging, and where does it belong?
Answer
(a) A recognizable header (magic bytes), the length, a checksum over the body (to reject padding, holes and partial records), and a unique id chosen by the producer (to drop duplicates). This is `gfs.encode_record`. (b) Not different sets: every successful append is at the same offset on all replicas of some chunk, so every replica holds every acknowledged record. They can see different *duplicates*, and so different orders after de-duplication if a reader keeps the first copy and the copies sit at different places. In demo 01 Part D the three replica views held 110, 104 and 105 records, and the same 100 after de-duplication. A reader that needs an order should order by record content (e.g. a producer sequence number), not by offset. (c) The consumer must remember which ids it has executed, durably and atomically with the charge itself (e.g. in the same database transaction as the payment), so that a consumer crash and re-read does not charge twice. That is Lecture 4's end-to-end argument: only the application can make this exactly-once. -
Virtual nodes and the departure spike. A ring of N = 50 cache servers, each serving 2,000 requests/s. (a) With one point per server, a server fails. Approximately how much load does each other server get? (b) Same with 100 points per server. (c) Why can (a) cascade?
Answer
(a) All the failed server's keys go to its single successor, which goes from about 2,000 to about 4,000 requests/s (more if the failed server's arc was large, which with one point per server is likely to vary by several ×); all others are unchanged. (b) The failed server's 100 arcs have 100 different successors, scattered over the ring: about 2,000/49 ≈ 41 extra requests/s per surviving server, a 2% increase. (c) If the successor in (a) was running at 60% of capacity, doubling its load overloads it; it fails or becomes so slow that clients time out and treat it as dead; its keys (now twice as many) move to *its* successor, and so on around the ring. A cascading failure caused by the placement function. Rendezvous hashing has the spreading property of (b) without virtual nodes. -
Rendezvous or ring for a small cluster? A web tier picks one of N = 8 cache servers for each request, at 10⁶ requests per second per load balancer. (a) Compare the work per request of rendezvous hashing and a ring with 200 points per server. (b) Which needs what state? (c) Which would you choose, and when would your answer change?
Answer
(a) Rendezvous: 8 hashes and comparisons per request. Ring: one hash plus a binary search over 1,600 entries (about 11 comparisons). Both take well under a microsecond with a fast non-cryptographic hash; at 10⁶ requests/s, rendezvous computes 8 million hashes a second, a fraction of one core. (b) Rendezvous needs only the list of 8 servers. The ring needs its sorted 1,600-entry table, rebuilt on each membership change. (c) With 8 servers, rendezvous is simpler, spreads a failed server's load evenly without virtual nodes, and supports exact weights: a natural choice. As N grows to thousands, O(N) hashes per request become too expensive. Then a ring (or a precomputed lookup table such as Maglev's, or hierarchical rendezvous, as CRUSH does) is better. -
firstn or indep? CRUSH has two ways to fill a list of n devices when one of them fails. With “firstn”, the failed device is skipped and the later ones shift up ([A, B, C] with B failed becomes [A, C, D]); with “indep”, each position is filled independently and only the failed position changes ([A, D, C]). (a) Why is firstn right for replication, where every copy is identical and the first is the primary? (b) Why is indep needed for erasure coding, where a 4 + 2 code stores 6 different fragments, position i holding fragment i? (c) With indep, how many fragments must be rebuilt when one device fails, and with firstn?
Answer
(a) With replication, positions mean nothing except "who is primary". firstn keeps A as primary, and after B fails, C (which already has a copy) moves up, so only one new copy is needed, on D. (b) With erasure coding, the device at position i must hold fragment i. Under firstn, C would move from position 3 to position 2 and suddenly be expected to hold fragment 2, and D fragment 3: both must be rebuilt, though C was healthy. Under indep, only position 2 changes. (c) indep: one fragment (the failed one). firstn: every fragment after the failed position shifts, so up to n − 1 fragments move, here 2 (positions 2 and 3, and every later one in a longer list). This is the paper's "replica ranks" discussion (section 3.2.2). -
Copyset arithmetic. A cluster has 500 nodes and 3 replicas, and a power event kills 5 random nodes. (a) Compute the probability of data loss if the cluster uses 50,000 distinct, random replica groups. (b) Same for 167 disjoint triples. (c) For (b), what is a node’s scatter width, and what does it mean for recovery after a single failure? (d) Suggest a scheme in between, and its scatter width.
Answer
Use P ≈ 1 − (1 − G / C(500, 3))^C(5, 3), with C(500, 3) = 20,708,500 and C(5, 3) = 10. (a) G / C = 50,000 / 20,708,500 ≈ 0.00241; P ≈ 1 − (1 − 0.00241)¹⁰ ≈ 2.4%. (b) 167 / 20,708,500 ≈ 8.1 × 10⁻⁶; P ≈ 8.1 × 10⁻⁵ ≈ 0.008%. (c) Each node shares data with exactly 2 others (its triple), so after a failure only those 2 can supply the data, and the copy is limited by their disks and links: recovery is slow, which leaves a longer window for a second failure in the same triple. (d) Copysets with scatter width S: S/2 random permutations of the nodes, each cut into triples. S = 10 gives 5 × 166 = 830 groups, P ≈ 1 − (1 − 4.0 × 10⁻⁵)¹⁰ ≈ 0.04%, and 10 sources to recover a node from: 5 × faster recovery than (b) at 5 × its loss probability. Ceph's pg_num plays the same role. -
How long a successor list? A Chord ring has N = 10,000 nodes. During one repair interval, each node fails independently with probability p = 0.5 (a severe event). (a) What is the probability that a given node loses all r successors? (b) Choose r so that the probability that any node loses all its successors is below 1%. (c) Each node also stores the keys of its predecessor’s arc on its successors (replication factor r). What is the probability that a given key is lost, and how many of 10⁷ keys would you expect to lose?
Answer
(a) p^r = 2^(−r). (b) By the union bound, N 2^(−r) < 0.01, i.e. 2^r > 10⁶, so r ≥ 20 = log₂(N / 0.01). That is Theorem 7's O(log N) with its constant: about log₂ N + 7 here. (c) A key is lost if all r nodes holding it fail: 2^(−20) ≈ 9.5 × 10⁻⁷, so about 10 keys of 10⁷. If losing even one key is unacceptable, r must grow with log of the number of keys, not just of the number of nodes, or repair must be fast enough that p is much smaller than 0.5.
Related project and problem set (concepts only)
- Problem Set 4 has a Chord question (a finger table and a lookup on a given 10-bit ring with 12 nodes, an insert time, a join) and GFS-vs-Ceph questions about given applications. §2–§5 give the concepts: finger tables and lookups (§5.2), joins and key hand-over (§5.4), GFS’s and Ceph’s design choices (§2, §4, §4.7), record append (§2.5). The PS’s ring, applications and numbers are not discussed, and no answers are given. Our example ring is 6-bit with different nodes, and the exercises above have other shapes.
- Project 2 (a caching proxy) and Project 3 (scaling a service) both meet §3’s question of mapping requests to servers, where consistent hashing keeps caches warm when servers come and go.
Further reading
- S. Ghemawat, H. Gobioff and S.-T. Leung, “The Google File System”, SOSP 2003.
- M. K. McKusick and S. Quinlan, “GFS: Evolution on Fast-forward”, ACM Queue 7(7), 2009.
- K. Shvachko, H. Kuang, S. Radia and R. Chansler, “The Hadoop Distributed File System”, MSST 2010.
- S. Weil et al., “Ceph: A Scalable, High-Performance Distributed File System”, OSDI 2006; “CRUSH: Controlled, Scalable, Decentralized Placement of Replicated Data”, SC 2006; “RADOS: A Scalable, Reliable Storage Service for Petabyte-scale Storage Clusters”, PDSW 2007.
- D. Karger et al., “Consistent Hashing and Random Trees”, STOC 1997.
- D. Thaler and C. Ravishankar, “Using Name-Based Mappings to Increase Hit Rates”, IEEE/ACM Transactions on Networking 1998.
- J. Lamping and E. Veach, “A Fast, Minimal Memory, Consistent Hash Algorithm”, arXiv 2014.
- V. Mirrokni, M. Thorup and M. Zadimoghaddam, “Consistent Hashing with Bounded Loads”, SODA 2018.
- D. Eisenbud et al., “Maglev: A Fast and Reliable Software Network Load Balancer”, NSDI 2016.
- I. Stoica et al., “Chord: A Scalable Peer-to-peer Lookup Service for Internet Applications”, SIGCOMM 2001 (and the longer IEEE/ACM ToN 2003 version).
- P. Maymounkov and D. Mazières, “Kademlia: A Peer-to-peer Information System Based on the XOR Metric”, IPTPS 2002.
- A. Rowstron and P. Druschel, “Pastry”, Middleware 2001; S. Ratnasamy et al., “A Scalable Content-Addressable Network”, SIGCOMM 2001.
- G. DeCandia et al., “Dynamo: Amazon’s Highly Available Key-value Store”, SOSP 2007.
- A. Cidon et al., “Copysets: Reducing the Frequency of Data Loss in Cloud Storage”, USENIX ATC 2013.
- C. Blake and R. Rodrigues, “High Availability, Scalable Storage, Dynamic Peer Networks: Pick Two”, HotOS 2003.
- F. Dabek et al., “Designing a DHT for Low Latency and High Throughput”, NSDI 2004.
- A. Gupta, B. Liskov and R. Rodrigues, “Efficient Routing for Peer-to-Peer Overlays”, NSDI 2004 (one-hop lookups).
- M. Castro et al., “Secure Routing for Structured Peer-to-Peer Overlay Networks”, OSDI 2002; J. Douceur, “The Sybil Attack”, IPTPS 2002.
- S. Saroiu, P. K. Gummadi and S. Gribble, “A Measurement Study of Peer-to-Peer File Sharing Systems”, MMCN 2002.
- B. Cohen, “Incentives Build Robustness in BitTorrent”, 2003.
Preview of Lecture 26 — Security in distributed systems
Every system in this lecture trusted its components: GFS trusts its chunkservers, Ceph its OSDs, Chord its peers (and §5.7 showed what happens when it cannot). Lecture 26 drops that assumption:
- channel security: confidentiality, integrity and freshness of messages on a network an attacker controls;
- authentication protocols: how two parties who share nothing but a trusted server prove who they are, why Needham–Schroeder needed fixing, and how Kerberos and AFS’s tokens work;
- authorization: access lists against capabilities;
- and a wrap-up of the whole course.
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| naming / name resolution | 命名 / 名字解析 |
| directory / lookup service | 目录 / 查找服务 |
| metadata / metadata server | 元数据 / 元数据服务器 |
| master / chunkserver / chunk / chunk handle | 主节点 / 块服务器 / 数据块 / 块句柄 |
| namespace / prefix compression | 命名空间 / 前缀压缩 |
| operation log / checkpoint | 操作日志 / 检查点 |
| heartbeat | 心跳 |
| hot spot | 热点 |
| lease / primary / secondary replica | 租约 / 主副本 / 从副本 |
| mutation / serial number / mutation order | 变更(写操作) / 序列号 / 变更顺序 |
| consistent / defined / undefined / inconsistent region | 一致的 / 已定义的 / 未定义的 / 不一致的区域 |
| relaxed consistency model | 宽松一致性模型 |
| data flow / control flow | 数据流 / 控制流 |
| pipelining / store-and-forward | 流水线传输 / 存储转发 |
| record append / at-least-once / padding / duplicate record | 记录追加 / 至少一次 / 填充 / 重复记录 |
| self-validating, self-identifying record | 自校验、自标识的记录 |
| replica placement / rack-aware placement | 副本放置 / 机架感知放置 |
| re-replication / cloning / rebalancing | 重新复制 / 克隆 / 再平衡 |
| garbage collection / orphaned chunk | 垃圾回收 / 孤儿块 |
| chunk version number / stale replica | 块版本号 / 过期副本 |
| shadow master | 影子主节点 |
| consistent hashing / hash ring | 一致性哈希 / 哈希环 |
| virtual node / token | 虚拟节点 / 令牌 |
| monotonicity / minimal disruption | 单调性 / 最小扰动 |
| rendezvous hashing / highest random weight | 汇合哈希 / 最高随机权重 |
| jump consistent hash / harmonic number | 跳跃一致性哈希 / 调和数 |
| consistent hashing with bounded loads | 有界负载一致性哈希 |
| preference list | 偏好列表 |
| hot key / load imbalance | 热点键 / 负载不均衡 |
| object storage device (OSD) | 对象存储设备 |
| metadata server (MDS) / dynamic subtree partitioning | 元数据服务器 / 动态子树划分 |
| placement group (PG) / peering | 放置组 / 对等同步 |
| CRUSH / cluster map / epoch | CRUSH 算法 / 集群映射 / 纪元(版本号) |
| bucket (uniform / list / straw2) | 桶(均匀桶 / 列表桶 / straw2 桶) |
| failure domain / placement rule | 故障域 / 放置规则 |
| marked down / marked out | 标记为宕机 / 标记为移出 |
| monitor (cluster) | 监视器(集群) |
| ack / commit | 确认 / 提交(落盘) |
| correlated failure / power outage | 相关故障 / 断电 |
| copyset / scatter width | 副本集 / 分散宽度 |
| peer-to-peer (P2P) / client-server | 对等网络 / 客户端-服务器 |
| central index / flooding | 中心索引 / 泛洪 |
| distributed hash table (DHT) | 分布式哈希表 |
| identifier circle / identifier space | 标识符环 / 标识符空间 |
| successor / predecessor | 后继 / 前驱 |
| finger table / finger | 指针表 / 指针 |
| iterative lookup / recursive lookup | 迭代查找 / 递归查找 |
| overlay network / overlay hop | 覆盖网络 / 覆盖网络跳 |
| join / stabilize / notify | 加入 / 稳定化 / 通知 |
| successor list | 后继列表 |
| churn / session time | 节点频繁加入离开(抖动) / 会话时长 |
| proximity neighbour selection | 邻近邻居选择 |
| XOR metric / k-bucket | 异或距离 / k 桶 |
| one-hop DHT | 单跳分布式哈希表 |
| Sybil attack / eclipse attack | 女巫攻击 / 日蚀攻击 |
| swarm / rarest first / tracker | 群(种子群) / 最稀有优先 / 追踪服务器 |
| aggregate upload capacity | 聚合上传容量 |
| availability / repair bandwidth | 可用性 / 修复带宽 |
| content delivery network (CDN) | 内容分发网络 |