Systemsfor Aravinda
0 / 78 core
Week 4 · Distributed systemsAdvanced

CRDTs

2 hours · optional track

Read first: Consistency models

In one sitting

Replicas accept updates with no coordinator and still converge when the merge is built so that order and retries do not matter. A grow-only counter keeps every increment, while a last-writer-wins register keeps one write and drops the other. The metadata is the bill, and a server that orders updates is not paying it.

A new-grad loop rarely requires them. Collaborative editing in that loop is one server that orders updates, and that is the design you should be ready to defend. The evening is worth it because the name has become a loose compliment for any merge, including merges that have a leader. The useful skill is to say whether replicas can take writes with nobody in charge and still converge, what the merge drops, and how the metadata grows.

Core concepts

A CRDT, from Shapiro and others, is a replicated object that accepts updates without coordination and converges because the merge was designed to. The problem it exists to solve is a partition where both sides must keep writing, and a heal where you want one deterministic result without electing a winner after the fact. Eventual consistency says replicas converge if updates stop. A CRDT is one way to make that sentence true by construction, instead of hoping the clients agree.

There is no central authority in the definition. A server that receives every update and picks the order is a simpler system, and it is not a CRDT. You pay the server’s availability. You do not pay a merge function, and you do not pay the metadata the merge needs. If you have that server, use it. The rest of this page is the case where you do not.

Two ways to ship the update

State-based CRDTs ship the local state. The merge of two states is a join: you can merge in either order, you can group the merges however you like, and merging a state with itself changes nothing. A retried state message is safe for that reason. The merge is idempotent in the same sense as setting a field. Delivering the payload twice does not double the effect.

Operation-based CRDTs ship the operation. The operations have to commute, or two replicas that apply them in different orders diverge, which is the failure you built this to avoid. A retried operation is not automatically safe. “Increment” delivered twice is two increments. The commutativity is about order. Duplicate delivery is a separate problem, and the channel or the operation has to address it. If you cannot say which of the two styles you are holding, you do not yet have a merge. You have messages.

A grow-only counter

A G-counter is the teaching example because the merge is visible. Each replica holds its own non-negative integer. An increment adds to the local slot and does not touch the others. The value anyone reads is the sum of the slots. The merge takes the max of each slot. Because a slot only grows, the max never throws an increment away. Both sides of a partition can increment. When the partition heals, the sum counts every increment either side accepted.

The structure cannot represent a decrement. A slot has no inverse. If the product needs to undo an increment, a grow-only counter is the wrong object. Inventory that must go down is the usual trap. Two replicas can each increment a “sold” counter during a partition and merge to the right total sold. That does not enforce “do not sell the last unit twice.” The counter converged. The invariant was a different problem, the one CAP puts on a checkout. Do not point a G-counter at a stock count and call the partition handled.

A last-writer-wins register

A last-writer-wins register stores one value. The merge keeps the write that ranks highest in a total order. The usual order is a timestamp plus a replica id, so a tie in the timestamp still has a winner and you do not flicker. The other write is dropped. That is the entire merge.

This fits a nickname, or any field where one of the concurrent values is acceptable and the other is waste. It does not fit a counter. Two increments become one number, and the number is whichever side won the order, not the sum. It does not fit a cart if both adds have to survive. The total order is something you imposed. Clocks and ordering is why a wall-clock timestamp is a shaky way to impose it: skew crowns the fast oscillator, not the later causal write. A replica id breaks ties. It does not repair a clock that is minutes off.

An observed-remove set, at the level of tags

A plain set has no good merge for “one side added x, the other removed x.” Whichever state arrives last wins, and the winner depends on the network. An observed-remove set, taught here at the level of the idea rather than a wire spec, gives each add a unique tag. A remove names the tags the replica has observed. Tags remember what you have seen. A concurrent add has a tag the remover has not seen, so the merge keeps it. An add the remover did see stays removed.

That is the intuition worth being able to say. You do not need the full replica state on a whiteboard. You need the reason a tag exists: so a remove cannot delete an add that had not happened yet from that replica’s point of view. The cost is the tags. They are metadata. They accumulate. A scheme to forget tags that everyone has already applied is a further design, and this page does not invent one.

What grows

Metadata is the bill for not having a leader. A G-counter’s payload is one integer per replica. Two replicas hold two integers no matter how large the count becomes. The payload grows when you add replicas, not when you increment. An observed-remove set grows with tags. A key that is added and removed in a loop still has a history of tags inside the merge, unless you have that extra scheme. The value the user sees can be a short set while the state you replicate is not.

Dynamo hit the same shape of pain with vector clocks, without being a CRDT catalog. Versions multiplied, and the client had to merge. A CRDT moves that merge into the object so two replicas that have seen the same set of updates reach the same state. It does not make the metadata free. If you cannot point at what gets larger, you have a slogan.

