Coordination Avoidance

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.

Keep the cart through a cut

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

The Cost of Waiting

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.

Say it aloud

T equals r-L plus r sub q minus one.

T
T the time the shopper waits for one coordinated write, in milliseconds.
rL
r-L the round trip from the shopper's region to the leader. It is 0 if the shopper sits next to the leader.
rq−1
r sub q minus one the leader's round trip to its follower that is q minus 1 places down the list, sorted nearest first. With three replicas, q is 2, so this is the nearest follower.
In plain words

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.

With numbers

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.

Price one write

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.

  1. Merge laws: order, grouping and duplicates must not change the result.
  2. G-Counter: one slot per replica, merged with max.
  3. PN-Counter: a second counter for every decrement.
  4. Registers and sets: last writer wins, and tags that make adds win.
  5. Gossip: random calls reach N nodes in about log N rounds.
  6. Anti-entropy: Merkle trees find what differs in a few hashes.
  7. Causal order: vector clocks hold a reply until its question arrives.
  8. CALM: the test for when you must coordinate after all.
  9. Showcase: three replicas, three CRDTs, cuts and gossip.
  10. The field guide: numbers, checklist, code and links.
The leader is in Virginia and a majority is 2 of 3. Round trips: Tokyo to Virginia 150 ms, Virginia to Frankfurt 90 ms, Tokyo to Frankfurt 230 ms. How long does a write from Tokyo take?

Chapter 1

Three Laws of Merging

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.

Say it aloud

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.

a
a the state of one replica, for example its counter.
b
b the state of a second replica.
c
c the state of a third replica.
⊔
join the merge: it takes two states and returns one.
( )
first merge these two brackets fix which merge happens first.
In plain words

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 numbers

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.

Break a merge law

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.

A merge is commutative and associative but not idempotent. The network delivers one update twice to replica A. What happens?

Chapter 2

A Counter That Only Grows

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.

Say it aloud

v equals the sum over i of the max of a-i and b-i.

v
v the counter's value after the merge.
Σi
the sum over i add one term for each replica i.
max
the max of the larger of two numbers.
ai
a-i slot i in the local copy: how many times replica i added 1, as far as this copy knows.
bi
b-i slot i in the copy that just arrived.
In plain words

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.

With numbers

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.

Merge three G-Counters

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.

Five replicas each add 10 to their own slot. No merges have happened yet. What does each replica read?

Chapter 3

Counting Down Without Erasing

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.

Say it aloud

v equals the sum over i of P-i, minus the sum over i of N-i.

v
v the counter's value: here, the cart quantity.
Σi
the sum over i add one term for each replica i.
Pi
P-i how many increments replica i has made.
−
minus take the second total from the first.
Ni
N-i how many decrements replica i has made.
In plain words

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.

With numbers

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.

Count up and down

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.

A adds 5, B removes 3 and C adds 2, all at once. After a full merge, what is the value?

Chapter 4

Registers and Sets

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.

winner = the write with the larger (timestamp, replica id) A writes "Alice" at 1,000 ms real time. B writes "Bob" at 990 ms, but B's clock runs 50 ms fast, so "Bob" carries 1,040. Bob wins, though Alice wrote last.

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.

Say it aloud

e is in S if and only if A-e minus R-e is not empty.

e
e one element, such as milk.
∈ S
is in S is in the set the user sees.
⇔
if and only if the two sides are true together or false together.
Ae
A-e every tag ever added for e, on any replica this copy has merged.
∖
minus set difference: keep the tags of A-e that are not in R-e.
Re
R-e the tags of e that some remove has seen and deleted. They are called tombstones.
≠ ∅
is not empty at least one tag is left.
In plain words

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.

With numbers

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.

Add and remove milk at once

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.

50 ms

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.

A adds X (tag 1) and syncs with B. Then A removes X while B adds X again (tag 2). After the merge, is X in the set?

Chapter 5

Spreading by Gossip

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.

Say it aloud

r is about log base two of N, plus the natural log of N.

r
r the number of rounds until every node has the update.
≈
is about on average, for a large N; single runs scatter around it.
log2 N
log base two of N how many doublings take 1 node to N nodes.
ln N
the natural log of N the extra rounds spent finding the last nodes, when most calls reach nodes that already know. N is the number of nodes.
In plain words

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.

With numbers

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.

Spread one update

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.

1,000 nodes run push gossip: each informed node calls one random node per round. About how many rounds until every node has the update?

Chapter 6

