← Data structures

CRDT

Text, space and time

A conflict-free replicated data type: a counter, set, map or text document defined so that any two replicas, updated independently, can be merged into the same result no matter the order the updates arrive. It exists so that offline devices and far-apart regions can accept writes without coordination and still converge.

What it costs

OperationCostNote
Local updateO(1)Apply immediately, no round trip; the change is a commutative operation or a state delta.
Merge two replicasO(state size)A deterministic join: element-wise max for counters, union for grow-only sets.
Read the valueO(replicas) for countersSum of all per-replica counts; O(1) if a cached total is kept.
Remove (sets)O(1) + tombstoneRemoval needs a tombstone or a unique tag per add, so adds and removes commute.

Memory: Per-replica state rather than one value: a counter across 5 regions is 5 integers (40 bytes) instead of 1. Sets carry a unique tag per element and tombstones for removals until garbage-collected, so an observed-remove set of 1,000 reactions is about 50 KB rather than 8 KB.

A grow-only counter: per-replica slots, max-merge, sum to read

Each region increments only its own slot. Merging takes the element-wise maximum, so messages can arrive in any order or twice and both sides still converge on the same total.

How it works

  1. Pick a data type whose merge is a join: an operation that is commutative (order does not matter), associative (grouping does not matter) and idempotent (applying twice equals once). Max, union and logical OR all qualify; plain addition and overwrite do not.
  2. Grow-only counter (G-Counter): each replica keeps its own slot and only increments it. Merge is the element-wise maximum of the vectors. The value is the sum of all slots. Two replicas each adding 3 to their own slot merge to [3, 3] = 6 no matter who merges first.
  3. Positive-negative counter (PN-Counter): two G-Counters, one for increments and one for decrements. Value is P minus N. Now decrements work, still with max-merge.
  4. Grow-only set: merge is set union. Observed-remove set (OR-Set): every add gets a unique tag; a remove deletes the tags it has seen. A concurrent add with a new tag survives the remove, so "add wins" deterministically instead of depending on arrival order.
  5. Last-writer-wins register: a value plus a timestamp (or hybrid logical clock); merge keeps the larger timestamp. Simple, but it is the one CRDT that does lose a concurrent write by design.
  6. Sequence CRDTs (RGA, Yjs, Automerge) give each character a unique position id between its neighbours so concurrent inserts from two editors interleave deterministically; this is how collaborative text editing merges without a central server.

Why it is shaped this way

  • Keeping per-replica state instead of one merged value is what makes the merge a pure function of the two states; nobody needs to know which update happened first.
  • Idempotence means retransmitting a state or applying an update twice is harmless, which removes the need for exactly-once delivery between replicas.

Worked example

View counts and reactions on the streaming platform

  • View counter across 5 regions: each region keeps its own slot and increments locally with no cross-region call. Region vectors after an hour: [120K, 95K, 80K, 60K, 45K]. Every region gossips its vector; merge is element-wise max, so a replayed or duplicated message cannot double count. Displayed total: 400K, and every region shows the same number once vectors have propagated, typically within a second.
  • Compare a single global counter: 400K increments an hour means cross-region writes or a central Redis on every view; the CRDT makes it 5 local counters and 5 small vectors per second of gossip.
  • Reactions as an OR-Set per video: user 42 taps 👍 in Sydney (add tag s1), then removes it on their laptop in London before the add has arrived there. London sends remove of tags it has seen (none); Sydney has add s1. Merge: s1 survives because the remove never observed it. The reaction stays, which is the intended add-wins behaviour, and both sides converge on the same set.
  • Cost: each reaction carries a 16-byte tag and removed tags linger as tombstones until a periodic compaction once every replica has seen them. 1,000 reactions ≈ 50 KB per video versus 8 KB as a plain set.
  • Where it stops: a video’s title (one value) uses a last-writer-wins register with a hybrid logical clock, because there is no sensible merge of two titles.

When it is the wrong choice

  • Values with an invariant that merging cannot preserve: an account balance that must never go below zero, or inventory with 1 unit left. Two replicas can each "sell the last one"; you need a single writer or consensus for that key.
  • Data with no natural merge (a title, a price): only last-writer-wins applies, and then you are back to losing a concurrent write, just deterministically.
  • When metadata dominates: tags and tombstones can be several times the payload for tiny values updated often; a central counter in Redis may be cheaper if a cross-region round trip is acceptable.

Interviewer follow-ups

Answer out loud before you open each one.

Why does a counter need one slot per replica instead of one number?

With one number, two replicas that each added 3 to a base of 10 both hold 13, and merging has no way to know the answer should be 16. With a slot per replica each holds its own contribution, merge takes the maximum per slot (which is safe because each slot only grows), and the sum gives 16. The extra slots are what make the merge order-independent.

How does an observed-remove set decide between a concurrent add and remove?

Every add carries a fresh unique tag. A remove deletes only the tags the remover had seen. If an add happened concurrently, its tag is new to the remover and survives, so the element stays: add wins. The rule is deterministic, so every replica reaches the same set.

What properties must the merge function have, and why?

Commutative so arrival order does not matter, associative so grouping does not matter when three replicas merge pairwise, and idempotent so a repeated or replayed state changes nothing. Together they guarantee all replicas converge once they have exchanged states, without any coordination or exactly-once delivery.

What can a CRDT not do?

Enforce a global invariant across concurrent writes. "Never oversell", "unique username" and "balance above zero" need someone to say no to one of two concurrent writes, which is coordination. CRDTs are for data where every concurrent write is acceptable and the question is only how to combine them.

Where it shows up

Building blocks
Accept a short delay for scale · Deliver to users who are offline · Count big things with small memory · Shard by region
Problems
Video Streaming Platform (YouTube / Netflix) · Chat App (WhatsApp / Messenger)