CRDTs & Conflict Resolution: Merging Concurrent Writes Without Losing Data
A shopper in Frankfurt adds a pair of headphones to her cart from her phone. Ten seconds later her partner, on the same family account, removes a phone case and adds a charger from a laptop that happens to be routed to the Dublin region. Both regions accept the write locally, because the whole point of running active in two regions is that a write never waits 25 ms for the other side.
When the two regions exchange their changes, the database holds two versions of the same cart. Version A has the headphones. Version B has the charger and no phone case. Neither is “newer” in any meaningful sense: they were written at the same time, by different people, about different items.
If the database keeps the version with the larger timestamp, one person’s change disappears. No error, no log line, no alert. The cart simply loses the headphones, the order ships without them, and support gets a ticket three days later that nobody can reproduce. This article is about how to stop that from happening.
What it is
A conflict happens when two replicas accept writes to the same data without first agreeing on an order. This is normal, not exceptional, in two kinds of system covered in replication strategies:
- Multi-leader: each region (or each offline device) has its own leader that accepts writes and replicates asynchronously to the others.
- Leaderless: any replica in a quorum can accept a write, so two clients writing the same key through different coordinators can each succeed on overlapping but different replica sets.
Single-leader systems avoid the problem for ordinary writes, because one node serialises everything. The price is that every write pays a round trip to the leader, and the leader’s region going dark blocks writes.
Conflict resolution is the rule that turns two concurrent versions into one. There are four families of rules:
- Last write wins (LWW): keep the version with the highest timestamp, discard the other.
- Application merge: call custom code with both versions and let it decide.
- Siblings: keep every concurrent version and hand them all to the next reader, who merges and writes back.
- CRDTs (conflict-free replicated data types): data structures whose merge is mathematically guaranteed to converge, so replicas can apply updates in any order and still end up identical.
The guarantee CRDTs give is called strong eventual consistency: any two replicas that have received the same set of updates are in the same state, with no coordination and no rollback. It sits among the weaker models in consistency models, but it is stronger than plain eventual consistency because convergence is deterministic rather than “eventually someone fixes it”.
How it works
Step 1: detect that two writes are concurrent
You cannot resolve a conflict you cannot see. Wall-clock timestamps cannot tell “B happened after A” from “A and B happened at the same time on different machines”. Version vectors can. Each replica keeps a counter per replica, increments its own counter on every write, and attaches the vector to the value. Comparing two vectors gives one of three answers: A happened before B, B happened before A, or they are concurrent. The mechanics are covered in time, clocks and ordering; here we only need the result.
sequenceDiagram participant F as Replica Frankfurt participant D as Replica Dublin Note over F,D: Both start with cart v[F:1, D:1] F->>F: add headphones, v[F:2, D:1] D->>D: remove case, add charger, v[F:1, D:2] F->>D: replicate v[F:2, D:1] D->>F: replicate v[F:1, D:2] Note over F,D: Neither vector dominates the other: CONCURRENT Note over F,D: Resolution rule decides the merged cart
Step 2: pick a resolution strategy
Last write wins attaches a timestamp to each write and keeps the highest one. It is cheap, needs no extra metadata beyond the timestamp, and always converges. It also silently discards every concurrent write except one. With clock skew of even 100 ms between nodes, a write that really happened later can lose to an earlier one stamped by a fast clock. Cassandra resolves every cell this way using client or coordinator timestamps, and DynamoDB global tables in their default multi-Region eventually consistent mode reconcile concurrent updates to the same item with last writer wins. LWW is the right choice when each key is effectively written once (immutable events, cache entries) or when losing a concurrent write is acceptable (a “last seen online” timestamp). It is the wrong choice for anything a human edits.
Application merge gives you both versions and lets your code decide. CouchDB stores conflicting revisions and picks a deterministic winner while keeping the losers so the application can merge them. The danger is that merge code is ordinary code: it must be deterministic, it must produce the same result regardless of which replica runs it, and it must handle three-way and four-way conflicts, not just two.
Siblings push the problem to the reader. The 2007 Amazon Dynamo paper described exactly this for the shopping cart: the store returned all concurrent versions, the cart service took their union, and wrote the merged cart back with a version vector that dominated both. Riak exposed the same model with allow_mult. Siblings never lose a write, but the paper also notes the cost: a union merge can resurrect deleted items, because a removal in one branch looks the same as “never added” in a set without metadata.
CRDTs build the merge into the data type so it can never be written wrong. That is the rest of this article.
Step 3: understand why CRDT merges always converge
A state-based CRDT is a value plus a merge function with three properties:
- Commutative: merge(a, b) equals merge(b, a). Order of arrival does not matter.
- Associative: merge(merge(a, b), c) equals merge(a, merge(b, c)). Grouping does not matter, so gossip can take any path.
- Idempotent: merge(a, a) equals a. Receiving the same state twice is harmless, so you can resend freely.
A set of states with a merge that satisfies these three is a join semilattice: every pair of states has a least upper bound, and merge computes it. Intuitively, each state sits somewhere on a hill, updates only ever move a replica uphill, and merge takes two replicas to the lowest point that is above both. Because there is exactly one such point, every replica that sees the same updates ends up at the same place. That is the whole trick, and it is why CRDTs can replicate over unreliable gossip (covered in gossip and failure detection) with duplicates, reordering and arbitrary delays.
State-based vs operation-based
State-based (CvRDT) replicas ship their whole state (or a delta of it) and the receiver merges. The network may drop, duplicate and reorder messages; idempotent merge absorbs it all. The cost is bandwidth: shipping a large set on every sync is wasteful, which is why practical systems use delta-state CRDTs that ship only the changed part while keeping the same merge.
Operation-based (CmRDT) replicas ship operations such as “add milk with tag x7”. Messages are small, but the delivery layer must guarantee every operation arrives exactly once at every replica and in causal order (an operation’s dependencies arrive before it). That pushes complexity into the messaging layer, and the delivery semantics article explains why exactly-once delivery is itself something you build, not something networks give you.
| Property | State-based | Operation-based |
|---|---|---|
| What travels | full state or deltas | individual operations |
| Network needs | any order, duplicates fine | exactly once, causal order |
| Message size | larger, grows with state | small |
| Typical use | database replication, gossip | collaborative editors with a sync server |
The core CRDT catalogue
G-Counter (grow-only counter). Each replica keeps its own slot in a vector of counts and only increments its own slot. The value is the sum of all slots. Merge takes the element-wise maximum. Because each slot only grows and only one replica writes it, max never loses an increment.
PN-Counter. Two G-Counters: P for increments, N for decrements. Value is sum(P) minus sum(N). Riak’s counters were PN-Counters.
G-Set (grow-only set). Merge is set union. Elements can be added, never removed. Useful for “users who have seen this announcement”.
2P-Set. A G-Set of additions plus a G-Set of removals (tombstones). Once removed, an element can never be re-added. Too restrictive for carts.
OR-Set (observed-remove set). Every add attaches a unique tag. A remove deletes only the tags the remover has observed. A concurrent add carries a fresh tag the remover never saw, so it survives. The result is add-wins semantics, which is what users expect from a cart.
LWW-Register. A single value plus a timestamp; merge keeps the higher timestamp, with a replica ID as tie breaker. This is LWW packaged as a CRDT: it converges, and it still drops concurrent writes. Use it for fields where that is acceptable.
MV-Register (multi-value register). Keeps every value written concurrently, tagged with version vectors, and returns all of them on read. This is the sibling model formalised. The application or user then picks one, and the next write supersedes all of them.
Maps compose these: each key holds a nested CRDT (a counter, a register, another map), and merge recurses. Riak KV 2.0 shipped counters, sets, maps, registers and flags built this way.
flowchart LR A["Replica A<br/>P[A:3, B:0, C:1]"] --> M["Merge = element-wise max"] B["Replica B<br/>P[A:2, B:4, C:1]"] --> M M --> R["Merged<br/>P[A:3, B:4, C:1]<br/>value = 8"] R --> X["Merge again with A or B<br/>still value = 8 (idempotent)"] style A fill:#EEEDFE,stroke:#534AB7,color:#3C3489 style B fill:#EEEDFE,stroke:#534AB7,color:#3C3489 style M fill:#F1EFE8,stroke:#888780,color:#444441 style R fill:#E1F5EE,stroke:#0F6E56,color:#085041 style X fill:#E1F5EE,stroke:#0F6E56,color:#085041
Worked example: merging two shopping carts
flowchart TB S["Start: milk(a1), case(a2)"] --> F["Frankfurt: add headphones(f1)"] S --> D["Dublin: remove case(a2), add charger(d1)"] F --> M["OR-Set merge<br/>live tags minus removed tags"] D --> M M --> R["milk, headphones, charger"] F --> L["LWW whole cart<br/>higher timestamp wins"] D --> L L --> LR["milk, case, headphones<br/>charger lost, case back"] style S fill:#F1EFE8,stroke:#888780,color:#444441 style M fill:#EEEDFE,stroke:#534AB7,color:#3C3489 style R fill:#E1F5EE,stroke:#0F6E56,color:#085041 style L fill:#FAEEDA,stroke:#854F0B,color:#633806 style LR fill:#FCEBEB,stroke:#A32D2D,color:#791F1F
Collaborative text: sequence CRDTs vs OT
Text is the hardest case. Two people type at position 5 at the same time; positions shift as soon as either insert lands, so “insert at index 5” means different things on different replicas.
Operational transformation (OT) keeps index-based operations and transforms each incoming operation against the concurrent ones already applied, shifting indexes so intent is preserved. Google Docs uses OT with a central server that defines the order of operations. OT is efficient and battle tested, but correct transform functions for rich text are notoriously hard, and practical OT systems rely on that server.
Sequence CRDTs give every character a unique, immutable ID (replica plus counter) and describe inserts relative to IDs, not indexes: “insert X after character f1:17”. Deletes mark a character as a tombstone rather than removing it, because a concurrent insert might reference it. RGA (replicated growable array) is the classic design; Automerge’s list and text types descend from it, and Yjs uses a related algorithm called YATA. Because there is no central ordering, these work peer to peer and offline, which is what local-first software needs.
Two current libraries worth knowing:
- Yjs: a JavaScript CRDT framework widely used for collaborative editors, with bindings for ProseMirror, CodeMirror and others.
- Automerge: a JSON-like CRDT document library with a Rust core and JavaScript bindings. Automerge 2.0 moved the core to Rust; Automerge 3.0 (July 2025) cut memory use drastically by keeping the document compressed in memory, and its 3.x line is current through 2026.
Where it breaks
Tombstones and garbage collection. OR-Sets keep removed tags and sequence CRDTs keep deleted characters, because a late-arriving concurrent operation might reference them. You can only purge a tombstone once every replica has seen the removal, which requires knowing the full set of replicas and their progress. Offline devices make that hard: a laptop that comes back after three months may still reference a deleted ID. Systems either keep tombstones forever (and compress them aggressively), or define a horizon after which stale replicas must resync from a snapshot. Cassandra’s gc_grace_seconds is the same problem in an LWW store: if repair does not reach a replica before tombstones are purged, deleted data comes back.
Metadata growth. Version vectors grow with the number of replicas that have ever written. Thousands of short-lived clients each writing once can bloat every object. Mitigations: use server-side replica IDs instead of client IDs, or use dotted version vectors.
Convergence is not correctness. A CRDT guarantees every replica agrees, not that the agreed value is what the business wants. Two replicas can each decrement stock from 1 to 0 and a PN-Counter will happily converge to minus 1. Any invariant that spans replicas (stock never negative, username unique, balance never below zero) needs coordination: a single leader for that key, consensus, or an escrow scheme that pre-allocates quota to each region.
Semantic surprises. Add-wins is right for carts but wrong for “revoke access”, where you want remove-wins. Text CRDTs can interleave two concurrent insertions character by character in some algorithms; newer designs such as Fugue were created specifically to minimise that. Pick the semantics per field.
LWW hides bugs. Because LWW always converges, data loss from it never surfaces as an error. If you choose LWW, choose it on purpose and ideally measure it: count writes that were overwritten by a concurrent write.
Real-world systems
- Redis Software and Redis Cloud Active-Active databases replicate across regions using CRDT semantics per data type. Counters merge by summing operations, sets use add-wins, and concurrent
SETon a string falls back to last write wins. - Riak KV (historically) shipped CRDT counters, sets, maps, registers and flags in version 2.0. Basho, its original vendor, shut down in 2017; it remains a useful reference implementation.
- Cassandra and DynamoDB global tables (multi-Region eventual consistency mode) use last write wins for concurrent updates. DynamoDB also offers multi-Region strong consistency, which avoids the conflict instead of resolving it.
- CouchDB keeps conflicting revisions and lets the application resolve them.
- Yjs and Automerge power collaborative and local-first apps where clients edit offline and sync later.
- Google Docs uses OT with a central server; Figma uses a server-ordered, CRDT-inspired design.
How to apply it
Choose per field, not per database:
| Data | Recommended rule | Why |
|---|---|---|
| Immutable events, logs | LWW or append-only G-Set | no concurrent edits to lose |
| Profile field like display name | LWW-Register | losing a concurrent rename is acceptable |
| Likes, views, rate counters | PN-Counter or G-Counter | every increment must count |
| Cart, tags, membership | OR-Set (add-wins) | preserves concurrent adds and removes |
| Revocations, blocklists | remove-wins set | safety beats availability here |
| Shared rich text | Yjs or Automerge, or OT with a server | positions shift under concurrent edits |
| Balance, stock, unique names | no CRDT: single leader or consensus | invariant spans replicas |
Checklist before you go multi-leader:
- Can you route each key to a home region so it has one writer most of the time? Conflicts you avoid are cheaper than conflicts you resolve.
- For each mutable field, have you written down the conflict rule and confirmed with product that the outcome is acceptable?
- Do you detect concurrency with version vectors, not wall clocks?
- Do you have a plan for tombstone collection and a resync path for replicas offline past the horizon?
- Are cross-replica invariants enforced by coordination, not hoped for?
Interview questions
1. Why is last-write-wins dangerous for a shopping cart, and what would you use instead?
LWW keeps one whole version and discards the others, so any concurrent change to the cart from another device or region is lost silently, with no error. Clock skew makes it worse: a write that really happened later can lose to one stamped by a faster clock. Use an OR-Set for the items so each add carries a unique tag and a remove deletes only tags the remover observed; concurrent adds survive and the merge is deterministic. Quantities per item can be PN-Counters or LWW registers depending on whether concurrent changes should add up.
2. What are the requirements for a state-based CRDT merge, and why do they matter?
The merge must be commutative, associative and idempotent, which makes the states a join semilattice with merge as the least upper bound. Commutativity and associativity mean replicas can receive updates in any order and via any gossip path. Idempotence means duplicates are harmless. Together they guarantee that replicas that have seen the same updates converge to the same state without coordination, so the transport can be unreliable.
3. Can you implement an inventory count with a PN-Counter so it never oversells?
No. A PN-Counter guarantees convergence, not invariants. Two regions can each see 1 unit, each decrement, and converge to minus 1. Preventing oversell needs coordination for that key: route all decrements for a SKU to one leader, use a consensus-backed store, or pre-split stock into per-region quotas (escrow) so each region can decrement locally only within its own allocation and must coordinate to rebalance.
✅ Key takeaways
- Concurrent writes are normal in multi-leader and leaderless systems; detect them with version vectors, not wall clocks.
- Last write wins always converges and silently loses concurrent writes. Use it only where losing a write is acceptable.
- CRDT merges are commutative, associative and idempotent, so replicas converge regardless of order, duplicates or delay.
- OR-Sets give add-wins semantics for carts; counters need PN-Counters; text needs sequence CRDTs or OT with a server.
- CRDTs cost metadata and tombstones, and they cannot enforce invariants like non-negative stock. Those need coordination.
🧠 Check your understanding
0 / 4-
1Two regions accept concurrent writes to the same cart. The store uses last write wins with wall-clock timestamps. What is the main risk?
LWW always converges, which is why its data loss is silent: the lower-timestamp version is dropped. Non-convergence is the tempting answer but LWW is deterministic. Keeping siblings is a different strategy.
-
2Which property lets a state-based CRDT tolerate the same update being delivered three times?
Idempotence means merge(a, a) equals a, so duplicates change nothing. Commutativity handles reordering, not duplication. Causal delivery is a requirement of operation-based CRDTs, not something state-based merge needs.
-
3Replica A removes item X from an OR-Set while replica B concurrently adds X again. What does the merged set contain?
A's remove deletes only the tags it observed. B's add created a fresh tag, so X survives: add-wins. Remove-wins is a different set design. Timestamps play no role in an OR-Set, and a set never holds duplicates.
-
4Why do sequence CRDTs for text keep tombstones for deleted characters?
Inserts reference neighbouring character IDs, and a concurrent insert may reference a character another replica just deleted, so the ID must remain resolvable. Undo is a nice side effect in some editors, not the reason. Deletes are allowed; they are just represented as tombstones.
Where to go next
- Two-phase commit: the opposite approach, where replicas coordinate up front so there is never a conflict to resolve.
- Saga pattern: how to keep multi-service business processes consistent when you cannot lock across them.
- Time, clocks and ordering: the version vectors that make concurrency detection possible.
- Multi-region architecture: where active-active conflicts show up in real deployments and how to home data to avoid them.
Finished this lesson?
Mark it complete to track your progress across the roadmap.