Goal

After this module you can say what a retry may do to replicated state, why timestamps and tombstones let replicas converge, prove that read and write quorums intersect exactly when , and give the execution that shows quorum reads and writes are still not linearizable.

Modules 1 and 2 were about messages: in which order a node may deliver them, and how to build each order. From here on the messages carry updates to data, and the question becomes: if several nodes hold copies of the same data, how do the copies stay the same while clients keep reading and writing?

Two problems appear even before we talk about ordering. First, a client that does not hear back cannot tell whether its update was lost or only the acknowledgement was, so it retries, and a retry may apply the update twice. Second, the copies drift apart when some messages reach one replica and not another. This module solves both with one idea that the lecturer called the general recipe of the field: add metadata (request identifiers, timestamps, tombstones, version vectors) so that a replica can tell an old update from a new one.

The second half is about how many replicas to talk to. Writing to every replica and reading from any one is correct but stops writes as soon as one replica is down. Quorums replace “all” by “enough”, and the condition is the arithmetic that makes “enough” safe. We end with the limit of the method: quorums give read-after-write, not linearizability, and the stronger guarantee needs either an extra write-back phase or, for read-modify-write operations, consensus (Module 4).

Lectures 05.01 (replication, retries, idempotence, tombstones), 05.02 (concurrent writes, probability of faults) and 05.03 (read-after-write consistency, quorums, read repair). Kleppmann’s notes, Sections 5.1 and 5.2 (slides 87-100), and Section 7.2 (slides 132-134) for linearizability (1).

Why replicate, and why updates are the hard part

Why keep several copies of the same data at all? The lecture (05.01) gives two reasons. Performance: one server handles some fixed number of requests per second, and more traffic needs more machines. Availability: if the one machine holding the data is down, the data is gone for as long as it is down, so we keep copies on machines that fail independently.

Definition 3.1 (Replica).

A replica is a node that stores a copy of some data item. Replication is the maintenance of copies of the same data on replicas. The goal is that clients may read from or write to some replicas and still observe the data as if there were one copy.

If the data never changes, replication is a one-time copy and there is nothing to study. All the difficulty comes from updates. Suppose on three replicas and a client updates it to . Until all three replicas have applied the update, a client that reads from a replica still holding sees a stale value. The lecturer gave the trivially correct solution: stop all reads and writes, update the replicas one by one, then resume. It is correct and nobody uses it, because nothing can be read or written during an update. Every technique in this module trades some consistency for the ability to keep serving requests while an update spreads.

Retries and idempotence

The lost acknowledgement

Before there are even two replicas, a single remote server already shows the first problem. The example of lecture 05.01 and Kleppmann’s slide 88: a post has 12,300 likes. A client sends “increment the like count”. The server applies it (12,301) and acknowledges, but the acknowledgement is lost. The client sees a timeout, cannot distinguish “request lost” from “reply lost”, and retries. The server increments again: 12,302, although one user liked the post once.

client server (likes) increment likes 12,301 ack lost timeout retry: increment likes 12,302 liked twice ack
Figure 3.1. A lost acknowledgement turns one like into two: the retried increment is applied a second time (lecture 05.01, Kleppmann slide 88).

Kleppmann’s slide 89 shows the same bug in production: a Twitter profile following a negative number of accounts, most likely an “unfollow” decrement that was retried. Replace “like” by “debit 1,000 from an account” and the problem is no longer cosmetic.

Definition 3.2 (Retry semantics).

For a request sent by a client to a server, we distinguish three guarantees about how many times its effect is applied.

  • At-most-once: send once, never retry. The effect is applied 0 or 1 times; a lost request is silently lost.
  • At-least-once: retry until an acknowledgement arrives. If the client does not crash and the network is fair-loss, the effect is applied 1 or more times.
  • Exactly-once: the effect is applied as if exactly once. It is built from at-least-once retries plus either idempotent requests or deduplication by request identifier.

At-most-once is the easiest to implement and the lecturer noted that real systems are not built on it. At-least-once is the natural choice with an unreliable network, and it is safe exactly when applying a request twice does no harm. That property has a name.

Definition 3.3 (Idempotent function).

A function on a set of states is idempotent if for every . By induction, then for every : applying it any positive number of times has the effect of applying it once.