Finding What Differs

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.

Say it aloud

h equals one plus two times log base two of K.

h
h how many hashes the two replicas compare to find one differing leaf.
1
one the comparison of the two roots.
2 ·
two times both children of the one node that differs, at each level.
log2 K
log base two of K the number of levels below the root, for a tree with K leaves.
In plain words

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.

With numbers

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.

Walk the hash tree

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.

1

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.

Two replicas hold trees with 1,024 leaves and differ in one leaf. How many hashes does the top-down walk compare?

Chapter 7

Keeping Cause Before Effect

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.

Say it aloud

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.

Vm
V-m the vector stamped on message m.
[j]
of j the entry for j, the replica that sent m.
Vi
V-i the receiving replica i's vector: how many messages it has delivered from each sender.
[k]
of k the entry for some other sender k.
≤
is at most less than or equal to.
∀ k ≠ j
for every k other than j check this for each sender except the one that sent m.
In plain words

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.

With numbers

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.

Hold the reply

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.

Replica C has delivered the vector (2, 1, 0) for senders A, B, C. A message from B arrives stamped (3, 2, 0). Can C deliver it now?

Chapter 8

When You Must Coordinate

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.

OperationMonotonic?Why
Union, filter, joinYesA new row only adds results.
"Count is at least 10"YesOnce true, more rows keep it true.
The final countNoOne late row changes the answer.
"No such row exists"NoThe row may still arrive.
Set difference A minus BNoA 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.

Run the merge test

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.

Which operation and rule can run on every replica with no coordination?

Chapter 9

A Live CRDT Cluster

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.

Run three replicas

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:

  1. Cut both of A's links. On A, add 2 and remove milk. On B, add 1 and add milk again.
  2. Gossip a few rounds: B and C agree, and A stays apart.
  3. Heal one of A's links and gossip again. All three show quantity 3 and keep milk, because B's add made a tag A never saw.
  4. Rename on A and on B during a cut. After healing, one name survives: the one with the larger timestamp.
  5. Cut every link. Gossip does nothing, and the state stays "not converged".

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.

Replica A is cut off. A adds 2 to the quantity while B adds 1. After the link heals and gossip runs, what does every replica show?

Chapter 10

The Field Guide

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.

Terms and numbers

TermWhat it isThis lesson's number
Coordinated writeT = rL + rq−1Tokyo via Virginia: 150 + 90 = 240 ms; local about 1 ms
Joincommutative, associative, idempotentupdates 3, 7, 5: max gives 7 everywhere
G-Counterv = Σ max(ai, bi)(2, 0, 0) and (0, 1, 0): 3
PN-Counterv = Σ Pi − Σ Ni+5, −3, +2: 4; last unit sold twice: −1
OR-Sete ∈ S ⇔ Ae ∖ Re ≠ ∅{a1, b2} minus {a1}: milk stays
Gossipr ≈ log2 N + ln NN 1,000: 16.9 predicted, 18.0 simulated
Merkle walkh = 1 + 2 · log2 KK 16: 9; K 220: 41
Causal deliveryVm[j] = Vi[j] + 1, Vm[k] ≤ Vi[k](1, 1, 0) held at (0, 0, 0)

Which tool for which job

JobUseWhy
Likes, views, page hitsG-CounterOnly grows; any replica may add
Cart quantity, vote tallyPN-CounterUp and down, no floor needed
Cart items, tags, flagsOR-SetConcurrent add beats remove; no resurrection
Status, last-seen timeLWW-RegisterOnly the newest value matters
Stock with a floorEscrow, or a coordinator for the last unitsstock ≥ 0 is not confluent
Usernames, balances, ordered logsConsensus (Raft)Uniqueness and floors need agreement

In production

Checklist

  1. Write down each rule (invariant) and run the merge test on it.
  2. Check that every merge is commutative, associative and idempotent: fuzz it with random states.
  3. Give each replica unique timestamps, or a unique id range.
  4. Plan for tombstones and per-replica slots: both grow until you collect them.
  5. Run anti-entropy as well as gossip, and alert when replicas stay apart.
  6. Coordinate only the operations that fail the test, and keep the rest local.

The core as code

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)

Keep going

The takeaway. Make the state something that only grows, and make the merge a join. Then replicas can take every write at once, receive updates late, twice and in any order, and still agree. Coordinate only the rules that a merge can break.

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.

Coordination Avoidance
CRDTs 2011 · Coordination Avoidance 2014 · Keeping CALM · Back to Gleams