Saltar al contenido principal

Finding the One Key That Drifted: Anti-Entropy with Merkle Trees

· 10 min de lectura
Clustron Team
Ingeniería de Sistemas Distribuidos

Replication is supposed to keep every copy of a partition identical, and most of the time it does. The owner applies a write, forwards it to the replicas, waits for the acknowledgements it needs, and moves on. But the forwarding happens over an unreliable network, and unreliable networks drop things. A replication message is lost and never retried to completion. A replica is briefly down and misses the writes that land while it is gone. A short partition lets the owner accept writes its replica cannot see, and by the time the partition heals the two have quietly diverged on the keys that changed during the gap.

Each of these is rare, and each leaves the same residue: two replicas of the same partition, holding millions of keys, that agree on all but a tiny handful. Nothing is obviously broken — both nodes are up, both answer reads, both report healthy. The divergence only surfaces when a client happens to read the stale copy and gets an old value, which may be hours or days later, long after the cause is gone. What catches this class of drift is not more careful replication; it is a background reconciliation process that assumes divergence will happen and continuously repairs it. The name for that process is anti-entropy.

The obvious way to reconcile two replicas is to compare them key by key. For a partition with a few million keys, that means reading every key and its version on both sides and shipping them across the wire — a full dataset transfer, performed periodically, to discover that a dozen keys are wrong. The cost is wildly out of proportion to the result, and it scales with the data you have rather than the drift you are looking for. A Merkle tree fixes exactly that mismatch.

A tree of hashes over the keyspace​

A Merkle tree is a hash tree built over the data. Divide the partition's keyspace into contiguous ranges — the leaves of the tree — and make each leaf a hash of the keys and versions that fall in its range. Each internal node is the hash of its children, so a parent summarizes everything beneath it, and the single hash at the root summarizes the entire partition. The crucial property is that the root hash changes if and only if something beneath it changed: two replicas with identical data compute the identical root, and two replicas that differ anywhere compute different roots.

That property turns reconciliation into a guided descent. Two replicas start by exchanging just their root hashes. If the roots match, the replicas are provably identical and the comparison is over — one hash each, regardless of whether the partition holds a thousand keys or ten million. If the roots differ, each replica sends the hashes of the root's children, and they compare: any subtree whose hashes match is identical on both sides and is pruned — never descended into — while any subtree whose hashes differ is descended. Repeat down each divergent branch, and the walk converges on exactly the leaf ranges that contain drifted keys, touching only the path from the root to those leaves.

rootroots differ → descend=match≠··pruned — whole subtree skipped=≠the one range that driftedexchange only these keys + versionsmatch → prunedmillions of keys reconciled by walking one root-to-leaf path

Reconciling what you find​

The descent ends at one or more leaf ranges known to differ, and only now does any key data cross the wire — the keys and their versions within those specific ranges, not the whole partition. With the differing keys in hand, each side applies the same deterministic rule to decide the winner, and that rule is the same one that resolves any replication conflict: compare versions and keep the one that happened later. A per-key monotonic version or a hybrid logical clock gives a total order that both replicas evaluate identically, so last-write-wins converges — both sides independently arrive at the same surviving value without a coordinator.

// Reconcile partition P between this replica and a peer, cheaply.
var mine = merkle[P]; // my hash tree over P's key ranges
var peer = RequestRootHash(peerNode, P);
if (mine.Root == peer) return; // identical — one hash exchanged, done

// Roots differ: walk down, pruning every subtree whose hashes match.
foreach (var range in mine.DivergentLeaves(peerNode)) { // O(log n) comparisons per diff
var mineKeys = mine.KeysIn(range); // only the drifted ranges
var peerKeys = RequestKeysIn(peerNode, range);
foreach (var k in mineKeys.Union(peerKeys))
if (peerKeys[k].Version > mineKeys[k].Version) // HLC/version: keep the later write
Apply(k, peerKeys[k]); // converges on both sides
}

The bucketing has to agree on both replicas or the comparison is meaningless: both sides must build leaves over the same key ranges, so the ranges are defined by the partition's own structure — slot boundaries, or fixed hash ranges — not by anything node-local like insertion order. Align the leaves to the same scheme the cluster already uses to place keys, and two replicas of a partition bucket identically by construction.

What it costs, and how often you can run it​

A Merkle tree is not free to keep. Its leaves must reflect current data, so every write dirties the leaf for its range and, transitively, every ancestor up to the root. You can rebuild the tree periodically — simple, but a tree built an hour ago reports ranges as divergent that have since been repaired, producing false positives that waste a comparison — or maintain it incrementally, recomputing a leaf and its ancestor path on each write, which keeps it fresh at the cost of a little work on the hot path. Most systems rebuild on a schedule and accept that anti-entropy is eventually, not instantly, correct.

Granularity is the other dial. More leaves mean each divergent leaf covers fewer keys, so a found difference ships less data — but the tree itself is larger and more expensive to build and hold. Fewer leaves mean a smaller tree but a coarser result: one drifted key forces you to exchange its whole (larger) range. The right point depends on how much drift you expect and how big your values are; a common choice is to size leaves so a single differing key transfers kilobytes, not megabytes.

None of this replaces synchronous replication — it backstops it. Replication keeps replicas in step in the common case; anti-entropy bounds how long a divergence that slipped through can survive, turning "stale until someone notices" into "stale until the next repair pass." It is the same instinct as rebuilding an owner from its replicas after a loss, scaled down from catastrophe to steady-state maintenance: instead of reconstructing everything after a node dies, you continuously reconcile the small, inevitable drift while every node is alive.

Wrap-up​

Replicas of a partition drift — a dropped message, a brief outage, a short partition — and the divergence hides until a client reads the stale copy. Anti-entropy is the background process that assumes this and repairs it, and a Merkle tree is what makes the repair affordable: a hash tree over the keyspace lets two replicas confirm they are identical with a single exchanged hash, and when they differ, descend only the branches that actually differ, narrowing millions of keys to the few drifted ranges in a logarithmic walk that transfers only the real differences. The found keys reconcile with the same version-ordered last-write-wins rule that settles any conflict, so both sides converge without a coordinator, provided they bucket the keyspace identically. The costs — keeping the tree fresh and choosing leaf granularity — decide how often and how finely you can repair, but the shape never changes: compare roots, prune everything that matches, and spend your bandwidth only on the keys that were actually wrong.