Example 3.4 (Which updates are idempotent).
  • (increment a counter) is not idempotent: .
  • (add user to the set of likers) is idempotent, since . Kleppmann’s fix for the like counter: store the set of likers and derive the count as its cardinality.
  • (blind assignment, “set to 5”) is idempotent.
  • The conditional update of lecture 05.01, “if the count is 12,300, set it to 12,301”, is idempotent. In general let if and otherwise, with . If then because ; if then . This is a compare-and-set, and it turns a non-idempotent increment into an idempotent request.

Exactly-once by deduplication

When an operation cannot be made idempotent (a bank transfer), the server makes it idempotent from the outside: each request carries a unique identifier, and the server remembers which identifiers it has already applied.

// Server: exactly-once effect for at-least-once clients.
// done is kept in stable storage (it must survive a crash).
done := {}                          // map requestId -> reply
 
on receive Request(id, op) from c:
    if id in done:
        send done[id] to c          // duplicate: replay the old reply
    else:
        atomically:                 // apply and record in one step
            reply := apply(op)
            done[id] := reply
        send reply to c
 
// Client: retry with the SAME id until a reply arrives.
on call(op):
    id := (myClientId, nextSeq); nextSeq := nextSeq + 1
    repeat: send Request(id, op) to server; wait with timeout
    until a reply for id arrives
  • The identifier is chosen once per logical request, so every retry carries the same id.
  • atomically is the line that matters: if the server could crash after apply but before recording id, the retry after recovery would apply the operation again.
  • done must be in stable storage in the crash-recovery model (Kleppmann 5.1). Garbage-collecting old entries is a separate problem (for example, the client acknowledges replies it has received).
Proposition 3.5 (Deduplication gives exactly-once).

Assume fair-loss links, a client that does not crash, and a server that eventually stays up and keeps done in stable storage with the atomic apply-and-record step above. Then for every request identifier , the operation is applied exactly once and the client eventually receives the reply of that single application.

Appendix A shows the same mechanism inside RPC libraries and Raft’s client table, and why running over TCP does not make it unnecessary.

Idempotent is not enough when requests interleave

Idempotence makes one request safe to retry. It says nothing about a retry that arrives after another request has run. Lecture 05.01 and Kleppmann’s slide 91: client 1 adds a like () and the acknowledgement is lost. Client 2 reads the likes, sees client 1’s like, and removes it (, an “unlike” that happens causally after ). Then client 1’s retry of arrives and adds the like back. Client 2’s removal is undone, although it was the causally last operation.

Proposition 3.6 (Idempotent updates can still combine badly).

Let and on sets . Both and are idempotent, yet for every . So a retried idempotent request that arrives after a later request can change the outcome.

Exam trap: idempotent means safe to retry

“The operation is idempotent, so retries are harmless” is only true if nothing else touches the same data between the original and the retry. The precise statement is about a single function, ; it does not give . The fix is not more idempotence but more metadata: the retry must carry the timestamp of the original request so that a replica can see it is older than (next section).

Timestamps, tombstones and anti-entropy

Two histories, one state

With two replicas there is a second problem (Kleppmann slide 92). History 1: a client adds to replicas A and B, then removes ; the removal reaches A but is lost on the way to B, and the client crashes before retrying. History 2: a client adds to A and B; the request to A is lost and the client crashes. Both histories end with and . In history 1 the client wanted gone, in history 2 present. When A and B compare notes, they cannot know which state to adopt, because the states carry no information about how they arose.

The lecturer’s remedy, and his general remark: most distributed systems problems are solved by adding metadata. Here we add two pieces.

Definition 3.7 (Timestamped records and tombstones).

Each replica stores, for every key , a record : the timestamp of the last write to , a flag (alive or deleted) and the value . Timestamps are Lamport timestamps with ties broken by node id, so any two distinct writes have distinct, totally ordered timestamps.

  • A write issued with timestamp is the record .
  • A delete issued with timestamp does not erase the key. It writes the record , called a tombstone.
  • A replica that receives a record for keeps it only if its timestamp is larger than the stored .

With this metadata the two histories of slide 92 differ: in history 1, A holds the tombstone and B holds with , so the delete is newer; in history 2, B holds and A holds nothing for , so the add is the only information. Kleppmann’s slide 93 draws the first case.

