CRDTs — Merging Without a Coordinator
Merging Without a Coordinator
System designsystem design / distributed systems
Same conflict, two resolution strategies
Shared shopping cart, both devices offline:
- Phone: removes "milk"
- Laptop: sets eggs quantity to 3
Both sync 5 minutes later.
LWW register (store the whole cart as one blob)
Unit of conflict = the entire object. Newest timestamp wins. Laptop wrote last → its blob replaces everything → milk is back in the cart. This is the classic Dynamo "resurrected deleted item" bug. Also: it needs synced clocks you don't have.
CRDT (per-field/per-element types)
Unit of conflict = each element. Resolution = a deterministic merge function. Remove-milk and set-eggs touch different elements, so both survive. No clocks, no coordinator, no lost write.
The actual rule
A CRDT merge must be commutative, associative and idempotent. Once it is, delivery order and duplicate messages stop mattering — every replica converges to the same state. That's the whole trick: you don't order the writes, you make ordering irrelevant.
Concrete: G-Counter (grow-only)
# state: {replica_id: count}
def inc(s, me): s[me] = s.get(me, 0) + 1
def merge(a, b): return {k: max(a.get(k,0), b.get(k,0)) for k in a | b}
def value(s): return sum(s.values())
Why max per key instead of summing? Because merge runs repeatedly over overlapping states. sum() double-counts a re-delivered gossip message; max() is idempotent. That single line is the difference between a counter and a slow drift bug.
Deletes are the hard part
You can't just drop an element — a stale replica re-adds it on the next merge. So you record the removal: a tombstone (2P-Set), or unique add-tags you've observed (OR-Set). Cost: state grows with every delete, so production systems need tombstone GC gated on causal stability.
What practitioners get wrong
- "CRDT means no conflicts." It means no merge failures. Two concurrent set-title ops still need a rule — and LWW-register is itself a legal CRDT, with real loss.
- Counters are trivial; text is not. Ordered sequences (RGA/YATA, as in Yjs/Automerge) need a unique ID per character.
- State-based (ship whole state) is simple but heavy. Op/delta-based is lighter but needs effectively-once delivery per op.
- CRDTs cannot enforce invariants. "Balance never goes negative" is impossible — two replicas each approve a withdrawal and both merges are valid. Invariants need consensus.
✅ Reach for them: offline-first apps, multi-region active-active writes, presence, counters, collaborative docs.
🚫 Don't: uniqueness constraints, quotas/limits, anything needing a global order.
Your exercise
Implement a PN-Counter (supports decrement) as two G-Counters, value = sum(P) - sum(D). Then answer in one sentence: why can't you do it as a single map of signed counts merged with max()? (Hint: trace what happens to one decrement.)