Conflict Resolution

On this page

The crux of a conflict is that two operations are generated based on their respective known states, and the system has not pre-ordered them into a common sequence. Arrival order on the network does not equate to causal order in the business logic. Before resolving conflicts, one should clarify the intent expressed by each operation and which outcome aligns with product semantics.

Overwrite Updates and Merge Operations Express Different Intentions

Setting a like count "to 11" is different from "incrementing by 1". If two clients start from 10 and both write 11, saving 11 may adhere to assignment semantics but loses the intent of one like. To preserve both likes, one should record independent operations or use an appropriate counting structure.

Similarly, directly taking the union of shopping carts preserves concurrent additions but may cause previously deleted items to reappear. "Preserving all changes" is not a complete rule; one must also define the relationship between deletion and re-addition.

LWW: Selecting a Winner Using a Total Order

Last-Write-Wins (LWW) assigns sortable keys to versions that allow for total ordering, such as (timestamp, writer_id), selecting the version with the largest key. The second field is used to deterministically break ties for identical timestamps; all replicas must use the same comparison rules.

Its advantage is a single result and simple merging; the cost is that the value of the losing concurrent operation is overwritten. "Last" refers to the largest sort key, not necessarily the person who operated last in reality. Nodes with faster physical clocks may consistently override others; logical time does not equal real time.

LWW is suitable for fields where overwriting based on specified priority rules is acceptable. It does not automatically merge content modified by two different editors, nor can it directly save multiple +1 intents as a count result after assignment.

Version Vectors: Identifying Causality and Concurrency

Taking two writers, A and B, as an example, the version vector [a,b] indicates the logical update progress of each writer included in that version. If for every component vᵢ≤wᵢ and at least one is strictly less, denoted as v<w; this means w has inherited the causal history of v in this model.

Starting from a common version [1,0], A updates locally to get [2,0]; B observes the old version and updates to get [1,1]. The former has a larger A component, the latter has a larger B component; the two vectors are incomparable, indicating concurrency. One cannot determine order by summing them (2 and 2).

During merging, one can first take the component-wise maximum [2,1] to represent the observed history, and then the writer performing the new update increments its own component. Merging causal context does not equal merging business values: addresses, shopping carts, and permissions still require their own rules. Version vectors help detect conflicts but do not make product decisions.

This simplified model assumes each writer has a reliable, monotonic identity and counter. Reusing old identities and resetting counters after node reinstallation breaks the meaning of the version vector. The growth in the number of writers also increases metadata costs.

CRDT: Embedding Merge Semantics into Data Structures

CRDTs use constrained data representations and update rules to allow replicas receiving the same updates to converge to the same state. They do not guarantee that offline replicas immediately know about remote updates, nor do they guarantee that arbitrary business rules can hold without coordination.

State-based CRDTs typically organize state as a semilattice: updates proceed monotonically along a partial order, and merging takes the least upper bound. The commutativity, associativity, and idempotency of merging ensure that repeated and out-of-order state propagation does not change the final result. A function satisfying these three laws alone is not enough; the update rules and state partial order must also align.

Operation-based CRDTs propagate operations, relying on their specified reliable delivery, deduplication, or causal delivery conditions to make concurrent operations that need to be exchanged commutative. One cannot directly apply the repeated delivery allowed by a state-based implementation to a generic operation-based implementation that simply "adds 1 upon receiving a message."

G-Counter and PN-Counter: Saving Contributions by Writer

In a G-Counter, each writer only increments its own component, reading sums all components, and merging takes the component-wise maximum. Suppose A is currently [3,0] and B is [1,2]; merging yields [3,2], with a value of 5. It is not adding the two local totals of 3 and 3 to get 6, because A's single increment already exists in both states.

Repeatedly merging [1,2] still results in [3,2]; changing the merge order yields the same result. This explains why recording "where each writer has cumulatively reached" avoids double counting. However, before receiving B's state, the 3 read by A is only its known result, not the real-time global total.