Figma is not a CRDT

Figma’s multiplayer design is the example people misname. The server is the authority. Clients send updates over a WebSocket and the server broadcasts them. Conflict resolution is per property on an object: the last update to reach the server wins. Unrelated properties do not conflict. This is the shape of a last-writer-wins register, except the server defines the order, so they do not need a timestamp. It is inspired by CRDTs and it is not one. A CRDT is built for replicas with no central authority, and that costs metadata they chose not to pay.

Text is a single property value. Two people editing the same text can end with one of the two strings, not a character-level merge. They say that is acceptable because Figma is a design tool, not a text editor. Sibling order uses fractional indexes, a fraction strictly between 0 and 1 stored as a string so they do not run out of precision, and concurrent inserts can interleave. That interleaving is a trade they accepted on the server. The Figma multiplayer page holds the rest of that design. The fact that belongs here is the negative one. A central order is simpler. It is not a CRDT, and calling it one will send you looking for a tag store the product does not have.

A worked example

Two replicas, A and B, and a counter of items added to a cart during a partition. You want every increment. Assumptions:

  • The counter starts at zero. Each replica’s slot starts at zero. There is no decrement in this product. If there were, you would stop and pick a different object.
  • The partition drops all messages until the end of the walk. Each increment is applied once, locally. You are not also retrying a duplicated operation message.
  • The value a replica shows locally is the sum of the slots it currently knows. During the partition it does not know the other side.
slots written as A, B
value = A + B

start
  0, 0
  value 0

partition

A increments twice
  A sees 2, 0
  local value 2

B increments once
  B sees 0, 1
  local value 1

heal, merge is the max of each slot
  A = max of 2 and 0 = 2
  B = max of 0 and 1 = 1
  value = 2 + 1 = 3

a single integer under last-writer-wins
  keeps either 2 or 1
  the other side's increments disappear

merge the same state again
  max of 2 and 2 is 2
  max of 1 and 1 is 1
  value stays 3
  a retried state message did not add a fourth

Three is the right total. Each side accepted increments the other could not see, and the max-per-slot merge kept both. A last-writer-wins integer would have stored one side’s local sum and deleted the other side’s work, which is the wrong object wearing the right name. The last line is the state-based property you can defend: merging a state you already have is a no-op. If you had shipped the operation “increment” instead, and the network delivered A’s two increments twice, a naive apply would move A from 2 to 4. Operation-based replication has to care about that duplicate. The state merge does not.

Now a set, because a counter is the friendly case. Milk is the item. Tags are unique ids the add creates. Assumptions: both replicas start from the same observed tag, then the partition splits a remove from a new add.

both sides have seen milk under tag t1

partition

B removes milk
  B has observed t1
  the remove names t1

A adds milk again under a new tag t2
  A has not observed the remove

merge
  t1 is named by the remove, so t1 is gone
  t2 was never observed by the remover, so t2 stays
  milk is in the set

if A had not added again
  the only tag was t1
  t1 is removed
  milk is gone
  which is what B asked for, and A had seen that milk

The tag is the memory of what the remover was allowed to delete. A plain set, merged by “the remove arrived last,” would have deleted t2 as well, including an add B had never seen. Merged by “the add arrived last,” it would have resurrected t1 and undone a remove of milk both sides had already acknowledged. The tags split those histories. The state you ship now includes t1’s removal and t2’s add. That is more than the one word “milk” on the screen. Do that on a hot key for a long time and the metadata is the growth Dynamo was complaining about, moved into the object.

Figma, on the same two editors, does none of this. Both people change the same text property. The server applies the update that arrives last and broadcasts that string. One of the two strings survives. There is no tag, no per-replica slot, and no client merge. The editor who lost the race lost the string. They accepted that because the tool is not a text editor. If your product cannot accept that loss, the server-ordered register is the wrong copy of their design, and a CRDT is a different cost: tags or slots, and a merge you have to implement.

flowchart TB
  sideA[Replica A increments twice]
  sideB[Replica B increments once]
  split[Partition]
  heal[Merge keeps the max of each slot]
  sideA --> split
  sideB --> split
  split --> heal

The heal step is the product. If that box says “last write wins” on a counter, the diagram is a bug. If it says “the server picked the later packet,” you are describing Figma, and you should take the CRDT label off the box.

Tradeoffs

Object What the merge keeps What you lose
G-counter Every increment, summed after a max per slot Decrements, and any invariant the sum does not express
Last-writer-wins register One value, under timestamp plus replica id The write that lost, silently
Observed-remove set Adds whose tags the remover had not seen Space, as tags accumulate
Server-ordered property, as in Figma The last update that reached the server, per property Offline writers, character-level text merge, and it is not a CRDT
Single primary and a log One order everyone can replay Writes on the side that cannot reach the primary

