Sub topic 12
Resolving conflicts: last-write-wins and CRDTs
This chapter assumes you know what replication is, how eventual consistency lets replicas diverge temporarily, and how vector clocks tell ordered events from concurrent ones. You should also be able to read short Python programs.
Why conflicts happen
With eventual consistency, two clients can write the same key on different replicas at the same time, and neither replica sees the other's write first. When the replicas later exchange data, each holds a different value for the key. This is a conflict. The system has to turn two values into one, and every replica has to turn them into the same one, or the replicas never converge.
A vector clock tells you that two writes are concurrent. It does not tell you which value to keep. That choice is conflict resolution, and there are three broad strategies:
- Discard one write by using a rule, such as "latest timestamp wins".
- Keep both values (called siblings) and ask the application or the user to merge them.
- Design the data type so that any two versions merge automatically and correctly.
The first is last-write-wins. The third is the idea behind CRDTs.
Last-write-wins
Last-write-wins (LWW) attaches a timestamp to every write. When two versions of a key meet, the replica keeps the one with the larger timestamp and drops the other.
LWW is popular because it is simple. It needs no application code, stores one value per key, and always converges, provided the replicas agree on how to break ties. A common tie-break is to compare the writer's node ID when timestamps are equal.
def lww_merge(a, b):
"""Each version is a tuple: (timestamp, node_id, value)."""
return a if (a[0], a[1]) >= (b[0], b[1]) else b
v1 = (100, "A", "red")
v2 = (101, "B", "blue")
print(lww_merge(v1, v2)) # (101, 'B', 'blue')
print(lww_merge(v2, v1)) # (101, 'B', 'blue')The merge gives the same answer in either argument order. That property matters, because replicas receive updates in different orders.
What LWW loses
LWW is a deliberate decision to lose data. Consider these failure modes:
- Lost updates. If two clients write concurrently, one write is silently dropped. Neither client is told. If the writes were increments to a counter, the final count is wrong.
- Clock skew. Wall clocks on different machines disagree by milliseconds, sometimes by seconds. A node with a fast clock can win against writes that really happened later, and a write made hours after another can be overwritten if its clock is behind.
- Phantom ordering. The timestamp order is not the causal order. A client can read a value, write a new value based on it, and still lose to an older write whose timestamp happens to be larger.
- Deletes. A delete is a write. If a stale replica still holds an older value, an LWW rule can bring the deleted item back unless the delete is kept as a tombstone, a marker with its own timestamp, for long enough.
You can reduce the risk by using a hybrid logical clock, which combines physical time with a counter and never moves backward on a node. This limits the effect of skew, but it does not fix lost concurrent updates. Using a vector clock to detect concurrency and keep siblings does fix them, but then something else has to merge the siblings.
Application-level merging
Systems in the Dynamo family can return all concurrent versions on a read. The client merges them and writes back a value that supersedes them. A shopping cart is the classic example. If one replica has {book} and another has {pen}, the client merges them into {book, pen}.
This pushes correctness to the application, which is flexible but easy to get wrong. A set union merge cannot represent a removal. If the user removed the pen on one replica, a union brings it back. Each such case needs its own thought, and the merge code has to be deterministic and tolerate being run many times.
CRDTs
A conflict-free replicated data type (CRDT) is a data structure whose merge operation is built in and always produces a correct, converged result. Replicas can accept writes independently, without coordination, and exchange state later in any order.
For this to work, the merge function must satisfy three laws:
- Commutative:
merge(a, b) == merge(b, a). The order of the two arguments does not matter. - Associative:
merge(merge(a, b), c) == merge(a, merge(b, c)). Grouping does not matter. - Idempotent:
merge(a, a) == a. Receiving the same state twice does no harm.
Mathematically, states form a join-semilattice and merge is the least upper bound. In practice this means updates can be duplicated, delayed, and reordered, and the replicas still converge. That is strong eventual consistency: any two replicas that have received the same set of updates are in the same state, with no extra conflict-resolution step.
There are two main styles. State-based CRDTs (CvRDTs) ship their whole state, or a delta of it, and the receiver merges. Operation-based CRDTs (CmRDTs) ship operations, and the network layer must deliver each operation exactly once and in causal order.
Grow-only counter
A G-Counter gives each replica its own slot. A replica increments only its own slot. The value is the sum of all slots, and merge takes the maximum per slot.
def merge(a, b):
"""Merge two grow-only counters (G-Counters) held by different replicas."""
return {k: max(a.get(k, 0), b.get(k, 0)) for k in set(a) | set(b)}
def value(counter):
return sum(counter.values())
r1 = {"r1": 3}
r2 = {"r2": 2}
print(value(merge(r1, r2))) # 5
print(merge(r1, r2) == merge(r2, r1)) # TrueTaking the maximum is safe because each slot only grows and has one writer. Merging the same state twice changes nothing, so duplicate messages are harmless. Compare this with LWW on a counter. Two concurrent increments under LWW produce one increment. Under a G-Counter, both count.
Counters that decrease and sets that remove
A G-Counter cannot go down. A PN-Counter keeps two G-Counters, one for increments and one for decrements, and its value is the difference.
Sets raise the removal problem seen earlier. Common designs:
| Type | Add and remove behavior | Cost |
|---|---|---|
| G-Set | Add only. No remove. | Smallest |
| 2P-Set | An element removed once can never be added again. | Keeps a tombstone set |
| OR-Set (observed-remove) | Remove deletes only the additions the remover has seen, so a concurrent add survives. | Unique tags per add |
| LWW-Element-Set | Per-element timestamps decide add versus remove. | Inherits clock problems |
The OR-Set is the usual choice for shopping carts and similar data, because "add wins over concurrent remove" matches what most users expect.
Costs and limits of CRDTs
- Metadata growth. Tombstones, per-replica slots, and unique tags grow over time. Garbage collection usually needs some coordination, such as knowing that all replicas have seen a delete.
- Fixed semantics. A CRDT picks a merge meaning, such as add-wins, and you accept it. If your business rule is "stock can never go below zero", a PN-Counter cannot enforce it, because enforcing it needs coordination.
- No cross-key guarantees. Each CRDT converges on its own. Two CRDTs that must stay consistent with each other, such as a balance and a transaction log, do not do so automatically.
- Eventual only. A CRDT does not give linearizability. A read can return a stale state until merges arrive.
Choosing a strategy
| Situation | Reasonable choice |
|---|---|
| Overwriting a single field, loss is acceptable | LWW, ideally with a hybrid logical clock |
| Rare concurrent writes with rich merge rules | Siblings plus application merge |
| Counters, sets, collaborative editing, replicated state across regions | CRDTs |
| Invariants such as unique usernames or non-negative balances | Coordination, such as consensus, covered later |
Exercise
Two replicas each receive one increment to a counter while partitioned. The counter is stored as a single integer with LWW, so each replica writes value 1 with a different timestamp. After the partition heals, what is the counter value, and what would it be as a G-Counter with slots r1 and r2?
Show answer
Under LWW the replica with the later timestamp wins, so the counter is 1 and one increment is lost. As a G-Counter, the states are {"r1": 1} and {"r2": 1}. The merge is {"r1": 1, "r2": 1}, and the value is 2, so both increments are kept.
Exercise
A merge function returns the larger of two integers. Does it satisfy the three CRDT merge laws? Would a merge that returns the average of two integers?
Show answer
Max is commutative, associative, and idempotent, so it is a valid merge. The average is commutative and idempotent, but not associative. For example, the average of (avg(0, 4), 8) is 5, and the average of (0, avg(4, 8)) is 3. So replicas that merge in different groupings can end in different states, and the average is not a valid CRDT merge.