Lecture 7 · Cache consistency and one-copy semantics: check-on-use, callbacks and leases

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

课程源码 ZIP ↓

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

本篇目录

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:

  1. 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).
  2. 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.
  3. 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.
  4. Choose a lease term with Gray and Cheriton’s model, and say where the model and the protocol differ.
  5. 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.
  6. 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

SectionIdeaDemo in code/lecture07/
§2what a reader can see; lost updates01_what_can_a_reader_see.py
§4the four protocols compared; the TTL knob02_four_protocols.py Parts A–C
§5choosing a lease term (Gray & Cheriton’s model + simulation)03_lease_term.py
§6partitions, reboots, clocks04_failures_and_clocks.py
§7false sharing; installed files05_false_sharing.py
§8the grant/recall race02_four_protocols.py Part D
allobject server + caching clients with four protocolsconsistency.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

  • NN clients; each reads at rate RR and writes at rate WW (per second). SS = 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). tt = lease term; tct_c = the part of it the client can use; ε\varepsilon = 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): open takes a private snapshot, reads and writes use it, and close publishes a modified snapshot (“last close wins”).
R’s reads (session 1, session 1, session 2)one-copy: interleavingssession: interleavings
(0, 0, 0)29260
(0, 0, A)45—
(0, 0, B)10169
(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)291

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 kk clients each run open, read n, write n + 1, close on a counter file:

clientssemanticsinterleavingsinterleavings that lose an update
2one-copy7051.43%
2session7097.14%
2session + exclusive open (a lock)20%
3one-copy34,65084.47%
3session34,65099.98%
3session + exclusive open60%
  • 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:

contracta read returns…example
one-copy (strict, single-copy)the latest committed writea local UNIX file; leases or synchronous callbacks
session (open–close)the version at open; others’ changes appear at the next open after they closeAFS
close-to-open + time boundas session, but metadata may be up to TT seconds oldNFS (attribute cache)
time-bounded staleness (TTL)a copy at most TT seconds oldDNS, HTTP max-age
immutable datathe only version there isa 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:

  1. Who notices a change? The client, by asking (check-on-use, TTL), or the server, by telling (callbacks, leases).
  2. When? On every use, after a timeout, or at the moment of the write.
  3. What does the server remember? Nothing (check-on-use, TTL), or a promise per (client, object): a callback or a lease.
  4. What happens to writes? They complete at once, or they wait until the other copies are known to be gone (synchronous callbacks, leases).
  5. 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 TT, use it; otherwise fetch again.
  • Write: just write.
  • Server state: none.
  • Staleness: up to TT, 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 tt.
  • 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 ww 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):

protocolw = 0.01/s0.1/s0.3/s1/s3/s
TTL 3 s0.520.550.691.011.51
check-on-use2.002.002.002.002.00
callbacks0.080.911.682.322.62
leases 10 s0.241.172.152.983.38

Fraction of reads that were stale:

protocol0.01/s0.1/s0.3/s1/s3/s
TTL 3 s0.0180.3030.5600.7470.793
check-on-use00000
callbacks0000.0020.004
leases 10 s00000

Mean read latency (ms):

protocol0.01/s0.1/s0.3/s1/s3/s
TTL 3 s0.510.420.300.060.01
check-on-use2.002.002.002.002.00
callbacks0.050.530.951.331.45
leases 10 s0.200.540.951.321.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):

TTLmessages per opstale readsread latency
0.1 s1.840.2%1.83 ms
1 s1.039.1%0.95 ms
3 s0.5530.3%0.42 ms
10 s0.2763.0%0.12 ms
30 s0.1977.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):

protocol2 clients5 clients20 clients
check-on-use2.00 msgs/op, 0 promises2.00, 02.00, 0
callbacks0.45, 2 promises1.05, 52.03, 20
leases 10 s0.55, 21.35, 52.68, 20
TTL 3 s0.58 msgs/op, 8.7% stale0.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 tst_s, the client can use only

tc=max⁡(0,  ts−(mprop+2 mproc)−ε),t_c = \max\big(0,\; t_s - (m_{prop} + 2\,m_{proc}) - \varepsilon\big),

because the grant takes time to arrive and the clocks are uncertain by ε\varepsilon. A client then makes one extension request (2 messages) per 1+R tc1 + R\,t_c reads. A write to a file shared by SS caches costs SS approval messages with multicast, or 2(S−1)2(S-1) with unicast. So the server handles

2NR1+R tc+N S Wconsistency messages per second,\frac{2NR}{1 + R\,t_c} + N\,S\,W \qquad \text{consistency messages per second,}

