CRDTs & Eventual Consistency
Handling concurrent updates without coordination — conflict resolution strategies, last-writer-wins pitfalls, CRDTs (G-Counter, PN-Counter, OR-Set, LWW-Register, sequence CRDTs), state vs operation-based CRDTs, anti-entropy, and local-first software.
In multi-leader or leaderless systems — and in offline-capable apps — different replicas accept writes concurrently without coordinating. That's what makes them fast and available (CAP). The price: replicas diverge, and conflicting updates must be merged when they meet.
Conflict resolution strategies
| Strategy | How | Problem |
|---|---|---|
| Last-writer-wins (LWW) | Keep the value with the highest timestamp | Silently loses concurrent updates; depends on clocks (Clocks) |
| Keep siblings | Store all concurrent versions (detected by version vectors) and let the app/user merge | Pushes complexity to the application (Riak, early Dynamo shopping carts) |
| Application merge function | Custom code merges on read or write | Easy to get wrong |
| CRDTs | Data types whose merge is mathematically guaranteed to converge | Limited to supported types; metadata overhead |
CRDTs
A Conflict-free Replicated Data Type is a data structure that replicas can update independently and concurrently, and that always converges to the same state once all replicas have received the same updates — no coordination, no conflicts to resolve manually (strong eventual consistency).
State-based CRDTs (CvRDTs)
Replicas periodically send their whole state; the receiver merges it. Convergence is guaranteed if merge is:
- Commutative: merge(a, b) = merge(b, a)
- Associative: merge(merge(a, b), c) = merge(a, merge(b, c))
- Idempotent: merge(a, a) = a
These properties mean messages can arrive in any order, be duplicated, or be delayed — the result is the same. (Mathematically, states form a join-semilattice and merge is the least upper bound.)
Operation-based CRDTs (CmRDTs)
Replicas broadcast operations; concurrent operations must commute. Smaller messages, but requires reliable, exactly-once (often causally ordered) delivery. Delta-state CRDTs are a practical middle ground: send only the recently changed part of the state.
Classic CRDTs
G-Counter (grow-only counter)
Each replica keeps a count per replica. Increment your own entry; merge takes the element-wise max; the value is the sum.
class GCounter:
def __init__(self, replica_id: str):
self.id, self.counts = replica_id, {}
def increment(self, n: int = 1):
self.counts[self.id] = self.counts.get(self.id, 0) + n
def value(self) -> int:
return sum(self.counts.values())
def merge(self, other: "GCounter"):
for rid, c in other.counts.items():
self.counts[rid] = max(self.counts.get(rid, 0), c)Why not just send "+1" messages? Because a duplicated message would double-count; with per-replica maxima, duplicates are harmless (idempotent).
PN-Counter
Two G-Counters: one for increments (P), one for decrements (N). Value = sum(P) − sum(N). Used for likes, votes, inventory estimates.
Sets
- G-Set: add-only; merge = union.
- 2P-Set: an add set and a remove ("tombstone") set; once removed, an element can never be re-added.
- OR-Set (observed-remove set): each add is tagged with a unique ID; remove deletes only the tags it has observed. A concurrent add (with a new tag) survives — add wins. This matches user intent in most apps (shopping carts, tags, collaborative lists).
Replica A: add("milk") → {milk#a1}
Replica B (has seen a1): remove("milk") → removes tag a1
Replica A concurrently: add("milk") again → {milk#a2}
Merge: milk#a2 survives → "milk" is in the set (add wins)Registers and maps
- LWW-Register: a single value with a timestamp (often a hybrid logical clock + replica ID tie-break). Concurrent writes: one wins deterministically.
- MV-Register (multi-value): keeps all concurrent values for the app to resolve.
- OR-Map: a map whose values are themselves CRDTs — composable into JSON-like documents.
Sequences: collaborative text
Collaborative editors need a list where concurrent inserts and deletes at positions converge. Sequence CRDTs (RGA, Logoot/LSEQ, YATA used by Yjs, Fugue) give each character a unique, ordered identifier instead of an index, so "insert after character X" means the same thing on every replica. Deleted characters become tombstones (compacted later).
Operational transformation (OT) — used by Google Docs — solves the same problem by transforming concurrent operations against each other via a central server. CRDTs work peer-to-peer and offline.
Anti-entropy and read repair
How replicas find out they differ (in Dynamo-style stores like Cassandra and Riak):
- Read repair: when a read contacts several replicas and sees different versions, it writes the newest/merged version back to the stale ones.
- Hinted handoff: if a replica is down, another node stores the write with a "hint" and forwards it when the replica returns.
- Anti-entropy with Merkle trees: replicas exchange hash trees of their data; comparing hashes top-down finds differing key ranges with little data transferred.
Where CRDTs are used
- Collaborative editing: Yjs and Automerge (Figma-, Notion-, Linear-style multiplayer), Apple Notes.
- Databases: Riak data types, Redis Enterprise active-active, Azure Cosmos DB multi-region writes, AntidoteDB.
- Local-first software: apps that work fully offline on the device and sync when connected, with the user's data primarily local.
- Counters and presence in chat and gaming systems.
- Concurrent writes on different replicas must be merged; LWW is simple but loses updates.
- CRDTs converge automatically: merge is commutative, associative and idempotent.
- G-Counter / PN-Counter for counts, OR-Set (add wins) for sets, LWW/MV registers, sequence CRDTs for text.
- Read repair, hinted handoff and Merkle-tree anti-entropy keep replicas in sync.
- CRDTs power collaborative and local-first apps but can't enforce global invariants like uniqueness.