Maps to: CMU 15-440/640 Spring 2026, learning outcomes “data caching and one-copy semantics” and “cache consistency protocols and implementation trade-offs”. Readings (optional, course list):
- C. G. Gray and D. R. Cheriton, Leases: An Efficient Fault-Tolerant Mechanism for Distributed File Cache Consistency (SOSP 1989);
- J. H. Howard et al., Scale and Performance in a Distributed File System (ACM TOCS 1988), again.
Project: P2 must keep whole-file caches fresh with “one of the strategies covered in lecture (e.g., check on use, callbacks, etc.)” (handout) under open–close session semantics. This lecture explains the strategies; it does not design the proxy. Problem set: PS2 asks which strategy suits which scenario; the scenarios and numbers here are different. Sources: the readings above. Background:
- Lecture 5 (NFS, AFS);
- Tanenbaum & van Steen ch. 7 (consistency and replication);
- M. Burrows, The Chubby Lock Service for Loosely-Coupled Distributed Systems (OSDI 2006) — leases in a modern system;
- RFC 7530 (NFS v4: leases and delegations).
The slides are not public; this is not a transcript. Numbers from papers are labelled as such. Every other number comes from
code/lecture07/, run on the author’s machine (Apple M4 Pro, macOS, Python 3.13 and 3.9). Code:code/lecture07/. Reading time: ~85 minutes, plus ~15 to run the demos.
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- State one-copy semantics and session semantics precisely, and say what a reader can and cannot observe under each — including what neither of them protects (read-modify-write).
- Describe four ways to keep cached copies fresh — TTL, check-on-use, callbacks, leases — as message sequences, with the state each puts on the server.
- Predict each protocol’s cost (messages, read and write latency, staleness, server state) from the read rate, the write rate and the number of sharers. Find where one overtakes another.
- Choose a lease term with Gray and Cheriton’s model, and say where the model and the protocol differ.
- Explain what each protocol does when a client is partitioned, when the server reboots, and when a clock runs at the wrong rate, and why leases trade a bounded write delay for safety.
- Recognize false sharing (in space and in time), choose a consistency granularity, and spot races between grants and revocations.
0.2 Prerequisites and scope
- Prerequisites:
- Lecture 4 (timeouts, epochs, at-most-once);
- Lecture 5 (NFS’s TTLs and close-to-open checks; AFS’s check-on-open and callbacks; forgotten callbacks after a reboot);
- Lecture 6 (hit ratios, granularity).
- Scope: one server holding the master copy, many caching clients. Keeping several masters (replicas) consistent is Lectures 19–22. Transactions that group several reads and writes are Lectures 16–18. Clock synchronization is Supplement S1.
0.3 Section → code map
| Section | Idea | Demo in code/lecture07/ |
|---|---|---|
| §2 | what a reader can see; lost updates | 01_what_can_a_reader_see.py |
| §4 | the four protocols compared; the TTL knob | 02_four_protocols.py Parts A–C |
| §5 | choosing a lease term (Gray & Cheriton’s model + simulation) | 03_lease_term.py |
| §6 | partitions, reboots, clocks | 04_failures_and_clocks.py |
| §7 | false sharing; installed files | 05_false_sharing.py |
| §8 | the grant/recall race | 02_four_protocols.py Part D |
| all | object server + caching clients with four protocols | consistency.py (python3 consistency.py runs its self-test) |
consistency.py builds on Lecture 5. Its client is fsworld.FsClient (a generator program, RPCs with retransmission, server epochs, probes), plus answers to the server’s recalls and breaks. The server holds versioned objects and runs one protocol. Every read is checked by a god’s-eye rule:
A read is stale if it returned a version older than one whose write had already committed at the server when the read began.
A read that overlaps a write may return either version and is not counted.
0.4 Notation
- clients; each reads at rate and writes at rate (per second). = the number of caches holding a copy when a write happens (the sharers).
- RTT ≈ 2 ms in the simulations (0.8–1.2 ms each way). = lease term; = the part of it the client can use; = clock-uncertainty allowance.
- Writes are write-through at close: a client’s write replaces the whole object at the server. So all protocols here give session semantics at object granularity; they differ in how stale a read may be.
1. The problem
1.1 The intuition
You photocopy a document for five colleagues. Then you correct a typo in the original. Five copies are now wrong, and nobody holding one knows it.
There are only a few things you can do:
- tell everyone to check with you before relying on their copy (check-on-use);
- promise to phone them if anything changes (callbacks);
- write “valid until Friday” on each copy (a TTL);
- promise to phone them until Friday, and refuse to change the original before then without reaching them (a lease).
Lecture 6’s caches were safe because nobody changed the original. As soon as someone can, every cached copy is a potential lie. Cache consistency (or coherence) is the discipline of bounding that lie.
1.2 The ideal: one-copy semantics
Gray and Cheriton define consistency the way users want it (paraphrased): the system should behave exactly as if there were a single, uncached copy of the data — the cache changes only performance. This is one-copy semantics: a read returns the value of the most recent write, whoever made it, wherever they are. On one machine, UNIX gives it for free, because there is only one copy in the kernel’s buffer cache.
In a distributed system it costs at least one of these:
- every read asks the master copy (latency, server load);
- the master tells every copy holder before a write completes (server state, write latency, and a problem when a holder is unreachable);
- clocks: the master waits until every copy has certainly expired.
Every protocol in this lecture is a way to pay one of these bills, or a decision to accept some staleness instead.
2. What may a reader see? Semantics before protocols
A consistency semantics is a contract: it says which values a read may return. A protocol is a mechanism that implements a contract. Separate them, because the same protocol can implement different contracts, and arguments about “is it consistent?” are usually arguments about which contract is meant.
2.1 One-copy vs session semantics, exhaustively
Demo 01 takes a tiny scenario and enumerates every interleaving of its steps, each step atomic:
- a writer W does
open, write A, write B, close; - a reader R does
open, read, read, close, open, read, close; - the file starts as 0.
That gives 330 interleavings. It runs each under two semantics:
- one-copy: every write is instantly visible to every read;
- session (AFS, Lecture 5 §4.7):
opentakes a private snapshot, reads and writes use it, andclosepublishes a modified snapshot (“last close wins”).
| R’s reads (session 1, session 1, session 2) | one-copy: interleavings | session: interleavings |
|---|---|---|
| (0, 0, 0) | 29 | 260 |
| (0, 0, A) | 45 | — |
| (0, 0, B) | 101 | 69 |
| (0, A, A) | 9 | — |
| (0, A, B) | 36 | — |
| (0, B, B) | 18 | — |
| (A, A, A) | 9 | — |
| (A, A, B) | 36 | — |
| (A, B, B) | 18 | — |
| (B, B, B) | 29 | 1 |
What the table says:
- Under one-copy semantics a reader can see a half-finished update (A, which the writer meant only as a step toward B) in 153 of 330 interleavings. Its two reads within one open differed in 81 interleavings: the file changed under it.
- Under session semantics it never sees A, and two reads in one session never differ. Each session works on a snapshot, which is often what applications want: an editor or a compiler should not see half a file.
- The price is freshness. In 168 interleavings, R’s new open saw 0 although the writer had already written B — it had not yet closed, so its data was invisible. Session semantics returned (0, 0, 0) in 260 of 330 interleavings.
Neither semantics is “right”. One-copy is the stronger promise about recency; session semantics is a promise about isolation at open–close granularity. AFS chose session semantics because whole-file caching implements it almost for free (Lecture 5).
2.2 Neither protects read-modify-write
Part B of the demo has clients each run open, read n, write n + 1, close on a counter file:
| clients | semantics | interleavings | interleavings that lose an update |
|---|---|---|---|
| 2 | one-copy | 70 | 51.43% |
| 2 | session | 70 | 97.14% |
| 2 | session + exclusive open (a lock) | 2 | 0% |
| 3 | one-copy | 34,650 | 84.47% |
| 3 | session | 34,650 | 99.98% |
| 3 | session + exclusive open | 6 | 0% |
- One-copy semantics loses updates too. Two clients can both read 5 and both write 6. The semantics is about individual reads and writes, not about sequences of them.
- Session semantics loses them more often, because the whole session is the unit: whoever closes last overwrites the other (“last close wins”). With 3 clients the final value was as low as 1.
- Only excluding overlapping sessions — a whole-file lock from open to close — kept every increment.
These are counts of possible schedules, not probabilities: real timing is not uniform over interleavings. The point is that loss is possible in almost every overlapping schedule. Grouping several operations into an atomic unit is a transaction, the subject of Lectures 16–18. Cache consistency alone never provides it.
2.3 A spectrum of contracts
From strongest to weakest, the contracts met in practice:
| contract | a read returns… | example |
|---|---|---|
| one-copy (strict, single-copy) | the latest committed write | a local UNIX file; leases or synchronous callbacks |
| session (open–close) | the version at open; others’ changes appear at the next open after they close | AFS |
| close-to-open + time bound | as session, but metadata may be up to seconds old | NFS (attribute cache) |
| time-bounded staleness (TTL) | a copy at most seconds old | DNS, HTTP max-age |
| immutable data | the only version there is | a content-addressed file, a software release |
The last row is the cheapest consistency of all: data that never changes needs no protocol. “Change” becomes “create a new object with a new name”. AFS’s read-only volumes (Lecture 5) and Git’s content-addressed objects work this way, and many large systems are built so that most data is immutable.
3. The design space of consistency protocols
Every protocol answers five questions:
- Who notices a change? The client, by asking (check-on-use, TTL), or the server, by telling (callbacks, leases).
- When? On every use, after a timeout, or at the moment of the write.
- What does the server remember? Nothing (check-on-use, TTL), or a promise per (client, object): a callback or a lease.
- What happens to writes? They complete at once, or they wait until the other copies are known to be gone (synchronous callbacks, leases).
- At what granularity? Whole files, blocks or directories (§7).
There is also a write policy:
- Write-through: the write goes to the server now. The Model 85 (Lecture 6), NFS’s synchronous WRITE, and Gray and Cheriton’s leases work this way.
- Write-back (delayed write): the write goes later — at close, as in AFS, or after a delay. That saves traffic for temporary files, but a client crash then loses writes that others may already have been told about. Gray and Cheriton limit themselves to write-through because it gives clean failure semantics: no write that any client has seen can be lost.
4. The four protocols
4.1 How each one works
TTL (“faith-based”, time-to-live).
- Read: if the copy is younger than , use it; otherwise fetch again.
- Write: just write.
- Server state: none.
- Staleness: up to , with no guarantee in between.
- Examples: NFS’s attribute cache (3–60 s), DNS records, HTTP
Cache-Control: max-age.
Check-on-use (validate on every use).
- Read: send
VALIDATE(key, my version); the server replies “current” or sends the new copy. - Write: just write.
- Server state: none.
- Staleness: none in our definition; the read sees what the server had at that moment.
- Examples: the AFS prototype’s TestAuth; HTTP
If-Modified-Since.
Callbacks.
- Read: if the copy holds a callback, use it with no message. Otherwise fetch or validate; the server records the callback.
- Write: the server sends a BREAK to every other holder.
- Server state: one promise per (client, object).
- AFS-2 sends breaks without waiting for them to be delivered, so the write completes at once. Variants wait for acknowledgments.
Leases.
- Read: if the copy’s lease has not expired on the client’s clock, use it. Otherwise fetch or validate; the server grants a lease of term .
- Write: the server sends a RECALL to every other holder whose lease has not expired on the server’s clock. It waits until each has approved — dropping its copy — or until its lease expires. Meanwhile it grants no new leases on that object.
- Server state: one promise per (client, object), each with an expiry time. After a crash the server need not remember them: it waits one maximum term before allowing writes.
A lease is a callback with an expiry date. That one change is the subject of §6.
4.2 The measurements
Demo 02 Part A: 5 clients share one 1 KB object. Each reads once a second and writes times a second (Poisson). The run lasts 200 simulated seconds; the RTT is about 2 ms; TTL = 3 s; lease term 10 s.
Messages per operation (every message a client sends or receives, per read or write):
| protocol | w = 0.01/s | 0.1/s | 0.3/s | 1/s | 3/s |
|---|---|---|---|---|---|
| TTL 3 s | 0.52 | 0.55 | 0.69 | 1.01 | 1.51 |
| check-on-use | 2.00 | 2.00 | 2.00 | 2.00 | 2.00 |
| callbacks | 0.08 | 0.91 | 1.68 | 2.32 | 2.62 |
| leases 10 s | 0.24 | 1.17 | 2.15 | 2.98 | 3.38 |
Fraction of reads that were stale:
| protocol | 0.01/s | 0.1/s | 0.3/s | 1/s | 3/s |
|---|---|---|---|---|---|
| TTL 3 s | 0.018 | 0.303 | 0.560 | 0.747 | 0.793 |
| check-on-use | 0 | 0 | 0 | 0 | 0 |
| callbacks | 0 | 0 | 0 | 0.002 | 0.004 |
| leases 10 s | 0 | 0 | 0 | 0 | 0 |
Mean read latency (ms):
| protocol | 0.01/s | 0.1/s | 0.3/s | 1/s | 3/s |
|---|---|---|---|---|---|
| TTL 3 s | 0.51 | 0.42 | 0.30 | 0.06 | 0.01 |
| check-on-use | 2.00 | 2.00 | 2.00 | 2.00 | 2.00 |
| callbacks | 0.05 | 0.53 | 0.95 | 1.33 | 1.45 |
| leases 10 s | 0.20 | 0.54 | 0.95 | 1.32 | 1.48 |
Mean write latency: about 2 ms (one round trip) for everything except leases, about 3.7–4.1 ms. A leased write must first collect the other holders’ approvals: one more round trip.
4.3 Reading the numbers: one cost formula per protocol
- Check-on-use pays per read: exactly 2 messages and one RTT per read, at every write rate. It never returned stale data and keeps no state. Its cost is constant and predictable, which is why it is the simplest correct choice.
- Callbacks pay per write × sharers. When writes are rare they are nearly free: 0.08 messages per operation and 0.05 ms per read, because almost every read is a local hit. Every write breaks every other holder, and each of them re-fetches on its next read. So their cost rose with the write rate and overtook check-on-use at 1 write/s per client. The rule of thumb: callbacks win when objects are read much more often than they are written; check-on-use wins when they change between most uses.
- Asynchronous callbacks are not quite one-copy. A read that starts after a write has committed, but before the break arrives, uses the old copy: 0.2% of reads at 1 write/s. Making the write wait for the breaks’ acknowledgments closes that window. Callbacks then cost exactly what leases cost when nothing fails.
- Leases pay per write × sharers, plus a write delay: an extra round trip to collect approvals, and extensions every term. They never returned stale data. Writes that had to wait waited 2.0 ms on average — one round trip, not the 10 s term. The term matters only when a holder fails to answer (§6).
- TTL pays per TTL period, whether or not anything changed, and pays in staleness. At w = 0.01/s it needed 0.52 messages per operation where callbacks needed 0.08. At w = 0.1/s, 30% of its reads were stale. It is the cheapest protocol to implement (no server state, no server messages), not the cheapest to run.
The TTL knob (Part C; 5 clients, reads 1/s, writes 0.1/s each):
| TTL | messages per op | stale reads | read latency |
|---|---|---|---|
| 0.1 s | 1.84 | 0.2% | 1.83 ms |
| 1 s | 1.03 | 9.1% | 0.95 ms |
| 3 s | 0.55 | 30.3% | 0.42 ms |
| 10 s | 0.27 | 63.0% | 0.12 ms |
| 30 s | 0.19 | 77.6% | 0.02 ms |
A TTL bounds how old a copy can be, not whether it is current. It is right when some staleness is acceptable and the bound is what matters: DNS records, a web page’s images, NFS attributes.
More sharers (Part B; reads 1/s, writes 0.1/s each):
| protocol | 2 clients | 5 clients | 20 clients |
|---|---|---|---|
| check-on-use | 2.00 msgs/op, 0 promises | 2.00, 0 | 2.00, 0 |
| callbacks | 0.45, 2 promises | 1.05, 5 | 2.03, 20 |
| leases 10 s | 0.55, 2 | 1.35, 5 | 2.68, 20 |
| TTL 3 s | 0.58 msgs/op, 8.7% stale | 0.57, 34.7% | 0.57, 64.4% |
Callbacks degrade as sharing grows: more writers, and more holders to break per write. Check-on-use does not change. TTL’s staleness grows with the total write rate.
5. How long should a lease be?
5.1 The trade-off
A longer term means:
- more reads fall inside a lease, so fewer extension requests;
- but more writes find other holders still holding leases that must be recalled — false sharing in time, when a holder is not even using its copy (§7.2);
- and a longer wait whenever a holder is unreachable, and after a server reboot (§6).
Gray and Cheriton turned this into a model (paper, Section 3). For a lease of server term , the client can use only
because the grant takes time to arrive and the clocks are uncertain by . A client then makes one extension request (2 messages) per reads. A write to a file shared by caches costs approval messages with multicast, or with unicast. So the server handles
against for a zero term (check on every read). A nonzero term reduces load only if the lease benefit factor exceeds 1 and .
5.2 The model with the paper’s numbers
The paper measured the V system (MicroVAX II workstations, recompiling the V file server; paper’s Table 2): = 0.864 reads/s, = 0.039 writes/s, = 1 ms, = 0.25 ms, = 100 ms. Demo 03 Part A evaluates the model:
| sharing | 0 s | 1 s | 2 s | 5 s | 10 s | 20 s | 30 s | infinite |
|---|---|---|---|---|---|---|---|---|
| S = 1 | 1.000 | 0.563 | 0.379 | 0.191 | 0.105 | 0.055 | 0.037 | 0.000 |
| S = 10 | 1.000 | 0.789 | 0.604 | 0.417 | 0.330 | 0.281 | 0.263 | 0.226 |
| S = 20 | 1.000 | 1.014 | 0.830 | 0.643 | 0.556 | 0.506 | 0.489 | 0.451 |
| S = 40 | 1.000 | 1.466 | 1.282 | 1.094 | 1.007 | 0.958 | 0.940 | 0.903 |
(Server consistency load relative to a zero term.)
- Without sharing, a 10 s term cuts the consistency load to 0.105 of a zero term. The paper reports 10% for this case, and notes that most of the benefit comes from the first few seconds; longer terms buy little more.
- Sharing eats the benefit. At S = 40, , and any term whose usable part is below 10.7 s increases the load: approvals cost more than the extensions saved. The paper’s advice: give a heavily write-shared file a zero term. The server can choose terms per file, and even per client.
Delay added to each operation (Part B; S = 1):
| network | 0 s | 1 s | 10 s | 30 s |
|---|---|---|---|---|
| LAN, 1 ms one way | 2.87 ms | 1.62 ms | 0.30 ms | 0.11 ms |
| WAN, 50 ms one way | 96.6 ms | 55.7 ms | 10.2 ms | 3.6 ms |
On a 100 ms round trip a 10 s term still costs about 10 ms per operation on average. Longer networks favour somewhat longer terms; the paper reaches the same conclusion with its own response-time measure. The delay formula is our reconstruction of the paper’s formula (2), which is partly illegible in the scanned copy. It is used here only for this comparison.
5.3 The model vs the protocol
Demo 03 Part C simulates the actual lease protocol with the same and :
| clients | term | simulated relative load | model (unicast, measured S) |
|---|---|---|---|
| 1 | 1 s | 0.514 | 0.536 |
| 1 | 10 s | 0.081 | 0.104 |
| 1 | 30 s | 0.017 | 0.037 |
| 10 | 1 s | 0.742 | 0.715 |
| 10 | 5 s | 0.594 | 0.467 |
| 10 | 10 s | 0.577 | 0.394 |
| 10 | 30 s | 0.572 | 0.329 |
The shape agrees, and the two differences are instructive:
- With one client, the protocol beats the model (0.081 vs 0.104 at 10 s). In the protocol a write’s reply also renews the writer’s lease, which the formula leaves out. With writes switched off the two agree: 0.102 vs 0.104.
- With ten clients, the protocol loses to the model (0.577 vs 0.394). The model counts extensions only when leases expire, but every write also recalls the other holders’ leases. The nine other clients write about once every 2.8 s, so terms beyond about 5 s bought almost nothing (0.594 at 5 s, 0.572 at 30 s): writes, not the term, end the leases.
A model is a lens. Its value is in what it makes you check, and a simulation of the real protocol is how you check it.
6. When things fail: partitions, reboots and clocks
The protocols differ most when something breaks. Demo 04 scripts the failures: a reader c1 reads one object every 500 ms; a writer c0 writes it at fixed times.
6.1 A partitioned holder
c1 is cut off from the server at t = 12 s and healed at 50 s; c0 writes at 13 s and 40 s:
| protocol | write latency | c1’s reads | stale | longest read | write seen by c1 after |
|---|---|---|---|---|---|
| TTL 5 s | 2 ms / 2 ms | 50 | 4 | 35.0 s | 37.0 s / 10.0 s |
| check-on-use | 2 ms / 2 ms | 44 | 0 | 38.0 s | 37.0 s / 10.0 s |
| callbacks (breaks in the background) | 2 ms / 2 ms | 120 | 94 | 2 ms | never / never |
| callbacks, wait up to 5 s for acks | 5.0 s / 2 ms | 120 | 84 | 2 ms | never / never |
| leases 2 s | 2 ms / 2 ms | 44 | 0 | 38.0 s | 37.0 s / 10.0 s |
| leases 10 s | 7.0 s / 2 ms | 60 | 0 | 30.0 s | 30.0 s / 10.0 s |
This is the fundamental choice, in miniature:
- Callbacks keep the cut-off client available and make it wrong. The break never arrived, so c1 kept reading its old copy: 94 stale reads, and it never saw either write, even after the network healed. Waiting for the break’s acknowledgment only delayed the writer by 5 s and did not help the reader at all.
- Leases keep it right and make it unavailable. The first write waited 7 s, until c1’s unreachable lease expired on the server’s clock, and then committed safely. c1, unable to renew, could not complete a read until the network healed. A 2 s lease had already lapsed when the write came, so the write did not wait at all.
- Check-on-use is also never stale and never delays writes; c1 simply cannot read during the partition.
- TTL serves stale reads until the copy expires (4 here), then cannot read either. Its staleness is bounded by the TTL, whatever the network does.
Under a partition a cache must choose between answering (possibly wrongly) and refusing (safely). That choice reappears, generalized, as the CAP trade-off in the replication lectures. The lease term is the knob: it bounds both how long writes wait for an unreachable holder and how long a holder may serve without contact.
Real AFS does not leave the callback client stale forever. A server that cannot deliver a break remembers that the client missed it, and the client must revalidate its cache when it next makes contact (Kazar 1988 describes AFS’s callback recovery). The mechanism exists precisely because of the failure this experiment shows. It still leaves a window: everything the client reads before it contacts the server.
6.2 A server reboot
The server crashes at t = 20 s and restarts at 21 s; c0 writes at 23 s and 40 s:
| protocol | write latency | stale reads | write seen after |
|---|---|---|---|
| check-on-use | 2 ms / 2 ms | 0 | 0.1 s / 0.2 s |
| callbacks, no probes | 2 ms / 2 ms | 74 | never / never |
| callbacks, probe every 5 s | 2 ms / 2 ms | 4 | 2.0 s / 0.0 s |
| leases 10 s | 8.0 s / 4 ms | 0 | 0.0 s / 0.0 s |
- Callbacks live in the server’s memory, so the reboot forgot c1’s callback. The write sent no break, and c1 was stale 74 times. This is Lecture 5’s demo 04 again. Probing for the server’s epoch bounds the damage by the probe interval.
- Leases need no memory of what was granted. The rebooted server simply refuses writes for one maximum term, the longest any lease it granted before the crash could still be valid. The first write after the reboot waited 8 s, and nothing was stale. The alternative — writing every lease to disk — costs a disk write per grant to speed up the rare crash. Gray and Cheriton argue it is rarely worth it unless terms are much longer than recovery.
6.3 Clocks
Leases trade the server’s memory for an assumption about clocks. The server decides expiry on its clock and the client on its own, so they must agree to within . More precisely, both clocks must run at nearly the right rate over one term. Their absolute values need not agree, because the client counts the term from when it sent its request, and the server granted it later.
Demo 04 Part C: 10 s leases; c1 is cut off at t = 5 s; c0 writes at 6 s, and the server lets the write through when c1’s lease expires on the server’s clock (4 s later).
| c1’s clock rate error | ε = 0 | ε = 1 s | ε = 3 s |
|---|---|---|---|
| 0% | 0 stale | 0 | 0 |
| −5% (slow) | 2 | 0 | 0 |
| −20% (slow) | 5 | 3 | 0 |
| +20% (fast) | 0 | 0 | 0 |
- A slow client clock makes the client believe its lease is still valid after the server has let a write through, so it reads stale data.
- A fast client clock is harmless: the client only renews early. Symmetrically, a fast server clock is dangerous and a slow one harmless.
- The rule: the allowance must cover the term times the worst rate error. Here 10 s × 20% = 2 s, so ε = 1 s is not enough and 3 s is.
Real quartz clocks drift by around 10⁻⁵ to 10⁻⁴ (tens of parts per million). For a 10 s term that is about a millisecond, so leases are safe with a tiny ε, as long as clocks fail only in that way. A clock that jumps — a virtual machine paused for a minute, a misconfigured time daemon — breaks the assumption. Gray and Cheriton list clock failures among the “Byzantine” failures leases do not tolerate.
6.4 Leases everywhere
The pattern “a promise with an expiry date” solves a problem that recurs throughout distributed systems: the holder of a right may vanish, and the system must not wait forever.
- Orphans (Lecture 4): a server stops work on behalf of a client whose lease has lapsed.
- Locks: Google’s Chubby grants locks and cache entries with leases; a crashed holder’s lock frees itself.
- NFS v4 grants clients leases on their open state and delegations (callbacks) on files, recovered after a server reboot by a grace period — the “wait one term” of this lecture.
- Primaries in replicated storage: GFS’s master gives one replica a lease to order writes (Lecture 25). Leader leases in Paxos-based systems let a leader serve reads locally (Lectures 20–21).
7. Granularity and false sharing
7.1 False sharing in space
A promise covers a unit: a file, a block, a directory. When two clients use different parts of the same unit, every write by one revokes the other’s promise, although they never touch the same bytes. This is false sharing, the consistency counterpart of Lecture 6’s block-size trade-off.
Demo 05 Part A: client A edits blocks 0–3 and client B blocks 4–7 of one 64 KB file, 200 edits each:
| granularity | breaks | fetches of the unit | reads from cache | messages | KB moved |
|---|---|---|---|---|---|
| one callback per file | 167 | 168 (whole 64 KB file) | 232 | 1,303 | 37,355 |
| one callback per block | 0 | 8 (the first fetch of each block) | 392 | 816 | 3,424 |
Per-file callbacks moved 11× more data, all of it caused by conflicts that were not real. Finer promises cost state: up to 8 promises for this one file instead of 2. Whole-file AFS accepted false sharing because users rarely write-share files. Databases and parallel programs, which do, use record or page granularity.
7.2 False sharing in time
A holder that read a file once and is not using it still holds a valid lease. Another client’s write must then ask its permission. Gray and Cheriton call this false sharing too, and it argues for short terms. Demo 05 Part B: A reads a file every 30 s; B writes it every 2 s, 1.5 s after each of A’s reads:
| lease term | recalls sent to A | B’s writes that waited |
|---|---|---|
| 0 s, 1 s | 0 | 0 of 149 |
| 5 s, 30 s, 120 s | 10 | 10 of 149 |
With a 1 s term, A’s lease had lapsed before B’s next write. With 5 s or longer, each of A’s reads left a lease that B’s next write had to recall: one round trip of delay, one load on A. With many idle holders this multiplies. Short leases let unused promises lapse before anyone has to ask.
7.3 Installed files: one lease for many
The opposite case is files read by everyone and almost never written: commands, libraries, headers. Gray and Cheriton note that in their V trace such installed files accounted for almost half of all reads and no writes. Per-file leases are wasteful for them. Demo 05 Part C is a model: 100 clients, 200 installed files, each read once a minute per client, 10 s leases.
| leases on installed files | server messages/s | leases recorded |
|---|---|---|
| one per file, extended on demand | 571.4 | 20,000 |
| one per directory, extended on demand | 19.4 | 100 |
| one per directory, extended by a periodic multicast from the server | 0.20 | 0 |
With a multicast extension the server keeps no per-client state for installed files. To update one, it stops extending the lease and waits one term: no implosion of approval replies from thousands of clients, and no need to know who they are. AFS reached a similar end differently, with read-only replicated volumes that need no callbacks at all (Lecture 5 §6.3).
8. Races: the bug the simulator found
The first version of consistency.py returned stale data under leases: 1.3% of reads at 1 write/s. That should be impossible. Tracing one stale read found this sequence:
client server
READ(k) ------------------->
grants a lease on version 5; reply leaves
<------------- WRITE(k) arrives from another client
RECALL(k) leaves (to our client)
RECALL(k) arrives FIRST (the network delayed the reply more than the recall)
"I hold no lease on k" -> APPROVE --->
all holders approved -> commit version 6
reply arrives: lease on v5 -> installed!
... reads version 5 from cache for 10 s: STALE
The protocol was right on paper and wrong on a network that reorders messages. Each one-way delay was drawn independently from 0.8–1.2 ms, so a later message can overtake an earlier one. AFS’s cache manager faces the same race: a callback break can arrive while the fetch that establishes the callback is still in flight.
Three standard fixes:
- Remember revocations that arrive while a request is in flight, and then keep the data but not the promise. This is the fix in
CacheDesign(guard_races). Demo 02 Part D: without it, 13 of 996 lease reads were stale; with it, 0. The guard acted only 3 times, but each late 10 s grant had poisoned several reads. - Version the promise: the recall says “version ≤ 5 is revoked”, and the client ignores grants for revoked versions.
- Use a FIFO channel per client (one TCP connection) so that a reply and a later recall cannot be reordered. This works only while every message travels on that one channel.
The lesson generalizes. Consistency protocols are concurrent programs whose “threads” are messages, and their bugs live in interleavings, exactly like Lecture 1’s two replicas and this lecture’s §2. That is why these notes simulate with an adversarial network: an ordinary test on a LAN would almost never reorder those two messages.
9. Choosing a protocol: a summary table
| TTL | check-on-use | callbacks | leases | |
|---|---|---|---|---|
| server state | none | none | promise per (client, object) | promise per (client, object), expiring |
| cost grows with | 1 / TTL | reads | writes × sharers | writes × sharers + 1 / term |
| read latency on a hit | 0 | 1 RTT always | 0 | 0 while the lease lasts |
| write latency | 1 RTT | 1 RTT | 1 RTT (async) or more | 1 RTT + approvals; up to a term if a holder is unreachable |
| staleness | up to TTL | none | none if breaks are synchronous; a small window if async; unbounded if a break is lost | none (with sane clocks) |
| unreachable holder | reads stale until expiry | holder cannot read | holder stale indefinitely | writes wait ≤ term; holder cannot read after expiry |
| server reboot | nothing to recover | nothing to recover | promises forgotten: clients must find out | wait one term |
| best when | staleness OK, scale matters (DNS, CDN) | data changes between most uses; simplicity | read-mostly, write-rarely, reliable network (AFS) | read-mostly and failures matter (V, Chubby, NFS v4) |
Real systems mix them:
- AFS used callbacks for user files and read-only volumes for system files.
- NFS combines close-to-open checks with attribute TTLs.
- HTTP combines TTLs (
max-age) with check-on-use (If-None-Match). - NFS v4 adds delegations (callbacks) bounded by leases.
Summary
- Semantics before protocols.
- One-copy semantics promises recency: a reader saw a half-done update in 153 of 330 interleavings.
- Session semantics promises snapshot isolation per open: never a half-done update, but new opens missed unclosed writes in 168.
- Neither protects read-modify-write: a counter lost updates in 51–85% (one-copy) and 97–99.98% (session) of interleavings, and 0% only with exclusive sessions (a lock). Transactions are Lectures 16–18.
- Immutable data needs no protocol at all.
- Four protocols, four cost formulas (5 clients, 1 read/s each):
- Check-on-use: 2 messages and 1 RTT per read, never stale, no state.
- Callbacks: nearly free when writes are rare (0.08 messages per operation), but overtook check-on-use at 1 write/s; a small staleness window if breaks are asynchronous (0.2%).
- Leases: never stale; writes wait one extra round trip (~2 ms), not the term.
- TTL: pays per TTL period and in staleness (30% at w = 0.1/s with 3 s).
- Lease terms (Gray & Cheriton):
- without sharing, 10 s gives 0.105 of the zero-term load (the paper reports 10%); sharing can make leases worse than none (S = 40 below ~10.7 s);
- the simulation agreed in shape, but write replies renew leases (one client: 0.081 vs 0.104), and recalls end leases before they expire (ten clients plateau at ~0.57).
- Failures decide the choice:
- a partitioned callback holder stays available and wrong (94 stale reads, writes never seen); a leaseholder stays right and becomes unavailable, and the write waited 7 s, bounded by the term;
- after a reboot, callbacks are forgotten (74 stale reads) while leases just wait one term (8 s, 0 stale);
- leases need clocks with bounded rate error: ε must exceed term × drift (a 20% slow clock needed ε > 2 s).
- Granularity: per-file callbacks on two editors of different halves cost 167 breaks and 11× the bytes (false sharing in space). Long terms make idle holders delay writes (false sharing in time). One multicast-extended lease per directory makes installed files nearly free (0.2 vs 571 messages/s).
- Races: a grant and a recall crossing in the network made leases return stale data (13 of 996 reads) until the client learned to distrust grants that cross a revocation. Simulate protocols against a reordering network.
Common pitfalls
- Calling a TTL “consistency”: it bounds staleness and nothing else, and its hit ratio and staleness both depend on load.
- Assuming one-copy semantics makes read-modify-write safe. It does not; you need locks or transactions.
- Sending callbacks asynchronously and claiming one-copy semantics. There is a window between the write and the break’s arrival, and an unbounded one if the break is lost.
- Forgetting that promises live in memory. A rebooted callback server must make every client revalidate, or wait out every lease.
- Long leases on write-shared data: approvals and idle holders can make leases more expensive than checking every read.
- Trusting clocks you have not bounded. Leases fail silently when a clock runs slow, pauses, or jumps.
- Treating “nothing failed in my tests” as correctness. Grant/revocation races need message reordering, which a LAN rarely produces.
- Choosing granularity without looking at the sharing pattern: whole-file promises on write-shared files cause false sharing; per-block promises on read-only files waste state.
Exercises
-
Pick and justify. For each workload, choose among TTL, check-on-use, callbacks and leases, and say what you give up: (a) a cluster’s configuration file, read by 2,000 servers every second and changed once a week, where a stale read for a few seconds is harmless; (b) the same file, but a stale read causes a misrouted payment; (c) a live sports score, rewritten every second and read by 10 clients a few times a minute; (d) a laptop on unreliable Wi-Fi editing its owner’s own documents.
Answer
(a) TTL of a few seconds: no server state for 2,000 clients and a known staleness bound. Callbacks would hold 2,000 promises for a file that almost never changes, which is cheap but brings break storms and reboot risk for little gain. (b) Leases, with a short term, or check-on-use if the server can absorb 2,000 validations/s. Staleness is now unacceptable, and leases bound the write delay when some of the 2,000 holders are unreachable; callbacks cannot guarantee freshness when a break is lost. (c) Check-on-use, or no cache at all: the value changes between almost every read, so callbacks would break every holder every second for copies nobody reads, and leases add approvals on top. (d) Callbacks or leases with whole-file caching and session semantics — AFS's model, and Coda's (Lecture 22). Few others write those files, so false sharing is rare and the cache keeps the laptop working through outages. With leases the laptop must accept that it cannot *prove* freshness while disconnected. -
Crossover arithmetic. clients each read an object at rate and one writer writes it at rate . Check-on-use costs 2 messages per read. With callbacks, a read is free while the callback holds; after each write, every reader that reads again pays 1 break + 2 messages to re-fetch. Assuming every reader reads at least once between writes, write the message rates of both and find the crossover.
Answer
Check-on-use: 2Nr messages/s. Callbacks: per write, N breaks plus N re-fetches of 2 messages each, so 3Nw messages/s (plus the writes themselves, the same in both). Callbacks are cheaper while 3Nw < 2Nr, i.e. w < 2r/3. If readers read *less* often than writes happen, the assumption fails: a reader without a callback is not broken again, so callbacks cost about 3 messages per *read* — slightly worse than check-on-use's 2. That is the regime where demo 02 found check-on-use cheaper. -
Is a lease worth it? A file is read 2 times/s by each of its holders and written 0.5 times/s, and at each write 6 caches hold it. (a) Compute the lease benefit factor α (multicast approvals). (b) What is the minimum usable term for leases to reduce load? (c) With unicast approvals?
Answer
(a) α = 2R/(SW) = 2 × 2 / (6 × 0.5) = 1.33. (b) t_c > 1/(R(α − 1)) = 1/(2 × 0.33) = 1.5 s. Shorter usable terms *increase* the server's load compared with checking on every read. (c) With unicast, each write costs 2(S − 1) = 10 messages instead of S = 6, so the effective α is 2R/(2(S − 1)W) = 4/5 = 0.8 < 1, and no term reduces the load. Make it a zero-term file. -
Clock allowance. A lock service grants 60 s leases. Its clients’ clocks are disciplined by NTP to within 100 parts per million in rate. (a) What ε is needed? (b) A client runs in a virtual machine that can be paused for up to 30 s without its clock noticing. What happens, and what ε would be needed?
Answer
(a) 60 s × 10⁻⁴ = 6 ms. Any ε above that, say 100 ms, is safe and nearly free. (b) A pause is a clock that stops. The client may resume believing it has seconds of lease left while 30 s have passed in real time and the server has given the lock to someone else: two holders at once. Covering it would need ε ≥ 30 s, half the term. Real systems instead make the protected resource check a **fencing token**, a lease or lock version number that rejects requests from an old holder (Lecture 20). The general lesson: leases protect against slow and crashed clients, not against clocks that lie. -
Recovering a callback server. Compare three recovery strategies after an AFS-2-style server reboots: (a) clients probe every seconds and revalidate everything on seeing a new epoch; (b) the server logs every callback grant to disk before replying; (c) convert callbacks to leases of term . For each, give the staleness bound after a reboot and the cost in normal operation.
Answer
(a) Staleness up to P seconds after the reboot, for clients that do not contact the server sooner. Normal cost: one probe per client every P seconds, plus a revalidation storm at each reboot. (b) No staleness, since the server remembers and can still break. Normal cost: a synchronous disk write per fetch, on the critical path of every cache miss — expensive. (c) No staleness, given sane clocks. Normal cost: extensions every T seconds for files in use, plus approval round trips. After the reboot, writes wait up to T. Gray and Cheriton recommend (c) with short terms. -
Sessions by hand. Two clients each run
open, write X, close(one writes “P”, the other “Q”); a third runsopen, read, closeafter both have closed. Under session semantics, which values can the reader see, and what decides it? Under one-copy semantics, does anything change? How would an application that must keep both writes have to be written?Answer
Under session semantics the reader sees whichever client **closed last**, P or Q: last close wins, and the other write is lost without any error. Under one-copy semantics it sees whichever **write step** happened last; again one write is lost. Neither semantics merges. To keep both, the application must avoid whole-file overwrites: use exclusive opens or locks, append-only records with unique ids, separate files per writer, or a server-side operation such as "append P" that the server applies atomically. -
The race, generalized. In §8’s race, replace leases by asynchronous callbacks. Does the same reordering cause staleness? Which of the three fixes works if the client talks to two servers (for two different files)?
Answer
Yes. If a BREAK for k overtakes the fetch reply that establishes the callback, the client discards a callback it does not yet hold, then installs the late one and trusts it until the next break, which may never come. The in-flight guard and versioned promises work per object and per server, so they work with two servers. A FIFO channel works only per server-client connection: it orders the reply and the break from the same server, which is all this race needs. It cannot order messages from two different servers, so it would not help any protocol that needs cross-server ordering (Supplement S1). -
Granularity for a database file. A 1 GB database file is accessed by 50 clients, each reading and updating random 4 KB records; each record is touched by about one client per hour. Compare consistency promises per file, per 64 KB chunk and per record: what dominates the cost in each case?
Answer
Per file: every update anywhere revokes all 49 other clients' promises on the whole file, so false sharing dominates, along with whole-file re-fetches (impossible at 1 GB anyway). Per 64 KB chunk: 16 records share a chunk, so an update revokes only the holders of that one chunk out of 16,384. False sharing remains among the 16 records of a chunk, and the state is up to 50 × 16,384 promises. Per record: no false sharing, but up to 50 × 262,144 promises; state and per-record bookkeeping dominate. Real databases choose page-level caching with record-level locking, or skip client caching and use transactions at the server (Lectures 16–18).
Related project and problem set (concepts only)
- Project 2 requires open–close session semantics on whole files, a freshness protocol of your choice (“check on use, callbacks, etc.”), and correct behaviour under concurrent clients. §2 explains what session semantics promises. §4 compares the strategies, §6 says what each must do when something fails, and §8 warns about races between fetches and revocations. The protocol between your proxy and server, and how a client sees a stable version while it has a file open, are your design.
- Problem Set 2 asks which strategy suits which scenario, with traffic arithmetic, and what readers see under session semantics. §4.3’s cost formulas and §2’s enumerations are the method. The answers, and PS2’s scenarios, are not here.
Further reading
- C. G. Gray and D. R. Cheriton, “Leases: An Efficient Fault-Tolerant Mechanism for Distributed File Cache Consistency”, SOSP 1989 (course reading).
- J. H. Howard et al., “Scale and Performance in a Distributed File System”, ACM TOCS 6(1), 1988 (course reading) — §3.1 (callbacks) and the consistency semantics.
- M. L. Kazar, “Synchronization and Caching Issues in the Andrew File System”, USENIX Winter 1988 — callback races and recovery in the real AFS.
- M. Burrows, “The Chubby Lock Service for Loosely-Coupled Distributed Systems”, OSDI 2006 — leases, cache invalidation and grace periods at Google.
- B. Pawlowski et al., “The NFS Version 4 Protocol”, SANE 2000, and RFC 7530 — leases, delegations, grace periods.
- A. S. Tanenbaum and M. van Steen, Distributed Systems, 3rd ed., ch. 7 — consistency models and protocols.
- M. Kleppmann, “How to Do Distributed Locking” (2016, blog) — leases, paused processes and fencing tokens.
Preview of Lecture 8 — Cache replacement
This lecture decided whether a cached copy is still good. The next decides which copy to throw away when the cache is full. LRU fell off a cliff on loops and was polluted by scans in Lecture 6. Lecture 8 measures every policy against Belady’s optimal MIN (which knows the future): FIFO, LRU, CLOCK and LFU, then ARC, which adapts between recency and frequency, and S3-FIFO, whose lazy promotion and quick demotion beat LRU with less work. It also covers what changes when cached objects have different sizes, as in Project 2.
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| cache consistency / cache coherence | 缓存一致性 |
| one-copy semantics (single-copy) | 单副本语义 |
| UNIX semantics | UNIX 语义 |
| session (open–close) semantics | 会话(打开-关闭)语义 |
| last close wins | 最后关闭者获胜 |
| snapshot isolation | 快照隔离 |
| consistency semantics / contract | 一致性语义 / 契约 |
| stale read / staleness | 过期读 / 陈旧度 |
| freshness | 新鲜度 |
| read-modify-write | 读-改-写 |
| lost update | 丢失更新 |
| exclusive open / whole-file lock | 独占打开 / 整文件锁 |
| immutable data | 不可变数据 |
| content-addressed | 按内容寻址 |
| time-to-live (TTL) / faith-based caching | 生存时间 / 信任式缓存 |
| check-on-use (validate on use) | 使用时检查 |
| callback / callback break | 回调 / 回调撤销 |
| synchronous / asynchronous break | 同步 / 异步撤销 |
| lease / lease term | 租约 / 租期 |
| lease extension / renewal | 租约续期 |
| recall / approval | 召回 / 批准 |
| leaseholder | 租约持有者 |
| lease benefit factor | 租约收益因子 |
| sharers (degree of sharing) | 共享者(共享度) |
| write-through / write-back (delayed write) | 写直达 / 写回(延迟写) |
| server state / soft state | 服务器状态 / 软状态 |
| grace period | 宽限期 |
| delegation (NFS v4) | 委托 |
| clock drift / clock rate error | 时钟漂移 / 时钟速率误差 |
| clock-uncertainty allowance (ε) | 时钟不确定性余量 |
| fencing token | 隔离令牌 |
| partition / partitioned client | 网络分区 / 被分区的客户端 |
| availability vs consistency | 可用性与一致性 |
| false sharing (in space / in time) | 伪共享(空间上 / 时间上) |
| granularity of consistency | 一致性粒度 |
| installed files | 已安装文件(系统文件) |
| multicast extension | 组播续期 |
| message reordering | 消息乱序 |
| race condition | 竞态条件 |
| FIFO channel | 先进先出信道 |
| versioned promise | 带版本的承诺 |
| god’s-eye check | 上帝视角检查 |