Three replicas can each take a write at once and still agree later, with no waiting. A Tokyo click that waits 240 ms for a leader in Virginia answers in about 1 ms, if the merge rule is right.
Cut Tokyo off, add items in Tokyo and Frankfurt, heal the cut, then press Sync. Switch between the three rules on the same clicks. Then we build, piece by piece, the merge rules, the gossip that carries them, and the test for when you must wait after all.
You need a little Python and what a replica is. Consensus and Replication helps. We build the rest from zero.
Illustrative toy. The round trips (Virginia to Frankfurt 90 ms, Virginia to Tokyo 150 ms) are round numbers near public inter-region measurements. A local write is about 1 ms. Chapter 0 works the latency, Chapter 2 the merge.
Chapter 0
Measure what a coordinated write costs across oceans, and what a local write would save
A shopping cart lives on three replicas: Virginia, Frankfurt and Tokyo. A shopper in Tokyo presses "Add to cart". With one leader in Virginia, the write travels to Virginia, and the leader must hear from one more replica before it answers.
Each such wait is coordination: one node asks another "is this all right?" and waits. Inside one data centre that takes under a millisecond. Across an ocean it takes a large part of a second, and during a network cut it never ends.
Name the parts. Call the round trip from the shopper's region to the leader rL. A majority is q replicas, and the leader counts itself, so it waits for q − 1 followers. Call the round trip to the slowest of those followers rq−1.
T equals r-L plus r sub q minus one.
The write goes to the leader and the answer comes back: that costs r-L. In between, the leader sends the write to its followers. It waits until q minus 1 of them reply, so it waits for the slowest of its nearest q minus 1. Add the two waits to get T.
Take illustrative round trips: Tokyo to Virginia 150 ms, Virginia to Frankfurt 90 ms, and q = 2 of 3. Then T = 150 + 90 = 240 ms. A write that the Tokyo replica takes alone answers in about 1 ms, so the shopper waits about 240 times longer.
Yellow lines are round trips. Pick the leader and the shopper, compare the bars, then cut Tokyo off.
Illustrative round trips: Virginia to Frankfurt 90 ms, Virginia to Tokyo 150 ms, Frankfurt to Tokyo 230 ms. They are near public inter-region measurements. Your provider's numbers will differ.
The other road is coordination avoidance. Every replica takes the write at once and answers. The replicas swap their states later and merge them. This works only if the merge gives the same answer in any arrival order. This lesson builds such merges, the tools that carry them, and a test for when they cannot exist.
Coordination is still right for some jobs. A bank must not let two replicas each spend the last 100 dollars. Chapter 8 gives the test that tells the two kinds of job apart.
Failure. Symptom: shoppers far from the leader see a slow cart, and during a cut their writes fail. Measure: write latency per region, and the refused-write rate during a cut. Cause: every write waits for the leader and a majority. Fix: accept cart writes locally and merge them; keep coordination for the jobs that need it.
Chapter 1
Build a merge that ignores order, grouping and duplicates, and replicas that saw the same updates must agree
Replicas that act alone disagree for a while: Tokyo has the new item and Frankfurt does not. Eventual consistency promises only that the replicas end up the same once writes stop. It does not say how, or what a read returns in between.
Strong eventual consistency promises more: any two replicas that have received the same updates are in the same state, with no extra round of messages. Shapiro, Preguiça, Baquero and Zawirski defined it in 2011, with the types that give it: CRDTs, conflict-free replicated data types.
The trick is in the merge. Call three replica states a, b and c. Call the merge of two states "a join b", written a ⊔ b. It must obey three laws.
a join b equals b join a; a join b, then join c, equals a join the result of b join c; and a join a equals a.
Commutative: merging a into b or b into a gives the same state. Associative: merge a, b and c in any grouping and you get the same state. Idempotent: merging a with a copy of itself changes nothing.
With made-up updates 3, 7 and 5, and join = max: max(3, 7) = max(7, 3) = 7. Then max(max(3, 7), 5) = max(3, max(7, 5)) = 7. And max(7, 7) = 7. Every replica ends at 7, in any order and with any number of retries.
The network breaks each law in its own way. It reorders messages, so the merge must be commutative. Different paths group updates differently, so it must be associative. It retries, so it must be idempotent. A merge with all three laws is a join on a semilattice: a set of states where any two have a smallest state above both. Updates only move a state up.
Blue chips are updates in the order each replica got them; a pink ring marks a retry. The purple box is the state after merging them in. Choose a merge, then shuffle.
Illustrative toy with three made-up updates. Each replica starts at 0 and merges the updates in the order shown.
Failure. Symptom: two replicas that saw the same updates show different values. Measure: replay the same updates into the merge in two orders, and once with a duplicate. Cause: the merge breaks a law, as sum and "latest arrival" do. Fix: change the state so the merge is a join: max, set union, or a vector of those.
Chapter 2
Give each replica its own slot, merge slot by slot with max, and add the slots to read
Start with a like counter: any replica may add 1 at any time. One number per replica fails at once. Merge with max, and Tokyo's 2 and Frankfurt's 1 give 2, so a like is lost. Merge with sum, and the next sync counts the same likes again.
The G-Counter, a grow-only counter, keeps a vector with one slot per replica. Replica A adds only to slot A. Each slot has one writer, so it only grows, and the larger of two copies of a slot is the newer one. Call slot i in the local copy ai and in the copy that arrived bi.
v equals the sum over i of the max of a-i and b-i.
For each replica's slot, keep the larger of the two copies a-i and b-i. That is the merged vector. Add its slots to get v.
A has added 2 and B has added 1, at the same time. A holds (2, 0, 0) and B holds (0, 1, 0). Slot by slot: max(2, 0) = 2, max(0, 1) = 1, max(0, 0) = 0, so v = 2 + 1 + 0 = 3. Merging again still gives 3.
Each card is one replica; the purple bars are its slots for A, B and C. The grey line shows a one-number counter merged with max, for contrast. Add on any replica, then merge.
Illustrative. The device starts from the worked example: A has added 2 and B has added 1. A merge here is two-way: both replicas end with the joined state.
Note the split: the merge works on the vector, and the read adds it up. Every CRDT here has that shape. The state only grows, and you compute the value you show from it.
Shapiro's report names two costs. The vector has one slot per replica that ever wrote, so it grows with the replica count. And every replica must know the full list of replicas, because a new replica needs a slot.
Failure. Symptom: the like count drops after a sync, or jumps by a whole replica's count. Measure: log each replica's state before and after a merge. Cause: one number per replica, merged with max (loses likes) or with sum (counts them twice). Fix: a slot per replica, merged slot by slot with max.
Chapter 3
Record each decrement as growth in a second counter, and read the difference
A cart quantity goes down as well as up. A G-Counter cannot go down: lower a slot, and max at the next merge brings the old value back.
The PN-Counter keeps two G-Counters. P counts increments and N counts decrements, and both only grow. It is double-entry bookkeeping: you never erase a number, you add an entry to the second ledger. Call replica i's increment slot Pi and its decrement slot Ni.
v equals the sum over i of P-i, minus the sum over i of N-i.
Add every replica's increment slot P-i. Add every decrement slot N-i. Take the second total from the first. To merge, take max slot by slot in P, and again in N.
A adds 5, B removes 3 and C adds 2, all at once. After merging, P = (5, 0, 2) and N = (0, 3, 0). So v = (5 + 0 + 2) − (0 + 3 + 0) = 7 − 3 = 4.
Each card shows P (increments) on the top row and N (decrements) below, one slot per replica. Add and remove on different replicas, then merge all.
Illustrative. "Load the example" puts in the worked numbers: A adds 5, B removes 3, C adds 2, with no merge yet.
The value can go below zero. That is fine for a vote tally, and wrong for stock on a shelf. Shapiro's report gives the case: two replicas both see 1 item, and each sells it. Each is still at 0 alone, yet after the merge the count is −1.
No local check stops this. The rule "never below zero" is about all replicas together, and neither replica knows what the other sold. Chapter 8 names the test for such rules.
Failure. Symptom: stock reads −1 after a sync. Measure: compare P and N per replica for that item. Cause: two replicas sold the last unit at once, and a PN-Counter has no floor. Fix: give each replica its own share of the stock (escrow), or sell the last units through one coordinator.
Chapter 4
Pick one value by timestamp, and tag every add so a remove deletes only what it saw
A display name is one value. The LWW-Register, last writer wins, stores the value with a timestamp. A merge keeps the write with the larger timestamp, and breaks a tie with the replica id. That is a join, so it converges.
It converges by dropping a write, and clock skew picks which. Our fuzz test found a second trap: two writes from one replica with the same timestamp make the result depend on merge order. So timestamps must be unique per replica.
Sets are harder: A adds milk while B removes it. The OR-Set, observed-remove set, says the add wins. Each add makes a fresh unique tag. A remove deletes only the tags it has seen. For an element e, call every tag ever added Ae and every tag removed Re.
e is in S if and only if A-e minus R-e is not empty.
Collect every tag added for e. Strike out the tags that a remove saw. If any tag is left, e is in the set. To merge, take the union of the added tags and the union of the removed tags.
A adds milk with tag a1, and both replicas sync. A removes milk, so R-milk = {a1}. At the same time B adds milk again with tag b2. After the merge, A-milk = {a1, b2}, and A-milk minus R-milk = {b2}. One tag is left, so milk stays.
Left: the OR-Set, live tags purple, tombstones struck out. Right: a last-writer-wins set with the newest add and remove times. Move the skew: only the right side changes.
Illustrative. Each action happens 10 ms of real time after the one before. A's clock is exact; B's clock adds the skew. A tie in the last-writer-wins set goes to the remove.
The merge takes unions, so it is a join. A concurrent add makes a tag the remover never saw, and that tag survives. The price is tombstones, which pile up until the replicas agree to drop them.
Dynamo's shopping cart (DeCandia and others, 2007) merged diverged cart versions. The paper says an "add to cart" is never lost, but deleted items can resurface. An OR-Set keeps the promise without the flaw: a remove that saw the tag stays a remove.
Failure. Symptom: a renamed profile flips back to the old name after a sync. Measure: the timestamps and replica ids of both writes. Cause: last writer wins with a clock that runs ahead, so the earlier write carried the larger timestamp. Fix: hybrid logical clocks, or a multi-value register that keeps both values.
Chapter 5
Let each informed node tell one random node per round, and the news reaches N nodes in about log N rounds
Merges need states to travel. Sending each update to every replica costs N − 1 messages, and a sender that crashes halfway leaves some replicas out. Gossip, also called epidemic spreading (Demers and others, 1987), uses chance instead.
Each round, every node that has the update picks one other node at random and sends it. Early on, the informed group nearly doubles each round. Near the end, most calls reach nodes that already know, so the last few nodes take longer. Call the number of nodes N and the rounds until all of them have it r.
r is about log base two of N, plus the natural log of N.
First the informed group doubles each round, which takes log base two of N rounds. Then luck finds the last few nodes, which takes about ln N more. Pittel proved this sum in 1987 for this push rule on a network where any node can call any other.
For N = 1,000: log2 1,000 = 9.97 and ln 1,000 = 6.91, so r ≈ 16.9 rounds. Our 400 simulated runs averaged 18.0 rounds, from 15 to 26. Perfect doubling would take 10.
Purple dots know the update; blue dots learned it this round. The chart counts informed nodes per round, and the yellow line marks log2 N + ln N. Pick a size and play.
Illustrative simulation of push gossip on a network where any node can call any other. The average in the read-out comes from 200 fresh runs in your browser.
A CRDT makes gossip safe: messages arrive late, twice and out of order, and the merge laws absorb all three. Gossip makes CRDTs practical, because no node needs a list of who has what.
The cost is spread out. Each round, every informed node sends one message. So one update costs up to about N times r messages: about 17,000 for 1,000 nodes. Real systems batch many updates into each exchange.
Failure. Symptom: an update reaches most nodes fast, but a few lag far behind. Measure: rounds until the last node has it, against log2 N + ln N. Cause: in the last rounds most random calls reach nodes that already know. Fix: add pull, where uninformed nodes ask, and run anti-entropy (Chapter 6) as a safety net.
Chapter 6
Compare hash trees from the top down, so two replicas find a few differing keys in a handful of hashes
Gossip can still miss a write: a message is lost, or a replica was down for an hour. Anti-entropy repairs this. Two replicas compare all their data and swap what differs. Sending a million keys to find one changed key is wasteful.
A Merkle tree cuts the cost. Each leaf is the hash of one range of keys, and each parent is the hash of its two children. Two replicas compare roots first: equal roots mean equal data. If the roots differ, they compare the two children, and they go down only where hashes differ. Dynamo keeps one such tree for each key range a node holds. Call the number of leaves K.
h equals one plus two times log base two of K.
Compare the roots. At each level below, compare the two children of the node that differs, and follow the child that differs. There are log base two of K levels, at two hashes each.
K = 16: h = 1 + 2 × 4 = 9 hashes, where a scan checks 16. K = 1,048,576 (2 to the 20): h = 1 + 2 × 20 = 41 hashes instead of a million. Our script found the changed key with exactly these counts.
Each box is a hash. Green means both replicas agree on it, pink means they differ, grey means not compared. Set how many keys B changed, then compare.
Illustrative tree with 16 leaves, one key range each. The walk compares the root, then both children of every node that differs.
Each node that differs costs two more comparisons, one per child. One differing leaf has one differing node per level, so the cost grows with the depth, log2 K, not with K.
Several differing leaves share the top of their paths, so d of them cost at most 1 + 2 · d · log2 K. Two changed leaves out of 16 took 15 comparisons in our script, under the bound of 17. Many scattered changes push the walk towards a full scan.
Failure. Symptom: a repair run moves gigabytes although the replicas are nearly equal. Measure: hashes compared and bytes moved per repair. Cause: a full key scan, or leaves so large that one change resends a huge range. Fix: a Merkle tree with smaller leaves, so one change resends one small range.
Chapter 7
Stamp each message with a vector of counts, and hold any message whose cause has not arrived
Convergence says where replicas end, not what they show on the way. Alice asks the group chat "Pizza?" and Bob answers "Yes!". The network may bring Bob's answer to Carol first, so Carol sees a reply to nothing.
Causal delivery forbids that. If Bob saw message m1 before he sent m2, every replica must show m1 before m2. Messages that did not see each other are concurrent, and they may show in any order.
Each replica keeps a vector clock: for each sender, how many of that sender's messages it has delivered. A sender adds 1 to its own entry and stamps the vector on the message. Call the message's vector Vm, the receiving replica's vector Vi, the sender j, and any other sender k.
Deliver m when V-m of j equals V-i of j plus one, and V-m of k is at most V-i of k, for every k other than j.
Check the sender's entry: it must be exactly one more than you have delivered from that sender, so you skipped nothing from j. Check every other entry: you must already have delivered at least that many from each sender, so you have seen what j had seen. If both hold, deliver and set your entry for j to V-m of j. If not, hold the message.
Carol starts at (0, 0, 0) for Alice, Bob, Carol. Bob's "Yes!" arrives stamped (1, 1, 0). Bob's entry: 1 = 0 + 1, fine. Alice's entry: 1 is not at most 0, so Carol holds it. Alice's "Pizza?" (1, 0, 0) arrives and passes, so Carol moves to (1, 0, 0). Now "Yes!" passes both checks.
Time runs down. Blue arrows are messages; purple numbers are vectors; pink marks a held message. Step through, then turn causal delivery off.
Illustrative timing: Alice's link to Carol is slow, so m1 reaches Carol after m2. Vectors count delivered messages per sender, in the order Alice, Bob, Carol.
The first check means "the next message from j, none skipped". The second means "I have seen what j had seen". A held message waits in a buffer, which the replica checks again after each delivery. Vector clocks come from Fidge and from Mattern, both in 1988.
Failure. Symptom: a reply shows above its question, or a comment appears on a post that is not there yet. Measure: compare the two messages' vectors: if one is below the other in every entry, the order was causal. Cause: delivery in arrival order. Fix: hold messages until the rule holds; bound the buffer and alert on stuck messages.
Chapter 8
Test whether merging two valid states can break a rule, and coordinate only where it can
Counters, sets and chat run without coordination. A bank balance does not. The CALM theorem, consistency as logical monotonicity, draws the line. A program has a consistent, coordination-free implementation exactly when it is monotonic: more input never takes back an output it already gave.
Hellerstein stated CALM as a conjecture in 2010. Ameloot and colleagues proved a formal version, and Hellerstein and Alvaro surveyed it in 2019. The table sorts common operations.
| Operation | Monotonic? | Why |
|---|---|---|
| Union, filter, join | Yes | A new row only adds results. |
| "Count is at least 10" | Yes | Once true, more rows keep it true. |
| The final count | No | One late row changes the answer. |
| "No such row exists" | No | The row may still arrive. |
| Set difference A minus B | No | A new row in B removes a result. |
Bailis and others (2014) asked the same question for each application rule, and called it invariant confluence. Start two replicas from one valid state. Each runs operations that keep the rule true locally. If every merge of two such states also keeps the rule true, the operations need no coordination.
Pick an operation and its rule. Both replicas act from the same start and each passes its local check. Then the device checks the merge. For stock, turn on escrow.
Illustrative states. The merges are the CRDT merges of the earlier chapters: counters merge as PN-Counters, rows as a set union.
Run the test on stock with the rule "stock ≥ 0". Both replicas see 1, each sells one, and each is valid alone; the merge gives −1. So selling needs coordination. Likes pass. Usernames that users choose fail, but ids from per-replica ranges (A-1, B-1) pass. Escrow is the middle road: split 10 units as 6 for A and 4 for B, and each sells its share without asking.
The payoff can be large. Bailis and others found 10 of the 12 TPC-C invariants confluent, and reported a 25-fold improvement over earlier TPC-C New-Order results on 200 servers.
Failure. Symptom: oversold stock, or two accounts with one username, after a cut heals. Measure: run the merge test on the rule. Cause: a rule that is not confluent, guarded only by local checks. Fix: coordinate that one operation (consensus, a lock or escrow) and leave the rest local.
Chapter 9
Cut links, write on every replica, and gossip until the three states agree
Three replicas run three CRDTs side by side: a PN-Counter for the cart quantity, an OR-Set for the items, and an LWW-Register for the shopper's name. Each name write takes a timestamp one above any the replica has seen, so timestamps stay unique. Pick a replica, act on it, cut links, and gossip.
Pick the replica you act on, then press actions. Lines are links: a red dashed line is cut. Teal pulses are gossip exchanges. Gossip until the state says converged.
Illustrative. In each gossip round, every replica swaps full state with one random replica it still has a link to. The merges are exactly those of Chapters 2 to 4.
Things to try:
The worked number: from quantity 0, A adds 2 and B adds 1 during the cut. After healing, every replica reads P = (2, 1, 0) and N = (0, 0, 0), so the quantity is 2 + 1 = 3. No write waited, and none was lost.
Failure. Symptom: replicas stay different after many gossip rounds. Measure: check whether every replica has a path of live links to the others. Cause: a replica is cut off, so no exchange can reach it. Fix: heal the link; a few rounds after it heals, the replica catches up.
Chapter 10
Keep the numbers, the checklist and the code for the next time a write does not need to wait
A coordinated write waits for a leader and a majority; across oceans that costs hundreds of milliseconds, and a cut stops it. A CRDT takes the write locally and merges later with a join: commutative, associative and idempotent. Counters use slots and max, sets use tags, and registers use timestamps. Gossip and Merkle trees carry the states, vector clocks keep causes first, and the merge test says where you must still coordinate.
| Term | What it is | This lesson's number |
|---|---|---|
| Coordinated write | T = rL + rq−1 | Tokyo via Virginia: 150 + 90 = 240 ms; local about 1 ms |
| Join | commutative, associative, idempotent | updates 3, 7, 5: max gives 7 everywhere |
| G-Counter | v = Σ max(ai, bi) | (2, 0, 0) and (0, 1, 0): 3 |
| PN-Counter | v = Σ Pi − Σ Ni | +5, −3, +2: 4; last unit sold twice: −1 |
| OR-Set | e ∈ S ⇔ Ae ∖ Re ≠ ∅ | {a1, b2} minus {a1}: milk stays |
| Gossip | r ≈ log2 N + ln N | N 1,000: 16.9 predicted, 18.0 simulated |
| Merkle walk | h = 1 + 2 · log2 K | K 16: 9; K 220: 41 |
| Causal delivery | Vm[j] = Vi[j] + 1, Vm[k] ≤ Vi[k] | (1, 1, 0) held at (0, 0, 0) |
| Job | Use | Why |
|---|---|---|
| Likes, views, page hits | G-Counter | Only grows; any replica may add |
| Cart quantity, vote tally | PN-Counter | Up and down, no floor needed |
| Cart items, tags, flags | OR-Set | Concurrent add beats remove; no resurrection |
| Status, last-seen time | LWW-Register | Only the newest value matters |
| Stock with a floor | Escrow, or a coordinator for the last units | stock ≥ 0 is not confluent |
| Usernames, balances, ordered logs | Consensus (Raft) | Uniqueness and floors need agreement |
python# state-based CRDTs: every merge is a join (fuzzed for the three laws) def g_merge(a, b): # G-Counter: one slot per replica return {r: max(a.get(r, 0), b.get(r, 0)) for r in a.keys() | b.keys()} def pn_value(P, N): # PN-Counter: two G-Counters return sum(P.values()) - sum(N.values()) def lww_merge(x, y): # (value, timestamp, replica): unique per replica return x if (x[1], x[2]) >= (y[1], y[2]) else y def or_add(s, e, tag): return (s[0] | {(e, tag)}, s[1]) def or_remove(s, e): # delete only the tags this replica has seen return (s[0], s[1] | {p for p in s[0] if p[0] == e}) def or_merge(a, b): return (a[0] | b[0], a[1] | b[1]) def or_has(s, e): return any(p[0] == e and p not in s[1] for p in s[0]) def deliverable(Vm, j, Vi): # causal broadcast check return Vm[j] == Vi[j] + 1 and all(Vm[k] <= Vi[k] for k in range(len(Vm)) if k != j)
Now press Present or Teach and explain five things from memory. Explain the three merge laws, why a G-Counter needs a slot per replica, and how OR-Set tags make adds win. Explain why gossip takes about log2 N + ln N rounds, and why "stock ≥ 0" needs coordination. Then go back to the hero, cut Tokyo off, and try all three rules on the same clicks.