A five-replica G-counter holds five integers. That payload does not grow with the number of increments. An observed-remove set does grow with the number of adds you have ever observed, until you design a way to drop tags, which you should not pretend is free. A primary stores the latest value and forgets the losers. The primary is the smaller state. It is unavailable to writers on the wrong side of a partition. Pay for the CRDT when that unavailability is the failure you refuse. Do not pay for it because the word sounds precise.

Pitfalls

  • Calling Figma a CRDT. The server orders each property. There is no merge without a leader, and text does not merge by character. You will go looking for metadata they chose not to store.
  • Using last-writer-wins for a counter. One side’s increments disappear. The symptom is a total that is smaller than the number of accepted clicks.
  • Using a G-counter for a balance that must go down, or for units left in stock. You cannot represent the decrement, and convergence of a sold-count does not stop a double sale.
  • Treating an operation-based increment as safe to retry. Delivered twice, it counts twice. The state-based max does not have that trap. The styles are not interchangeable at the transport.
  • Ignoring metadata. The user-visible set stays small while tags accumulate. The replicate-everything path gets slower and you cannot explain why from the product screen.
  • Reaching for a CRDT in a system that has one database and one primary. The primary already orders the writes. The merge function is an extra way to be wrong.
  • Assuming the clock inside a last-writer-wins register is causal. A fast wall clock wins. That is a total order, not happened-before.

In the interview

In a new-grad loop, say the server orders property updates and that this is not a CRDT. Name the loss: two people editing the same text can end with one of the two strings. If they want the structure anyway, draw the G-counter. Two slots, increments 2 and 1 during a partition, merge to 3, and a single integer would have kept 2 or 1. The number is the merged sum. The bottleneck is metadata, one integer per replica for the counter and a tag per observed add for the set. The tradeoff is accepting writes on both sides of a partition against that growth, and against the updates the merge drops.

Skip a lattice proof. You are not being graded on one. Skip a wire layout for an observed-remove set. The sentence is enough: a remove deletes the tags you have seen, and a concurrent add carries a tag you have not.

The question that usually follows is “what grows?” Answer with the payload, not with the user-visible value. Then say what you refuse to drop. A counter must not drop an increment. A nickname can drop the losing write. A stock count should not be a G-counter at all, because the operation you need is a decrement under an invariant.

Check yourself

A G-counter ends a partition with slots 2 and 1. What is the merged value, and what would one integer have done?

The merge takes the max of each slot, so the slots stay 2 and 1, and the value is their sum, 3. Every increment either side accepted is in that sum. A last-writer-wins integer would store 2 or 1 and delete the other side. Merging the state a second time stays at 3, because the max of a slot with itself is the slot. That is why a retried state message does not invent a new increment.

Why is Figma's per-property last update not a CRDT?

The server is the authority. The last update to reach it wins for that property, and the server defines the order, so no timestamp and no tag is required. A CRDT is for replicas with no central authority, and it costs the metadata Figma chose not to pay. Text is one property, so two editors can end with one of the two strings rather than a character-level merge. They accept that because it is a design tool, not a text editor. Inspired by CRDTs is not the same as being one.

One side removes milk while the other adds milk under a new tag. What does an observed-remove set keep?

It keeps the new tag. The remove only names tags the remover had observed. The new add’s tag was not among them, so the concurrent add survives and milk stays in the set. A tag the remover had seen stays removed. A plain set has to pick add or remove for the whole item and will either resurrect the old milk or destroy the new add. The tags are what make those histories different, and they are also what accumulate.

Someone proposes a grow-only counter for units left in stock. What can it not represent?

A decrement. Each slot only grows, and the merge keeps the max, so there is no way to put a unit back or to record that a unit was sold as a subtraction. Two sides can each count sales and merge the total sold. That total does not stop both of them from selling the last unit during the partition. The invariant lives somewhere that can refuse a write. The counter will only add.

An operation-based increment is delivered twice, and a state-based G-counter receives the same state twice. Which one changes value the second time?

The operation does, if “increment” applied twice means two increments. Commutativity does not make the operation idempotent. The state-based counter does not change the second time. The merge is a max per slot, and the max of a slot with the same slot is that slot, so a retry of the state is a no-op. The two styles meet the partition differently, and only one of them forgives a duplicate message for free.

Based on: Shapiro and others, CRDTs; Figma multiplayer; Amazon Dynamo, SOSP 2007, DeCandia and others; Designing Data-Intensive Applications, Kleppmann and Riccomini.