Sub topic 10
Resolving conflicts: last-write-wins, siblings, and CRDTs
The previous chapter showed how vector clocks detect that two writes to the same key are concurrent. Detection only tells the store that a conflict exists. This chapter covers what the store does next. It assumes you can read short Python snippets, know how vector clocks are compared, and understand that a leaderless store accepts writes on several replicas without coordination.
Why conflicts happen
In a leaderless, quorum-based store, two clients can write the same key through different coordinators at nearly the same time. Neither write has seen the other, so their vector clocks are concurrent. A network partition or a sloppy quorum has the same effect. Each side accepts writes, and the replicas diverge.
When replicas later exchange data, through read repair or anti-entropy, they must reduce the divergent versions to something the client can use. There are three common strategies:
- Pick one version and discard the rest (last-write-wins).
- Keep all concurrent versions and let the application merge them (siblings).
- Use data types whose merge operation is defined so that replicas converge automatically (CRDTs).
Note that only the concurrent branch needs a strategy. Ordered versions are handled by overwriting the older one.
Last-write-wins
Last-write-wins (LWW) attaches a timestamp to every write. When versions conflict, the highest timestamp wins and the others are discarded. Cassandra uses this model by default.
def lww_merge(a: tuple, b: tuple) -> tuple:
"""Each version is (timestamp_ms, node_id, value). Highest (timestamp, node_id) wins."""
return max(a, b, key=lambda v: (v[0], v[1]))
print(lww_merge((1000, "node-a", "red"), (1003, "node-b", "blue")))
print(lww_merge((1000, "node-a", "red"), (1000, "node-b", "blue")))The second call shows tie-breaking. Without a deterministic tie-breaker, two replicas could pick different winners for equal timestamps and never converge. Here the node id breaks the tie.
LWW has real advantages:
- Reads return one value, so the client API stays simple.
- No version metadata grows per key beyond one timestamp.
- Replicas converge because the rule is deterministic.
Its costs matter just as much:
- Silent data loss. If two clients write concurrently, one write vanishes without any error.
- Clock skew. Timestamps come from physical clocks, which drift. A node whose clock runs 5 seconds ahead can overwrite a causally later write made on a correct node.
- No causality. A write that logically happened after a read can lose to an older write with a larger timestamp.
A safer LWW design uses vector clocks to detect conflicts and falls back to timestamps only for truly concurrent writes. Causally ordered writes then never lose to clock skew.
Siblings: push the decision to the application
Dynamo and Riak take a different approach. If the vector clocks are concurrent, the store keeps both versions, called siblings. A read returns all siblings together with a context, which is the merged vector clock. The client merges the values in application logic and writes the result back with that context. The new clock dominates all the siblings, so they are all superseded.
The following code implements the store-side logic. It repeats the compare function from the previous chapter so the snippet runs on its own.
def compare(a: dict, b: dict) -> str:
keys = set(a) | set(b)
a_le_b = all(a.get(k, 0) <= b.get(k, 0) for k in keys)
b_le_a = all(b.get(k, 0) <= a.get(k, 0) for k in keys)
if a_le_b and b_le_a:
return "equal"
if a_le_b:
return "before"
if b_le_a:
return "after"
return "concurrent"
def reconcile(siblings: list, new: tuple) -> list:
"""siblings and new are (clock, value). Return the surviving versions."""
survivors = []
for clock, value in siblings:
rel = compare(clock, new[0])
if rel in ("before", "equal"):
continue # the new version supersedes this one
if rel == "after":
return siblings # the new version is stale, ignore it
survivors.append((clock, value)) # concurrent, keep it
survivors.append(new)
return survivors
def merge_cart(siblings: list, coordinator: str) -> tuple:
"""Application merge for a shopping cart: union the items, then bump the clock."""
clock = {}
items = set()
for c, value in siblings:
items |= value
for node, counter in c.items():
clock[node] = max(clock.get(node, 0), counter)
clock[coordinator] = clock.get(coordinator, 0) + 1
return clock, items
s = []
s = reconcile(s, ({"a": 1}, {"milk"}))
s = reconcile(s, ({"a": 2}, {"milk", "eggs"})) # supersedes the first
s = reconcile(s, ({"a": 1, "b": 1}, {"milk", "jam"})) # concurrent with the second
print(len(s)) # 2 siblings
s = reconcile(s, merge_cart(s, "a"))
print(len(s), sorted(s[0][1])) # 1 ['eggs', 'jam', 'milk']Siblings never lose data on their own. The price is shifted to application developers:
- Every read path must handle a list of values, not one.
- The merge function must be correct. A union works for adds but resurrects deleted items, so deletes need tombstones (markers recording that an item was removed) and a rule for them.
- If clients never write back merged values, siblings accumulate and reads get larger.
- Vector clocks themselves can grow with the number of coordinators. Systems prune old entries, which can create false concurrency.
CRDTs: make the merge automatic
A conflict-free replicated data type (CRDT) is a data structure whose merge function is designed so that any replicas that have seen the same updates end in the same state, regardless of delivery order. The merge must be:
- 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 replicas can merge repeatedly, in any order, and with duplicate messages. That fits anti-entropy and read repair well.
The simplest example is the grow-only counter (G-counter). Each node increments only its own slot. The total is the sum of all slots, and merging takes the per-slot maximum.
class GCounter:
def __init__(self, node: str):
self.node = node
self.counts = {}
def increment(self, amount: int = 1) -> None:
self.counts[self.node] = self.counts.get(self.node, 0) + amount
def value(self) -> int:
return sum(self.counts.values())
def merge(self, other: "GCounter") -> None:
for node, count in other.counts.items():
self.counts[node] = max(self.counts.get(node, 0), count)
a, b = GCounter("a"), GCounter("b")
a.increment(2)
b.increment(3)
a.merge(b)
b.merge(a)
a.merge(b) # merging again changes nothing
print(a.value(), b.value()) # 5 5Two concurrent increments both survive, which LWW would not allow. Other common CRDTs include:
- PN-counter: two G-counters, one for increments and one for decrements.
- OR-set (observed-remove set): each added element carries a unique tag, and a remove deletes only the tags it has observed. A concurrent add therefore beats a remove.
- LWW-register: a CRDT version of LWW, convergent but still lossy.
CRDTs have limits. They support only operations that can be expressed as a mergeable structure. Some invariants, such as "balance never goes below zero", cannot be enforced without coordination. State-based CRDTs may also carry growing metadata such as tombstones and per-node slots.
Choosing a strategy
| Strategy | Data loss on concurrent writes | Client complexity | Metadata | Typical use |
|---|---|---|---|---|
| Last-write-wins | Yes, silently | Low | One timestamp | Caches, sessions, overwrite-only values |
| Siblings | No | High, the app merges | Vector clock plus extra values | Carts, profiles with custom merge rules |
| CRDTs | No | Medium, use the right type | Type-specific state | Counters, sets, presence, collaborative data |
Some practical rules follow from the table:
- If a lost update is unacceptable and the data fits a CRDT, use the CRDT.
- If the merge needs domain knowledge, use siblings and test the merge function directly, including with delete cases.
- If only the latest value matters, use LWW and accept the loss. Prefer server-assigned timestamps and monitor clock skew.
- If you must preserve an invariant, avoid leaderless merging for that key and consider consensus-based replication, covered later in the tutorial.
Exercise
Two replicas of a G-counter hold {"a": 4, "b": 1} and {"a": 3, "b": 2}. What is the merged state and the counter's value, and why would a last-write-wins register have given a different outcome for the same concurrent updates?
Show answer
The per-slot maximum gives {"a": 4, "b": 2}, so the value is 6. Each replica contributed an increment the other had not seen, and the merge keeps both. A last-write-wins register would keep only the version with the higher timestamp and discard the other replica's increments, so the total would be lower.
Exercise
A client reads a key and gets three siblings. It merges them and writes the result back without sending the context it received. What is likely to happen, and how should the write be made?
Show answer
The new write carries a clock that does not dominate the siblings, so the store may treat it as concurrent with them and keep it as a fourth sibling, so the conflict is never resolved. The client must send the context (the merged vector clock) from the read, so the merged value's clock supersedes all the siblings.