Anti-entropy

Entropy here means disorder among replicas; an anti-entropy process removes it. Replicas periodically exchange their records and each keeps, per key, the record with the larger timestamp (Kleppmann slide 94). The epidemic-protocol literature studies how fast such exchanges spread an update (2).

Proposition 3.8 (Timestamp merge converges).

For a fixed key, define the merge of two records by the one with the larger timestamp (a missing record counts as timestamp ). Then is commutative, associative and idempotent. Consequently, if two replicas have each received (directly, through anti-entropy, or through retries, in any order and with any repetitions) the same set of records for a key, they hold the same record, namely the one in with the largest timestamp.

Timestamps also repair the like/unlike example. A retry carries the timestamp of the original request. Client 2 read client 1’s like before unliking, so with Lamport clocks its unlike has a timestamp . When the retry arrives, the replica holds the tombstone with and discards the older record. The late retry no longer resurrects the like (Kleppmann 5.1).

Metadata is not free

The lecturer stressed the other side of the recipe. Every timestamp and tombstone costs storage and network, and, more importantly, complexity: many production bugs come from two pieces of metadata that disagree. Tombstones in particular cannot be deleted until every replica has seen them. If replica A garbage-collects the tombstone for while replica B still holds the older live record , the next anti-entropy round copies back to A and the deleted item reappears.

Concurrent writes: last writer wins or keep both

What if two clients write the same key at the same time, in the happens-before sense of Module 1: ? Replica A may receive then , replica B the other way round (Kleppmann slide 95). If each replica simply applied writes in arrival order, they would disagree forever. Lecture 05.02 and Kleppmann give two ways out, which differ in the kind of timestamp.

Definition 3.9 (Last-writer-wins and multi-value registers).
  • A last-writer-wins (LWW) register tags each write with a totally ordered timestamp, usually a Lamport timestamp , and keeps only the write with the largest timestamp. Concurrent writes are ordered arbitrarily, and the “loser” is discarded.
  • A multi-value register tags each write with a version vector (one counter per client or replica, compared like vector clocks). A replica stores a set of siblings, writes with pairwise concurrent vectors. A write with vector removes every sibling whose vector is and is added unless it is itself some stored sibling. A read returns all siblings, and the application merges them.

LWW is what Proposition 3.8 analyses: replicas converge, but one of two concurrent writes is silently lost. Kleppmann’s slide puts it bluntly: “data loss”. Whether that is acceptable depends on the application. The multi-value register loses nothing but needs bigger timestamps (one entry per writer) and pushes conflict resolution to someone.

Proposition 3.10 (Multi-value merge converges).

For a finite set of (vector, value) pairs, let be the pairs of whose vector is not strictly below the vector of another pair in . Define , and call an antichain if . Then is commutative and associative, , and is idempotent on antichains: when . Every replica state is an antichain: this holds initially () and is preserved because always returns a set of the form . So replicas that have received the same writes hold the same siblings, regardless of order and repetition.

The lecture’s example of keeping both values is the Amazon shopping cart. If you add items from two browser windows at once, Amazon keeps both: throwing away something a customer wanted to buy costs revenue, so the extra metadata pays for itself. The conflict resolution is pushed to the user (“you have two carts, here is the union”). A student asked in 05.03 whether that works for a bank balance; the answer was no: a user resolving a conflict between two balances would pick the larger one. There the provider resolves conflicts, or concurrent writes are prevented altogether, which is where total order and consensus come in.

LWW registerMulti-value register
timestampLamport , total orderversion vector, partial order
concurrent writeslarger timestamp winsall kept as siblings
costsmall metadata, silent data lossone counter per writer, merge logic
typical usecaches, last-known positionshopping cart, collaborative data

How likely are faults?

Is replication only about performance? No: it changes the arithmetic of failure, in both directions (lecture 05.02, Kleppmann slide 96). Assume each replica is faulty (crashed or unreachable) at a given moment with probability , independently of the others.

Proposition 3.11 (Fault probabilities for n replicas).

Under the independence assumption, with replicas,

With (the lecture’s 1%):

replicas at least one faultymajority faultyall faulty
10.010.010.01
30.03
50.049
1000.63