PN-Counter uses two G-Counters to record increments P and decrements M separately, reading sum(P)-sum(M). The underlying two states still only grow, while the visible value can increase or decrease.

However, PN-Counter does not guarantee non-negative inventory. If inventory is 1, and both locations deduct 1 concurrently, merging can correctly converge to -1. If overselling is not allowed, coordinated checks are needed, or consumable quotas must be pre-allocated and managed using bounded counting protocols for quota transfer; convergence itself does not preserve this constraint.

Why Merging Results in -1 When Both Locations "Check for 1 Remaining"

Initially, the increment component only has seed=1. Before A and B see each other's decrements, they each generate one decrement. The remaining inventory seen locally by each is 0, but after merging the two decrements, both must be preserved:

P = {"seed": 1}
minus_A, minus_B = {"A": 1}, {"B": 1}
assert sum(P.values()) - sum(minus_A.values()) == 0
assert sum(P.values()) - sum(minus_B.values()) == 0
merged_minus = {writer: max(minus_A.get(writer, 0), minus_B.get(writer, 0))
                for writer in minus_A.keys() | minus_B.keys()}
assert sum(P.values()) - sum(merged_minus.values()) == -1

# Pre-allocate the single consumable quota to A; each location can only consume its own quota.
rights = {"A": 1, "B": 0}
def consume_local(node):
    if rights[node] == 0:
        return False
    rights[node] -= 1
    return True

assert consume_local("A")
assert not consume_local("B")
assert not consume_local("A")
assert sum(rights.values()) == 0
Converging counts and preventing overselling are two different conditions Shared Old View: Inventory 1 Both A and B think they can deduct Deduct 1 Separately, Then Merge Final -1: Result converges but oversold Pre-allocation: A=1, B=0 Total quota is 1 A can deduct, B has no quota Constraint preserved, B may need to wait Quota transfers must also prevent double spending; the example does not implement a complete bounded counting protocol.

The quota method sacrifices some immediate availability: if A still has quota but B is network-isolated, B cannot pretend it can sell. It can wait, reject, or request a transfer from A when allowed, but the transfer process must prevent the same quota from being used in both locations simultaneously. The dictionary above only demonstrates a simplified model of pre-allocation and atomic local deduction, without implementing distributed transfer, persistence, or request deduplication. For complete bounded counting design, refer to the Numeric Invariants Paper.

OR-Set: Deleting Observed Add Tags

A state-based OR-Set that is easy to understand assigns a unique tag to each addition, maintaining a set of added tags A and a set of deleted tags T. An element exists if and only if it has at least one add tag not in T. When deleting an element, only record the tags of that element that have been locally observed.

Observed-Remove: Can only delete observed additions Initial: Both ends know (x, t1) A deletes x Records deletion of t1 B concurrently adds x Generates new tag t2 Merge: t1 deleted, t2 survives → x exists A did not observe t2 when deleting, so it cannot delete this concurrent addition.

Merging can take the union of A and T separately. In the diagram above, deleting t1 does not affect the concurrently generated t2, so it appears that the concurrent addition wins; if A observes t2 first and then deletes x, then both t1 and t2 can be deleted, and finally x does not exist. This distinction comes from causality, not from whether messages happened to arrive first or last.

Tombstones in teaching implementations will grow indefinitely. Cleanup requires proving that old tags will not reappear from delayed messages, offline replicas, or backups; practical optimized implementations can compress metadata using causal context. One cannot unconditionally clear them just because "deletion happened days ago."

Running an OR-Set with Tombstones Preserved

To clarify the semantics, the following uses immutable sets to save all add tags and delete tags. New tags are provided by "writer unique identity + monotonic sequence number"; merging only propagates existing tags, not regenerating them. The model assumes that even across replicas, identical tags are not generated; functions can only check for duplicates they have already seen.

