Conflict Resolution and CRDTs
What happens when two replicas accept different writes to the same data at the same time, and how to merge them safely.
What is it?
In a single-leader system, all writes for a key go through one node, which puts them in order. Multi-leader (one leader per region) and leaderless (Dynamo-style: Cassandra, Riak, DynamoDB's ancestor) systems let several replicas accept writes independently. That keeps writes fast and available during partitions, but two clients can now update the same key on different replicas at the same time. Those writes are concurrent: neither one knew about the other.
Someone must decide what the final value is. The options:
- Last-write-wins (LWW): attach a timestamp and keep the highest. Simple, but it silently discards the other writes, and with skewed clocks the "last" write may not even be the latest in real time. - Detect and keep siblings: track causality (with version vectors) so the database knows two values are concurrent and returns both, letting the application merge them. - Merge automatically: use data types whose merge is mathematically guaranteed to converge, called CRDTs (conflict-free replicated data types).
Leaderless systems also need rules for reads and writes across replicas: quorums (R + W > N), plus read repair and hinted handoff to bring stragglers back in sync.
Explain like I'm 10
Two siblings edit the same shopping list on paper copies while apart. Last-write-wins means you throw away whichever list was written earlier, losing items. A CRDT shopping list is like each person only ever adding stickers with their initials; merging is just combining all the stickers, and nothing gets lost no matter who merges first.
Examples
G-counter: a grow-only counter CRDT
// Each replica only increments its own slot.
type GCounter = Record<string, number>; // replicaId -> count
function increment(counter: GCounter, replicaId: string): GCounter {
return { ...counter, [replicaId]: (counter[replicaId] ?? 0) + 1 };
}
function value(counter: GCounter): number {
return Object.values(counter).reduce((sum, count) => sum + count, 0);
}
// Merge takes the max per replica: commutative, associative, idempotent.
function merge(a: GCounter, b: GCounter): GCounter {
const merged: GCounter = { ...a };
for (const [replicaId, count] of Object.entries(b)) {
merged[replicaId] = Math.max(merged[replicaId] ?? 0, count);
}
return merged;
}
// Replica A sees 3 likes, replica B sees 2, concurrently:
// a = { A: 3 }, b = { B: 2 } → merge = { A: 3, B: 2 }, value = 5
// Merging the same state twice changes nothing.Summing raw counts on merge would double-count when states are re-merged; taking the max per replica makes merging safe to repeat. A PN-counter (supports decrement) is two G-counters: increments minus decrements.
Comparing vector clocks
type VectorClock = Record<string, number>;
function compare(a: VectorClock, b: VectorClock):
"before" | "after" | "equal" | "concurrent" {
const replicaIds = new Set([...Object.keys(a), ...Object.keys(b)]);
let aHasGreater = false;
let bHasGreater = false;
for (const id of replicaIds) {
const countA = a[id] ?? 0;
const countB = b[id] ?? 0;
if (countA > countB) aHasGreater = true;
if (countB > countA) bHasGreater = true;
}
if (aHasGreater && bHasGreater) return "concurrent"; // a real conflict
if (aHasGreater) return "after";
if (bHasGreater) return "before";
return "equal";
}
compare({ A: 2, B: 1 }, { A: 1, B: 1 }); // "after": safe to overwrite
compare({ A: 2, B: 0 }, { A: 1, B: 1 }); // "concurrent": keep bothUnlike a timestamp, a vector clock can tell 'newer' apart from 'happened independently'.
How it works
Lamport clocks. Each node keeps a counter. Increment it on every local event; send it with every message; on receive, set counter = max(local, received) + 1. Ties are broken by node id, giving a total order consistent with causality: if A happened before B, then L(A) < L(B). The converse doesn't hold, so Lamport timestamps can't tell you whether two events were concurrent.
Vector clocks / version vectors. Each node keeps one counter per node. A version V1 happened before V2 if every entry of V1 is ≤ the matching entry in V2 and at least one is smaller. If neither dominates, the versions are concurrent, which is exactly a conflict. Amazon's Dynamo paper used vector clocks and returned concurrent siblings to the client to merge; Riak uses dotted version vectors, a refinement that avoids sibling explosion.
Last-write-wins. Cassandra resolves per column using write timestamps (highest wins). It's cheap and convergent, but concurrent writes are dropped, and a node whose clock runs ahead can make its writes "win" over later ones. Safe only for immutable data or keys written by one writer at a time.
CRDTs come in two flavours. State-based CRDTs ship whole states and merge with a function that is commutative, associative and idempotent (a join semilattice), so replicas converge regardless of delivery order or duplication. Operation-based CRDTs ship operations that must commute, and need reliable, causally ordered delivery. Common types:
- G-counter / PN-counter: counters (likes, views). - G-set / 2P-set: add-only set; set with a remove tombstone that can't be re-added. - OR-set (observed-remove set): each add gets a unique tag; a remove deletes only the tags it has observed. A concurrent add has a new tag, so it survives: add wins. - LWW-register, MV-register (keeps concurrent values), sequence CRDTs for collaborative text (RGA, Yjs and Automerge's data types).
Quorums in leaderless stores. Data lives on N replicas. A write waits for W acknowledgements; a read queries R replicas and takes the newest version. If R + W > N, every read set overlaps every write set in at least one replica, so a read sees the latest successful write. With N = 3, W = 2, R = 2 is the classic choice. W = 1/R = 1 maximizes speed and availability at the cost of stale reads. Even with R + W > N you don't get linearizability: concurrent writes, writes that failed on some replicas but succeeded on others, and sloppy quorums all leak anomalies.
Read repair. When a read sees replicas returning different versions, the coordinator writes the newest version back to the stale ones. It only fixes keys that get read.
Anti-entropy. A background process compares replicas (Cassandra and Dynamo use Merkle trees so they can compare hashes of ranges instead of every key) and copies missing data, fixing keys that are rarely read.
Hinted handoff and sloppy quorums. If a replica for a key is down, the coordinator writes to another healthy node, along with a hint naming the intended owner. When the owner returns, the hint is replayed to it. This keeps writes available, but a "quorum" that includes stand-in nodes no longer guarantees overlap with a later read quorum.
Concurrent writes in a leaderless store (N = 3, W = 2, R = 2)
Client 1: put(cart, [milk]) → R1 ✓ R2 ✓ version {R1:1}
Client 2: put(cart, [eggs]) → R2 ✓ R3 ✓ version {R3:1}
(neither saw the other: concurrent)
Read with R = 2 hits R1 and R3:
R1 → [milk] {R1:1}
R3 → [eggs] {R3:1}
LWW: keep one by timestamp, lose the other
Version vector: return both siblings, app merges → [milk, eggs]
CRDT (OR-set): merge automatically → {milk, eggs}
Read repair then writes the merged value back to stale replicas.Why does it exist?
Coordinating every write through one leader costs latency (cross-region round trips) and availability (no writes while the leader is unreachable). Systems that accept writes anywhere, such as multi-region databases, offline-first apps and collaborative editors, must handle the resulting conflicts. Clocks and CRDTs make conflicts detectable or impossible, and quorum tricks keep replicas converging.
When to use it
- Multi-region active-active writes where local latency matters more than global ordering. - Offline-first and collaborative apps (notes, docs, whiteboards) that sync later: CRDTs are the natural fit. - High-write, availability-first data such as counters, carts, presence, feature usage, where merges have obvious meaning. - Tunable consistency stores (Cassandra, Riak, DynamoDB) where you pick R and W per use case.
When not to use it
- Invariants that need coordination: unique usernames, account balances that must never go negative, seat reservations. No merge function can enforce "at most one" without coordination; use a single leader or consensus for those keys. - When stale reads are unacceptable and you need linearizability; quorum tuning alone doesn't provide it. - Don't use LWW on data that multiple clients update concurrently unless losing writes is acceptable.
Common mistakes
Using last-write-wins on mutable shared data and not noticing the lost updates, especially with wall-clock timestamps from skewed machines.
Believing R + W > N gives strong consistency. Sloppy quorums, partial write failures and concurrent writes still produce stale or non-linearizable reads.
Writing a 'CRDT' whose merge isn't idempotent (e.g. summing counters on merge), so retries and re-syncs inflate values.
Expecting a CRDT to preserve business invariants. An OR-set converges, but it can't stop two regions from both selling the last item.
Ignoring tombstones and metadata growth: deleted items, version vectors and CRDT tags pile up and need garbage collection.
Practice exercises
- Easy:
Given N = 5, list three (R, W) combinations that satisfy R + W > N, and describe the latency and availability trade-off of each.
- Medium:
Implement a PN-counter using two G-counters, with increment, decrement, value and merge. Show that merging in any order gives the same result.
- Hard:
Two replicas of an OR-set start with {apple}. Replica A removes apple while replica B concurrently adds apple again. Walk through the tags each replica holds and show why the merged result contains apple. Then design how you'd garbage-collect the tags.
Interview questions
When do write conflicts happen?
When more than one replica can accept writes for the same key (multi-leader or leaderless replication) and two writes happen concurrently, meaning neither was aware of the other.
What's wrong with last-write-wins?
It resolves conflicts by keeping the highest timestamp and silently discarding the rest, so concurrent updates are lost. With wall-clock timestamps, clock skew can also make an older write win.
What is a Lamport clock and what can't it do?
A logical counter incremented on each event and set to max(local, received) + 1 on receive. It guarantees that causally earlier events get smaller timestamps, but a smaller timestamp doesn't imply causality, so it can't detect concurrency.
How do vector clocks detect concurrency?
Each version carries a counter per node. If one vector is less than or equal in every entry, it happened before the other. If each is greater in some entry, the versions are concurrent and conflict.
What is a CRDT?
A replicated data type whose updates or merge function are commutative, associative and idempotent, so replicas that have seen the same updates converge to the same state without coordination.
How does an OR-set decide between a concurrent add and remove?
Every add creates a unique tag; a remove deletes only the tags it has observed. A concurrent add's tag wasn't observed, so it survives and the element remains: add wins.
What does R + W > N guarantee?
That every read quorum overlaps every write quorum in at least one replica, so a read can see the most recent successfully acknowledged write. It doesn't guarantee linearizability.
Explain read repair vs anti-entropy.
Read repair fixes stale replicas when a read notices divergent versions, so it only repairs keys that are read. Anti-entropy is a background comparison (often using Merkle trees) that repairs all data, including cold keys.
What is hinted handoff, and what does it cost?
When an owner replica is down, another node accepts the write plus a hint and forwards it when the owner recovers. It keeps writes available, but the resulting sloppy quorum may not overlap a later read quorum, so reads can be stale.
A product team wants active-active multi-region inventory with no oversells. How do you approach it?
Inventory decrements have a global invariant, so pure CRDTs or LWW can't prevent oversells. Options: route each SKU's writes to a home region (single leader per key), use consensus across regions for scarce items, or pre-allocate stock quotas to each region (escrow) so regions decrement locally within their quota and rebalance asynchronously.