Read the table by columns. The last two columns fall very fast: a system that keeps working while a minority is down is far more reliable than any single machine. The first column grows: with 100 replicas, some replica is down 63% of the time, and the lecturer’s “Google scale” of 10,000 machines gives , which is 1 to forty decimal places. So replication without fault tolerance makes things worse, and at scale a failed node is the normal state, not an event. The lecture’s conclusion: recovery must be automatic. A system that needs a human to replace a machine before it can continue does not scale, and in post-mortems humans are a frequent cause of the second failure.

Independence is an approximation

Equations and assume independent faults. Real faults are correlated: a power or network outage takes out a rack, a bad configuration push reaches every replica, and lecture 05.02 described cascading failures, where the failure of one service overloads the next until it fails too. The tiny numbers in the table are therefore lower bounds on the real risk, and cascading failures remain hard to test for.

Read-after-write consistency and quorums

The guarantee users expect

Definition 3.12 (Read-after-write consistency).

A replicated store provides read-after-write (read-your-writes) consistency if, after a client’s write of value to key completes, every later read of by that client returns or a value written later.

“Or a value written later” is needed because another client may overwrite in between. The lecture’s example (05.03): you add an item to your Amazon cart, close the tab, open the cart on your phone, and expect the item to be there.

With two replicas and no care, it is not (Kleppmann slide 97): the write of succeeds at B and fails at A; the read succeeds at A and fails at B, and returns the old . Two simple fixes both fail on availability. Writing to both replicas blocks writes when one replica is down; reading from both blocks reads. The lecture mentions sticky sessions (route a client always to the same replica), which works only while that replica is up and the client can be identified. The general fix is to read and write enough replicas.

Quorums and the intersection lemma

Definition 3.13 (Read and write quorums).

Fix replicas. A write is successful once distinct replicas have acknowledged it; the set of these replicas is the write quorum. A read is successful once distinct replicas have responded; the set is the read quorum, and the read returns the response with the largest timestamp. A majority quorum is any set of at least replicas.

Lemma 3.14 (Quorum intersection).

Let be a set of replicas and .

  1. If , then every with and every with satisfy .
  2. Conversely, if , there exist with , and .
Corollary 3.15 (Majority quorums intersect).

Any two majority quorums of the same replicas have at least one replica in common.

The lecture’s picture (05.03, Kleppmann slide 99) uses , , : a read from and a write to meet in .

Try it: start with , and check that every read quorum meets every write quorum. Then lower to 2 and look for a read quorum and a write quorum with no replica in common; one exists exactly when .

read quorum R, r = 3 write quorum W, w = 3 A B C D E overlap = 3 + 3 - 5 = 1 replica (C)
Figure 3.2. Read and write quorums for five replicas with three replicas each: they must share at least one replica, here C, which saw the write and answers the read.

Quorum reads see completed writes

The lemma is about sets. To turn it into a statement about reads and writes we need the replica rule of Definition 3.7, namely that a replica never replaces a record by one with a smaller timestamp. Here is the client side, with read repair (explained below) included.

// Quorum client, n replicas, r + w > n. Timestamps: Lamport + client id.
on set(x, v):
    t := newTimestamp()
    send Write(x, t, v) to all replicas
    wait for Ack(x, t) from w distinct replicas
    return ok
 
on get(x):
    send Read(x) to all replicas
    wait for responses (t_i, v_i) from r distinct replicas   // set R
    (t*, v*) := the response with the largest timestamp
    for each replica i in R with t_i < t*:                    // read repair
        send Write(x, t*, v*) to i            // original timestamp t*
    return v*
 
// Replica
on receive Write(x, t, v) from c:
    if t > store[x].t: store[x] := (t, v)     // never go back in time
    send Ack(x, t) to c
on receive Read(x) from c:
    send store[x] to c                        // the pair (t, v)
  • newTimestamp() returns a timestamp larger than any the client has seen, so a client’s later write has a larger timestamp than its earlier one.
  • The replica’s if t > store[x].t is the monotonicity that the next theorem uses. An equal timestamp (a retry) changes nothing but is still acknowledged.
  • Read repair resends the old timestamp : it is a retry of a past write, not a new write.