from dataclasses import dataclass
from itertools import permutations

@dataclass(frozen=True)
class ORSet:
    adds: frozenset = frozenset()  # (element, tag)
    removed: frozenset = frozenset()

    def add(self, element, tag):
        if tag in self.removed or any(t == tag for _, t in self.adds):
            raise ValueError("New additions must use unused tags")
        return ORSet(self.adds | {(element, tag)}, self.removed)

    def remove(self, element):
        observed = {tag for item, tag in self.adds if item == element}
        return ORSet(self.adds, self.removed | observed)

    def merge(self, other):
        return ORSet(self.adds | other.adds, self.removed | other.removed)

    def values(self):
        return {item for item, tag in self.adds if tag not in self.removed}

base = ORSet().add("x", "A:1")
left = base.remove("x")
right = base.add("x", "B:1")
third = base.add("y", "C:1")
for order in permutations((left, right, third)):
    merged = ORSet()
    for state in (*order, order[0]):  # Change order and repeat propagation
        merged = merged.merge(state)
    assert merged.values() == {"x", "y"}
    assert merged.removed == {"A:1"}

# After observing the concurrent addition, deleting again can delete both x tags.
deleted = merged.remove("x")
assert deleted.values() == {"y"}
assert deleted.removed == {"A:1", "B:1"}
assert deleted.merge(right).values() == {"y"}  # Late old state does not revive x
assert deleted.add("x", "A:2").values() == {"x", "y"}

# Clearing delete tags makes old add records immediately visible again.
assert ORSet(deleted.adds, frozenset()).values() == {"x", "y"}

The first deletion only knows about A:1, so it has no right to delete B:1; the second deletion has already observed both tags, allowing x to disappear. Using A:2 to re-add afterwards expresses a new business operation. The three results are determined by the causal context of the operations; exchanging the order of network message arrival does not change them.

In this naive representation, both adds and removed only grow, filtering tags only during queries, which makes it easy to see "how monotonic metadata produces a deletable visible set." The last assertion shows that arbitrarily clearing tombstones does not even require waiting for remote messages to restore locally preserved old additions. Production implementations can compress metadata but must retain sufficient causal evidence; optimization directions can be found in An Optimized Conflict-Free Replicated Set.

If the same business "add to cart" request generates a new tag upon retry, it becomes a second addition. The idempotency of OR-Set for duplicate state propagation does not recognize that two new tags actually come from the same user request; business request IDs still need to be handled separately.

What is Deleted Are Add Tags, Not Just a Name

Using tags instead of a single switch to represent x allows seeing what concurrent deletion actually covers. First, add a new tag in B, then let A (which has not yet synced) delete; after merging, the new tag remains. If merging happens first, letting A see the new tag before deleting, the result is different. The two results come from different observed sets, not from the merge function favoring one side.

Preparing the visual
What is Deleted Are Add Tags, Not Just a Name

OR-Set deletes locally observed add tags. Concurrently added tags that were not observed can still survive; only after observing again can they be overwritten.

Check Semantics When Choosing Rules, Not Just Convergence Ability

Data or ConstraintSemantics to Clarify
Personal Settings FieldsIs concurrent overwriting acceptable, how is the winner determined
Likes or StatisticsIs it only increment, is deduplication to business events needed
SetsWho wins between concurrent add and delete, can re-addition occur
Text EditingHow character identity, position, and deletion are expressed, how formats are merged
Inventory, Unique Names, Fund LimitsWhich operations must be coordinated, can local permissions be allocated

A CRDT counter will not automatically recognize that "a user repeatedly sent the same like." Underlying merge deduplication and business request deduplication are different layers; the latter still requires stable event identifiers or other business rules.

Continue Reading: Replication Strategies, Anti-Entropy and Data Repair.

References

Keywords: conflict resolution, LWW, version vector, CRDT, G-Counter, PN-Counter, OR-Set, convergence