Sub topic 10
Resolving conflicts: last-write-wins, siblings, and CRDTs
This chapter assumes you know how vector clocks detect concurrent writes (the previous chapter) and how replicas accept writes independently. Detecting a conflict is only half the job. The store must also decide what the client sees afterward.
The problem
Two clients write the same key at the same time on different replicas. The vector clocks compare as concurrent, so neither value supersedes the other. The store has three broad options: pick a winner, keep both, or merge them automatically.
Last-write-wins
Last-write-wins (LWW) attaches a timestamp to each write and keeps the largest. It is simple, needs no client logic, and always leaves one value.
Its weakness is data loss. Clocks on different machines drift, so the "last" write may not be the latest in real time. The losing write is discarded silently, even when it was a valid update to a different part of the value. LWW suits data where overwriting is acceptable, such as caches or session heartbeats.
Siblings
With siblings, the store keeps every concurrent value and returns all of them on a read, along with a vector clock that covers them. The client merges them and writes the result back with that clock. The new write descends from all siblings, so they are removed.
This preserves every update, but the application must supply merge logic. A shopping cart is the classic case: merging by union keeps every added item.
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 merge_clocks(a: dict, b: dict) -> dict:
return {k: max(a.get(k, 0), b.get(k, 0)) for k in set(a) | set(b)}
def resolve_cart(siblings):
"""siblings: list of (clock, set_of_items). Returns merged clock and items."""
clock, items = {}, set()
for c, value in siblings:
clock = merge_clocks(clock, c)
items |= value
return clock, items
siblings = [({"a": 2, "b": 1}, {"book", "pen"}), ({"a": 1, "b": 2}, {"book", "lamp"})]
print(compare(siblings[0][0], siblings[1][0])) # concurrent
print(resolve_cart(siblings))Union has a known flaw: if a client removes an item on one sibling, the merge can bring it back. The merge function must be designed with deletes in mind.
CRDTs
A conflict-free replicated data type (CRDT) is a data structure whose merge operation is commutative, associative, and idempotent. Replicas can merge in any order, any number of times, and still converge to the same state, so no client intervention is needed.
A grow-only counter is the simplest example. Each node increments only its own slot. The merge takes the per-node maximum, and the value is the sum.
class GCounter:
def __init__(self, node: str):
self.node = node
self.counts = {}
def increment(self, n: int = 1):
self.counts[self.node] = self.counts.get(self.node, 0) + n
def merge(self, other: "GCounter"):
for k, v in other.counts.items():
self.counts[k] = max(self.counts.get(k, 0), v)
def value(self) -> int:
return sum(self.counts.values())
a, b = GCounter("a"), GCounter("b")
a.increment(2)
b.increment(3)
a.merge(b)
b.merge(a)
print(a.value(), b.value()) # 5 5Choosing a strategy
| Strategy | Data loss | Client work | Typical use |
|---|---|---|---|
| Last-write-wins | Possible | None | Caches, sessions |
| Siblings | None | Merge logic | Carts, documents |
| CRDTs | None | Pick a type | Counters, sets, presence |
Exercise
Two replicas hold siblings for a cart: {"book", "pen"} and {"book", "lamp"}. A client merges them by union and writes back with the merged clock. What does the store keep, and why are the old siblings dropped?
Show answer
It keeps one value, {"book", "pen", "lamp"}. The merged clock is greater than or equal to both sibling clocks in every component, so the new write descends from both and supersedes them.