← Data structures

Merkle tree

Trees, logs and ordered structures

A tree of hashes where each leaf is the hash of a block of data and each internal node is the hash of its children, so one root hash summarises everything beneath it. It exists so two parties holding large datasets can find exactly where they differ by exchanging a handful of hashes instead of the data.

What it costs

OperationCostNote
BuildO(n) hashesHash every block, then hash pairs upward; a 1M-block tree is about 2M hashes.
Compare two treesO(d × log n) hashes exchangedd is the number of differing blocks. Equal root hashes mean identical data in one exchange.
Update one blockO(log n) hashesRehash the leaf and the path to the root.
Prove inclusionO(log n) hashesThe sibling hashes along the path let a verifier recompute the root (used by Git, certificate transparency, blockchains).

Memory: About 2n hashes of 32 bytes for n blocks; for a key range split into 1M blocks that is 64 MB, typically rebuilt on demand rather than kept.

Find the differing block by descending where hashes disagree

Both replicas hash the same block boundaries. Roots differ, so they compare children: the left subtree matches and is skipped; the right is descended until the single differing leaf (block 3) is found and only that block is transferred.

How it works

  1. Split the data into blocks, for example a key range split into 1,024 sub-ranges, or a file into 4 KB chunks. Hash each block with a cryptographic hash such as SHA-256; these are the leaves.
  2. Hash each pair of adjacent leaves together to form the parents, then pair the parents, and so on until one root hash remains. The root changes if any byte anywhere changes.
  3. To compare two replicas, each builds a tree over the same block boundaries and they exchange root hashes. If they match, the replicas are identical and the conversation is over after 32 bytes.
  4. If the roots differ, they exchange the two child hashes, descend into the children that differ, and repeat. Matching subtrees are never explored. After log2(n) rounds the differing leaves are known, and only those blocks are transferred.
  5. After repairing a block, the leaf and its ancestors are rehashed, so the tree stays current without a full rebuild.

Why it is shaped this way

  • Hashing is cheap and a 32-byte root is tiny, so detecting "are we in sync" costs one message regardless of data size.
  • The tree makes the search for differences logarithmic: a single corrupted block in a billion is found in 30 hash comparisons, not a billion.

Worked example

Anti-entropy between two replicas in the distributed cache (the same mechanism Cassandra and DynamoDB use)

  • Shard 3 holds 50M keys totalling 20 GB on a primary and a replica. After a network partition the replica may have missed some writes, and comparing 50M keys directly would mean streaming 20 GB.
  • Each node splits the shard’s key range into 1M sub-ranges of about 50 keys, hashes the keys and values in each sub-range into a leaf, and builds the tree: about 2M SHA-256 hashes, a few seconds of CPU, 64 MB of hashes.
  • The roots differ. Round 1 exchanges 2 hashes; round 2, 4; and so on. If 300 sub-ranges diverged, the exchange is at most 300 × 20 levels = 6,000 hashes, under 200 KB, in 20 round trips.
  • Only the 300 sub-ranges × 50 keys = 15,000 keys (about 6 MB) are streamed and reconciled by version, instead of 20 GB. The whole repair takes seconds and the network sees a thousandth of the data.
  • Update path: when a repaired key changes a leaf, 20 hashes are recomputed along the path to the root, so the tree stays valid for the next comparison.

When it is the wrong choice

  • Replicas that stream a single ordered log from one primary: they are kept in sync by log position, so there is nothing to reconcile and a tree is redundant.
  • Data that changes faster than a tree can be rebuilt or maintained: rehashing paths for every write adds log n hashes per write; use it for periodic repair, not per-request.
  • When you need to know what changed, not just where: the tree finds differing blocks; a version or vector clock per key decides which side is newer.

Interviewer follow-ups

Answer out loud before you open each one.

Why not just compare a hash of the whole dataset?

One hash tells you whether the two copies differ but not where, so a single stale key would force a full transfer. The tree adds intermediate hashes so the search for the difference narrows by half at each level and only the differing blocks move.

How does Cassandra use Merkle trees for repair?

During a repair each replica builds a tree over the token range being repaired, with leaves covering sub-ranges of rows. Replicas exchange trees, identify mismatching sub-ranges, and stream only those rows to each other, then resolve each row by timestamp. This is anti-entropy repair, run periodically to catch writes missed during outages.

What does Git use Merkle trees for?

Every commit is the hash of a tree object, which hashes the files and subtrees it contains. Two repositories compare commit hashes to know whether they are in sync, and a fetch sends only the objects whose hashes the other side lacks. The same property gives integrity: changing any byte of history changes every hash above it.

How does an inclusion proof work?

To prove block 3 is in the tree you supply its hash plus the sibling hash at each level on the path to the root: H2, then H01. The verifier recomputes H23 and then the root and checks it matches the published root. That is log2(n) hashes to prove membership in a set of n, which certificate transparency logs rely on.

Where it shows up

Building blocks
Survive losing a node · Tune reads and writes with quorums · Accept a short delay for scale · Recover from bad data, not just dead disks · Protect data and secrets
Problems
Distributed Key-Value Cache (Redis / Memcached-like) · Chat App (WhatsApp / Messenger)