Theorem 3.16 (Quorum reads return the latest completed write).

Assume and replicas follow the rule above. Suppose with timestamp has completed (received acknowledgements) before starts. Then the get returns a value whose timestamp is at least . In particular the store provides read-after-write consistency (Definition 3.12).

Choosing r and w

A read needs live replicas, a write needs . So reads tolerate unavailable replicas and writes tolerate (Kleppmann slide 99). For , every choice with :

reads survivewrites survivetypical use
(1, 5)4 replicas down0 downread-heavy, rare writes
(2, 4)3 down1 downread-heavy
(3, 3)2 down2 downmajority quorums, balanced
(5, 1)0 down4 downwrite-heavy, rare reads

The lecture adds the performance side: larger makes reads slower (wait for more replies, so the slowest of ), larger makes writes slower. Since in most services reads outnumber writes by about ten to one, read-optimised settings like are common.

Lecture correction: w = n and availability

Lecture 05.03 says that gives “very strong availability guarantees”, since replicas can fail and the data is still there. That is a statement about durability of data already written: a write that reached all replicas survives crashes. For write availability it is the worst choice: with a single unavailable replica blocks every write (the table’s “0 down”). Keep the two notions apart in an exam answer.

A student asked in 05.03 why a read does not take a majority vote on the value, as in the Byzantine generals problem. The answer: voting returns the most common value, not the newest. If a write with timestamp has so far reached only one replica of the read quorum, a vote discards it while the timestamp rule keeps it. Theorem 3.16 needs the maximum timestamp, not the majority value.

Read repair and anti-entropy

Quorums leave some replicas behind: after a write to , the replicas outside still hold the old value. Two mechanisms bring them up to date.

Definition 3.17 (Read repair).

Read repair: when a read collects responses with different timestamps, the reader sends the newest record , with its original timestamp, to the replicas that returned older records (and possibly to those that did not answer). Anti-entropy: a background process in which replicas compare their records and copy newer ones to each other, independently of client requests.

Kleppmann’s slide 100: the client reads from A and from B, gets nothing from C, and sends to A (and to C, in case). Any client may repair, not only the one that wrote. By Proposition 3.8, sending a record a replica already has is harmless, which is why “possibly to those that did not answer” is safe.

The lecturer’s trade-off: read repair fixes inconsistencies quickly, exactly where data is being read, but the client does more work and the read takes longer if it waits for the repair. Anti-entropy costs nothing on the request path but may leave rarely read keys stale for a long time. Systems in the style of Amazon’s Dynamo, which popularised this design, use both; the idea of weighted voting with read and write quorums is older (3). Appendix B lists the production systems built this way and what they add.

Quorums alone are not linearizable

Read-after-write is about one client reading its own writes. A stronger guarantee is that the replicated store behaves like one copy for everyone, in real time.

Definition 3.18 (Linearizability, informally).

A replicated register is linearizable if every operation appears to take effect atomically at some instant between its start and its completion, and every read returns the value of the last write before its instant (4). A consequence: if a read completes before a read starts, then returns a value no older than the value returned.

Proposition 3.19 (Quorum reads and writes are not linearizable).

The quorum protocol above with , , and read repair that does not wait for acknowledgements, has an execution violating linearizability: one read returns the new value , and a read that starts after it has completed returns the old value .

client 1 client 2 client 3 set(x, v1) get: A, B -> v1 get: B, C -> v0 replica A replica B replica C holds v1 holds v0 holds v0 real time; dots mark when v1 arrives
Figure 3.3. Quorum reads and writes without a write-back phase are not linearizable: client 2 reads the new value from A, then client 3 reads the old value from B and C, which the delayed write has not reached yet (Kleppmann slides 132-133).
Remark 3.20 (The ABD fix and its limit).

The ABD algorithm of Attiya, Bar-Noy and Dolev (5) makes quorum reads and writes linearizable by making the read repair synchronous: a get returns only after the newest value it saw is stored on a quorum (a write-back phase). Then whenever an operation completes, its value sits on a quorum, and by Lemma 3.14 every later quorum read sees it. With several writers, a set first reads a quorum to learn the largest timestamp and picks a larger one (Kleppmann 7.2, pp. 72-73).

