Sub topic 9
Resolving conflicts: last-writer-wins, version tracking and CRDTs
This chapter assumes you know the basics of asynchronous cross-region replication and why concurrent writes happen in an active-active design. It also assumes you can read short Python programs. You should know that two regions can accept a write to the same item before either sees the other's change.
Why conflicts happen
In an active-active system, each region accepts writes and replicates them to the others asynchronously. If a user in Europe and a user in the US update the same record within the replication lag window, each region applies its own write first. When the replicated writes arrive, the regions disagree about the current value.
Two writes are concurrent when neither writer saw the other's write before writing. Concurrent does not mean simultaneous. It means there is no causal order between them. Real timestamps can say one write came "later", but that does not mean the second writer knew about the first.
A conflict resolution strategy must meet two requirements:
- Convergence: once all updates have been delivered, every region holds the same value.
- Order independence: the result must not depend on the order in which updates arrive at each region.
The strategies below differ in how much information they keep and how much data they may lose.
Strategy 1: last-writer-wins
Last-writer-wins (LWW) keeps the version with the highest timestamp and discards the rest. It is simple, needs no coordination, and is the default in several multi-region databases.
Timestamps can tie, so you need a deterministic tie-breaker. Without one, two regions may each keep their own version on a tie and never converge. Using the region name as a secondary key gives every region the same answer.
def lww_merge(a, b):
"""Each version is a (timestamp, region, value) tuple.
The higher timestamp wins; the region name breaks ties
so every region picks the same winner."""
return a if (a[0], a[1]) >= (b[0], b[1]) else b
from_eu = (1700000005.2, "eu-west-1", "blue")
from_us = (1700000005.2, "us-east-1", "green")
print(lww_merge(from_eu, from_us)) # (1700000005.2, 'us-east-1', 'green')
print(lww_merge(from_us, from_eu)) # same result in either orderBoth calls return the US version, so the merge is order-independent. The tie-breaker is arbitrary but consistent.
Where LWW goes wrong
- Silent data loss. The losing write disappears. Nothing records that a conflict happened, and the user who wrote it receives a success response.
- Clock skew. Timestamps come from machine clocks. A region whose clock runs ahead wins every conflict, even when its write was causally older. Clock synchronization services keep drift small, but they do not remove it.
- Lost updates on partial changes. If one writer changes the email field and another changes the phone field on the same row, whole-row LWW keeps only one of the two changes. Per-field timestamps reduce this problem but add metadata.
- Non-commutative operations. LWW suits "set this value" operations. It is a poor fit for "add 1" operations, where both increments should count.
LWW is acceptable when the data is a overwritable snapshot: a user's last-seen time, a cached profile, or a status flag where the latest value is the only one that matters.
Strategy 2: version tracking
When losing a write is not acceptable, you need to detect conflicts instead of guessing. Version tracking records causal history so the system can tell "B came after A" from "A and B are concurrent".
Version vectors
A version vector is a map from region to a counter. Each region increments its own counter when it writes. To compare two vectors a and b:
- If every counter in
ais less than or equal to the matching counter inb, and at least one is smaller, thenahappened beforeb. Keepb. - If the reverse holds, keep
a. - If each has some counter larger than the other, the writes are concurrent. This is a true conflict.
def compare(a, b):
"""Return 'before', 'after', 'equal' or 'concurrent' for version vectors."""
regions = a.keys() | b.keys()
a_le_b = all(a.get(r, 0) <= b.get(r, 0) for r in regions)
b_le_a = all(b.get(r, 0) <= a.get(r, 0) for r in regions)
if a_le_b and b_le_a:
return "equal"
if a_le_b:
return "before"
if b_le_a:
return "after"
return "concurrent"
print(compare({"eu": 1, "us": 0}, {"eu": 2, "us": 0})) # before
print(compare({"eu": 2, "us": 0}, {"eu": 1, "us": 1})) # concurrentA version vector tells you that a conflict exists. It does not tell you how to fix it. When the result is "concurrent", the system must do one of three things:
- Store both values as siblings and return them to the application on the next read. The application merges them and writes back a version that supersedes both.
- Apply a merge function defined for the data type.
- Fall back to LWW for that item, which accepts data loss.
Costs of version tracking
- Metadata grows with the number of writers. With a handful of regions this is small. Tracking per client instead of per region can grow without bound unless you prune it.
- Siblings push merge logic into application code, and that code must be correct for every possible combination of siblings.
- Reads become more complex because a read can return several values.
Strategy 3: CRDTs
A conflict-free replicated data type (CRDT) is a data structure designed so that any two replicas can be merged without conflicts. The merge function is commutative (order of arguments does not matter), associative (grouping does not matter), and idempotent (merging the same state twice changes nothing). Those three properties guarantee convergence regardless of delivery order or duplicate delivery.
The simplest example is a grow-only counter, or G-counter. Each region increments only its own slot. Merging takes the per-region maximum. The counter's value is the sum of all slots.
def merge_counters(a, b):
"""G-counter CRDT: each region increments only its own slot.
Merging takes the per-region maximum."""
return {r: max(a.get(r, 0), b.get(r, 0)) for r in a.keys() | b.keys()}
def value(counter):
return sum(counter.values())
eu = {"eu-west-1": 3, "us-east-1": 1}
us = {"eu-west-1": 2, "us-east-1": 4}
merged = merge_counters(eu, us)
print(merged, value(merged)) # {'eu-west-1': 3, 'us-east-1': 4} 7Here the EU replica has seen only one of the US region's increments, and the US replica has seen only two of the EU region's. After the merge, both regions' increments are counted. Merging in the other order, or merging twice, gives the same result.
Other common CRDTs
| Type | Behavior | Typical use |
|---|---|---|
| G-counter | Increment only | Page views, event counts |
| PN-counter | Two G-counters, one for increments and one for decrements | Inventory adjustments, likes and unlikes |
| G-set | Add only | Tags, seen-item lists |
| OR-set | Add and remove, where a remove only affects the adds it has observed | Shopping carts, membership lists |
| LWW-register | A single value with a timestamp | Simple fields, with the LWW trade-offs |
Limits of CRDTs
- They cannot enforce global invariants. A PN-counter can tell you stock is at 3 in each region, but it cannot stop both regions from selling the last item at once. Constraints such as "balance never goes below zero" or "usernames are unique" need coordination or a single write owner.
- Metadata grows. An OR-set keeps tombstones for removed elements, and counters keep one slot per region. Garbage collection requires care.
- The model is narrow. Your data must fit an available CRDT type. Mapping a complex business record onto CRDTs takes design effort.
- Semantics may surprise users. In an OR-set, a concurrent add and remove of the same item results in the item being present. That is correct for the type but may not match what the user intended.
Choosing a strategy
| Question | If yes | If no |
|---|---|---|
| Is the data a snapshot where the latest value is all that matters? | LWW | Keep reading |
| Are the operations additive or set-like, such as counts or membership? | CRDT | Keep reading |
| Can the application merge two versions meaningfully? | Version vectors with siblings | Avoid concurrent writes with write ownership |
| Must a global invariant always hold, such as a unique value or a non-negative balance? | Single write owner or a coordinated write | Any of the above |
Resolving conflicts is the last line of defense. The cheapest conflict is one that never happens, so partition writes by owner where you can, as the previous chapter describes, and use these strategies for the data that remains shared.
Exercise
Two regions each start with the version vector {"eu": 1, "us": 1}. The EU region then writes and produces {"eu": 2, "us": 1}. The US region writes and produces {"eu": 1, "us": 2}. What does compare return for these two vectors, and what must the system do next?
Show answer
It returns "concurrent", because each vector has a counter larger than the other's (eu: 2 vs 1, us: 1 vs 2). Neither write happened before the other. The system must resolve the conflict by keeping both values as siblings for the application to merge, by applying a type-specific merge function, or by falling back to LWW and accepting that one write is lost.
Exercise
You store a "likes" count for each post and use last-writer-wins on the whole number. Describe how a like can be lost, and name a better data type for this field.
Show answer
If the EU region has count 10 and the US region has count 10, and each records one new like, both write 11. LWW keeps one 11 and drops the other, so the true total of 12 is lost. A PN-counter (or a G-counter if likes cannot be removed) stores one slot per region and merges by per-region maximum, so both increments are counted.