Video in progress

How do you find the differences between replicas in two data centers without comparing every record? How does a Merkle tree help here?

Each replica splits its key range into pieces and builds a tree from the hash of each piece: a parent node is the hash of its children's hashes. If the roots are equal, the replicas are identical. If not, we descend only into the branches whose hashes differ. O(differences × log n) data crosses the network, not O(n).

📖 Answer

The naive solution is to send 500 million records from one side to the other and compare. If the two sides are 99.999% identical, that's terabytes of pointless traffic.

How it's built:

  • I split the key space into, say, 2¹⁵ leaf ranges;
  • each leaf is the combined hash of the (key, version, valueHash) entries in that range;
  • an internal node is the hash of its two children's hashes;
  • the root is the "fingerprint" of the whole replica.

The comparison is recursive: we exchange the roots; if they differ, we exchange the two children, then only the ones that differ. With 10 differing leaves, that's ~10 × 15 hash exchanges and the records of 10 leaves.

void diff(Node a, Node b, List<Range> out) {
    if (Arrays.equals(a.hash(), b.hash())) return;   // identical branch — we don't descend
    if (a.isLeaf()) { out.add(a.range()); return; }
    diff(a.left(), b.left(), out);
    diff(a.right(), b.right(), out);
}

(In a real system this isn't in a single process; it's a sequence of requests between the two nodes.)

Who uses it: Cassandra's anti-entropy repair, the original DynamoDB paper, Git (every commit has a tree hash), blockchains, ZFS and IPFS.

Trade-offs you see in prod:

  • Leaf size: small leaves mean precise differences, but the tree is big and expensive to build. Large leaves mean thousands of records get transferred because of one differing record. This is why, in Cassandra, repair sometimes streams more data than expected.
  • Build cost: recomputing the whole tree from scratch every time is a full scan over the disk. An incrementally updated tree is a bit more expensive on writes, but repair is cheap.
  • The data doesn't stand still: writes keep arriving during the comparison. You usually compare against a snapshot or a "up to this timestamp" boundary, otherwise you get constant false differences.
  • The hash doesn't have to be cryptographic, but the collision probability must be small enough that it can't hide a difference; 128 bits is enough.

A Merkle tree doesn't answer "which one is right": it only finds the difference. Which version wins (last-write-wins, vector clocks, CRDTs) is a separate decision.