ABD handles reads and blind writes. It does not give a linearizable compare-and-set or increment: two clients can both read the old value from overlapping quorums and both decide to write. Such read-modify-write operations need all replicas to agree on one order of operations, which is consensus (Module 4).

Worked example: five replicas, a slow write and a repair

Setting: replicas A, B, C, D, E, quorums , Lamport timestamps written . Initially every replica holds with value “empty cart”.

  1. Write. Client P adds a book: with timestamp . The messages reach C, D, E, which store and acknowledge. The messages to A and B are lost. P has acknowledgements: the write is complete. State: A, B hold ; C, D, E hold .
  2. Read by another client. Client Q reads from (D and E are slow). Responses: , , . By Lemma 3.14 the overlap with is nonempty (here , size ). Q returns “book”, as Theorem 3.16 promises.
  3. Read repair. Q sends to A and B. Both have timestamp 0 < (1, P), so both store it. Now all five replicas agree.
  4. A late retry. P’s original message to A was lost; suppose P retries it now. A already holds ; the rule t > store[x].t fails, so nothing changes, and A acknowledges. The retry was harmless because it carried the original timestamp (Proposition 3.8).
  5. A concurrent pair. Clients P and Q now write concurrently: P writes “book, pen” with and Q writes “book, mug” with . With LWW and the tie broken by client id (), every replica that sees both keeps : “book, mug”. The pen is lost. With a multi-value register the two writes have incomparable version vectors, both survive as siblings, and the cart shows “book, pen, mug” after the application merges them (the Amazon choice).
  6. A read that could fail. If we had chosen , (so ), the read after step 1 could use , disjoint from as in part 2 of the lemma, and return the empty cart: read-after-write violated.

What breaks

  • Correlated faults break the probability table: three replicas in one rack fail together far more often than .
  • Clock and timestamp mistakes break LWW. If timestamps are physical clocks (as in some production databases) a node with a fast clock wins every conflict, and a causally later write can lose to an earlier one.
  • Tombstone garbage collection too early resurrects deleted data through anti-entropy.
  • Crash between apply and record breaks deduplication unless the two steps are atomic in stable storage.
  • Linearizability and read-modify-write are beyond plain quorums (Proposition 3.19).
  • Network partitions keep quorums safe but not available: a side with fewer than replicas cannot write at all. Systems that lower (or accept writes on any reachable replicas) to stay writable get conflicting writes on the two sides, which LWW later resolves by discarding one.

Why it matters

Every later module reuses two ideas from here. The quorum intersection lemma is the core of every consensus safety proof: Raft’s “one leader per term” (Module 5) and the fact that a new Paxos proposer learns a chosen value (Module 8) are both “two majorities share a witness”. And the monotone, timestamp-ordered replica state is the ancestor of terms and ballots. What quorums cannot give, a single agreed order of all operations, is exactly what Module 4 asks for and the rest of the notes build.

Further reading

  • Kleppmann’s notes, Sections 5.1-5.2 and 7.2 (1).
  • Gifford’s weighted voting, the origin of read and write quorums (3).
  • Epidemic algorithms for anti-entropy (2).
  • Linearizability, the formal definition (4), and the ABD algorithm (5).

Homework

The problems for this module are in Homework 3.

1.
Kleppmann M. Distributed Systems: Lecture Notes [Internet]. University of Cambridge, Computer Science Tripos Part IB; 2021. Available from: https://www.cl.cam.ac.uk/teaching/2122/ConcDisSys/dist-sys-notes.pdf
2.
Demers A, Greene D, Hauser C, Irish W, Larson J, Shenker S, et al. Epidemic Algorithms for Replicated Database Maintenance. In: Proceedings of the 6th ACM Symposium on Principles of Distributed Computing (PODC). 1987. p. 1–12.
3.
Gifford DK. Weighted Voting for Replicated Data. ACM SIGOPS Operating Systems Review. 1979;13(5):150–62.
4.
Herlihy MP, Wing JM. Linearizability: A Correctness Condition for Concurrent Objects. ACM Transactions on Programming Languages and Systems. 1990;12(3):463–92.
5.
Attiya H, Bar-Noy A, Dolev D. Sharing Memory Robustly in Message-Passing Systems. Journal of the ACM. 1995;42(1):124–42.