against 2NR2NR for a zero term (check on every read). A nonzero term reduces load only if the lease benefit factor α=2R/(SW)\alpha = 2R/(SW) exceeds 1 and tc>1/(R(α−1))t_c > 1/\big(R(\alpha - 1)\big).

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): RR = 0.864 reads/s, WW = 0.039 writes/s, mpropm_{prop} = 1 ms, mprocm_{proc} = 0.25 ms, ε\varepsilon = 100 ms. Demo 03 Part A evaluates the model:

sharing0 s1 s2 s5 s10 s20 s30 sinfinite
S = 11.0000.5630.3790.1910.1050.0550.0370.000
S = 101.0000.7890.6040.4170.3300.2810.2630.226
S = 201.0001.0140.8300.6430.5560.5060.4890.451
S = 401.0001.4661.2821.0941.0070.9580.9400.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, α=1.11\alpha = 1.11, 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):

network0 s1 s10 s30 s
LAN, 1 ms one way2.87 ms1.62 ms0.30 ms0.11 ms
WAN, 50 ms one way96.6 ms55.7 ms10.2 ms3.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 RR and WW:

clientstermsimulated relative loadmodel (unicast, measured S)
11 s0.5140.536
110 s0.0810.104
130 s0.0170.037
101 s0.7420.715
105 s0.5940.467
1010 s0.5770.394
1030 s0.5720.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:

protocolwrite latencyc1’s readsstalelongest readwrite seen by c1 after
TTL 5 s2 ms / 2 ms50435.0 s37.0 s / 10.0 s
check-on-use2 ms / 2 ms44038.0 s37.0 s / 10.0 s
callbacks (breaks in the background)2 ms / 2 ms120942 msnever / never
callbacks, wait up to 5 s for acks5.0 s / 2 ms120842 msnever / never
leases 2 s2 ms / 2 ms44038.0 s37.0 s / 10.0 s
leases 10 s7.0 s / 2 ms60030.0 s30.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:

protocolwrite latencystale readswrite seen after
check-on-use2 ms / 2 ms00.1 s / 0.2 s
callbacks, no probes2 ms / 2 ms74never / never
callbacks, probe every 5 s2 ms / 2 ms42.0 s / 0.0 s
leases 10 s8.0 s / 4 ms00.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 ε\varepsilon. 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 stale00
−5% (slow)200
−20% (slow)530
+20% (fast)000
  • 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:

granularitybreaksfetches of the unitreads from cachemessagesKB moved
one callback per file167168 (whole 64 KB file)2321,30337,355
one callback per block08 (the first fetch of each block)3928163,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 termrecalls sent to AB’s writes that waited
0 s, 1 s00 of 149
5 s, 30 s, 120 s1010 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 filesserver messages/sleases recorded
one per file, extended on demand571.420,000
one per directory, extended on demand19.4100
one per directory, extended by a periodic multicast from the server0.200

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:

  1. 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.
  2. Version the promise: the recall says “version ≤ 5 is revoked”, and the client ignores grants for revoked versions.
  3. 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

TTLcheck-on-usecallbacksleases
server statenonenonepromise per (client, object)promise per (client, object), expiring
cost grows with1 / TTLreadswrites × sharerswrites × sharers + 1 / term
read latency on a hit01 RTT always00 while the lease lasts
write latency1 RTT1 RTT1 RTT (async) or more1 RTT + approvals; up to a term if a holder is unreachable
stalenessup to TTLnonenone if breaks are synchronous; a small window if async; unbounded if a break is lostnone (with sane clocks)
unreachable holderreads stale until expiryholder cannot readholder stale indefinitelywrites wait ≤ term; holder cannot read after expiry
server rebootnothing to recovernothing to recoverpromises forgotten: clients must find outwait one term
best whenstaleness OK, scale matters (DNS, CDN)data changes between most uses; simplicityread-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

  1. 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.
  2. Crossover arithmetic. NN clients each read an object at rate rr and one writer writes it at rate ww. 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.

    AnswerCheck-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.
  3. 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.
  4. 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.
  5. Recovering a callback server. Compare three recovery strategies after an AFS-2-style server reboots: (a) clients probe every PP 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 TT. 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.
  6. Sessions by hand. Two clients each run open, write X, close (one writes “P”, the other “Q”); a third runs open, read, close after 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?

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

    AnswerYes. 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).
  8. 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?

    AnswerPer 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).
  • 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 semanticsUNIX 语义
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上帝视角检查
← 返回课程目录