Sub topic 14
Repairing divergence with read repair and Merkle trees
This chapter assumes you know the replication and quorum model from the earlier chapters: N replicas per key, read and write quorums (R and W), and vector clocks. It also assumes you can read short Python snippets.
Why replicas drift apart
Replicas of the same key diverge even in a healthy cluster. A write succeeds once W replicas acknowledge it, so the other N - W replicas may not have it yet. Failures make this worse. A node can be down during a write, a packet can be dropped, or a disk can lose a block. Hinted handoff covers short outages, but hints expire and the node holding them can fail.
Left alone, divergence accumulates. A key that nobody reads stays stale forever on the replicas that missed the write. If the replicas that did get the write then fail, the data is effectively lost.
Two mechanisms repair this, and they cover different cases:
| Mechanism | Trigger | Scope | Cost |
|---|---|---|---|
| Read repair | A client read | Only the key that was read | Extra writes on the read path |
| Anti-entropy with Merkle trees | A background timer | Whole key ranges, including keys nobody reads | Tree building and periodic comparison traffic |
Read repair
On a read, the coordinator asks the replicas for the key. It already waits for R responses, and it can compare their versions at no extra network cost. If some replicas return older versions, the coordinator sends them the newest version. That is read repair.
The decision logic uses the vector clocks from the previous chapter. A version is discarded only if another version strictly dominates it. Versions that are concurrent are all kept as siblings, and every replica that lacks the full set gets repaired.
def dominates(a: dict, b: dict) -> bool:
"""True when a is greater than or equal to b in every component."""
keys = set(a) | set(b)
return all(a.get(k, 0) >= b.get(k, 0) for k in keys)
def read_repair(responses):
"""responses maps node -> (clock, value).
Returns the surviving versions and the nodes that need a repair write."""
clocks = {node: clock for node, (clock, _) in responses.items()}
merged = {}
for node, (clock, value) in responses.items():
beaten = any(
dominates(other, clock) and other != clock for other in clocks.values()
)
if not beaten:
merged[tuple(sorted(clock.items()))] = (clock, value)
siblings = list(merged.values())
stale = [
node
for node, (clock, _) in responses.items()
if len(siblings) > 1 or clock != siblings[0][0]
]
return siblings, stale
responses = {
"node-a": ({"a": 2}, "v2"),
"node-b": ({"a": 1}, "v1"),
"node-c": ({"a": 2}, "v2"),
}
siblings, stale = read_repair(responses)
print(siblings) # [({'a': 2}, 'v2')]
print(stale) # ['node-b']Design choices in read repair
- Blocking or asynchronous. The coordinator can repair before replying, which gives monotonic reads for that client but adds latency. Most systems reply first and repair in the background.
- Which replicas to ask. With R = 2 and N = 3, the coordinator may contact only two replicas, and the third is never compared. Some systems send the read to all N replicas but return after R answers. They then use late responses for repair. Others read a random extra replica on a small fraction of reads.
- Repair is a write. It consumes disk and network capacity on the replicas, and it competes with client traffic when many keys are stale at once, for example after a node returns from a long outage.
Read repair has a hard limit: it only touches keys that clients read. Cold data, such as old records or archive keys, never gets repaired this way.
Anti-entropy with Merkle trees
Anti-entropy is a background process in which two replicas compare their data and copy what is missing. The naive version sends every key and version across the network, which is far too expensive for terabytes of data. A Merkle tree lets two replicas find the differences while exchanging very little.
A Merkle tree is a tree of hashes. Each leaf holds the hash of a small group of keys. Each inner node holds the hash of its children's hashes. The root hash summarizes the whole data set. If two replicas have the same root, they hold identical data (up to hash collisions), and the comparison ends after one small message. If the roots differ, they compare the children, then descend only into the subtrees whose hashes differ. The cost is proportional to the number of differences, not the size of the data.
import hashlib
def digest(data: bytes) -> bytes:
return hashlib.sha256(data).digest()
def bucket_of(key: str, buckets: int) -> int:
return int.from_bytes(digest(key.encode())[:8], "big") % buckets
def build_tree(store: dict, buckets: int = 8):
"""Return tree levels. levels[0] holds the leaves, levels[-1][0] is the root.
buckets must be a power of two."""
groups = [[] for _ in range(buckets)]
for key in sorted(store):
groups[bucket_of(key, buckets)].append(f"{key}={store[key]}")
level = [digest("|".join(items).encode()) for items in groups]
levels = [level]
while len(level) > 1:
level = [digest(level[i] + level[i + 1]) for i in range(0, len(level), 2)]
levels.append(level)
return levels
def differing_buckets(a, b):
"""Walk down from the root, following only the subtrees whose hashes differ."""
if a[-1][0] == b[-1][0]:
return []
suspects = [0]
for depth in range(len(a) - 2, -1, -1):
next_suspects = []
for i in suspects:
for child in (2 * i, 2 * i + 1):
if a[depth][child] != b[depth][child]:
next_suspects.append(child)
suspects = next_suspects
return suspects
store_a = {f"user:{i}": f"value-{i}" for i in range(1, 21)}
store_b = dict(store_a)
store_b["user:7"] = "stale-value"
tree_a = build_tree(store_a)
tree_b = build_tree(store_b)
print(differing_buckets(tree_a, tree_b)) # one bucket index
print(differing_buckets(tree_a, tree_a)) # []Only the keys in the differing buckets are then exchanged and reconciled with their vector clocks. In this example, one changed key leaves one differing bucket out of eight. Real systems use thousands or millions of leaves per range, so the saving is much larger.
How a repair round works
- Each replica builds a tree over a key range that it shares with another replica. In a ring design this is typically one virtual node's range, because the replicas for that range are the same for every key in it.
- The replicas exchange root hashes. If they match, the round ends.
- Otherwise they walk down the tree and list the differing leaf buckets.
- For each bucket, they exchange key and version pairs and stream the newer versions to the side that is behind.
Both sides must build their trees over the same range with the same bucket boundaries and the same hash function, or the hashes cannot be compared. A tree should also include the version or clock with each value, not just the value. Otherwise two replicas with the same value but different clocks look identical.
Operating considerations
- Tree maintenance. Rebuilding a tree means scanning the data. Some systems keep the tree updated incrementally on each write, which costs write throughput. Others rebuild periodically from a snapshot, which makes the tree slightly out of date. A stale tree causes some false differences, which are harmless but waste work.
- Leaf size. Few large leaves mean a small tree but a lot of data to stream for each differing leaf. Many small leaves mean a big tree in memory. Pick the leaf size so that the stream for one bucket is cheap.
- Throttling. Repair after a long outage can saturate disks and the network. Rate-limit it and run it at low priority.
- Churn. When a node joins or leaves, range boundaries change and trees for the affected ranges must be rebuilt.
Choosing between them
Use both. Read repair keeps hot keys consistent with no extra machinery. Anti-entropy is the safety net for cold keys, for long outages, and for silent corruption. A common schedule is a full anti-entropy pass over every range at least once per tombstone retention period.
Neither mechanism adds consistency guarantees to a single read. They make replicas converge over time, which is eventual consistency. A client can still read a stale value from a replica before repair reaches it, unless R + W > N.
Exercise
Two replicas each hold 1,000,000 keys in 1,024 leaf buckets. Exactly one key differs. Roughly how many hashes must they compare to find the differing bucket, and why is this better than sending all keys?
Show answer
A binary tree over 1,024 leaves has 10 levels below the root. At each level the replicas compare the two children of the one differing node, so they compare about 1 + 2 x 10 = 21 hashes. Then they exchange only the roughly 1,000 keys of one bucket (1,000,000 / 1,024) to fix the difference. Sending all keys would transfer 1,000,000 entries.
Exercise
A key is written with W = 2 on N = 3 and is never read again. Which mechanism repairs the third replica if it missed the write, and what happens if neither mechanism runs before the other two replicas fail?
Show answer
Because nobody reads the key, read repair never touches it. Only Merkle-tree anti-entropy (or a surviving hint) can bring the third replica up to date. If both up-to-date replicas fail before repair runs, the write is lost, even though it was acknowledged.