SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
  • Bloom Filters
  • Cuckoo Filter
  • Skip Lists
  • Count-Min Sketch
  • HyperLogLog
  • Merkle Trees
  • MinHash
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Advanced Data Topics/Probabilistic and Other Structures

Merkle Trees

A tree of hashes that lets two machines find exactly which data differs, fast.

โฑ 13 min readIntermediateInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A Merkle tree is a tree of hashes. Each leaf is the hash of one block of data, and each parent is the hash of its two children. The top hash is called the root, and it stands for all the data below it.

  • If two machines have the same root, their data is the same. One small comparison is enough.
  • If the roots differ, walk down and compare children. Matching branches are skipped, so you find the exact differing blocks fast.
  • Only the blocks that differ are copied, so syncing huge data sets sends very little over the network.

02Concept: What is it?

A hash turns any data into a short fixed-size fingerprint. The same data always gives the same hash, and even a tiny change gives a completely different one. Hashes are the base of a Merkle tree.

To build the tree, first split the data into blocks and hash each block. These are the leaves. Then join the leaves in pairs: hash the two child hashes together to make a parent. Keep going upward until one hash is left, the root. If a level has an odd number of nodes, systems usually repeat or promote the last one.

A Merkle tree over four blocks
๐ŸŒณRoothash(H12 + H34)
H12hash(H1 + H2)
H34hash(H3 + H4)
H1hash(block 1)
H2hash(block 2)
H3hash(block 3)
H4hash(block 4)
๐Ÿ“„Block 1
๐Ÿ“„Block 2
๐Ÿ“„Block 3
๐Ÿ“„Block 4
Change any block and its hash changes, and so do all the hashes above it, up to the root.
๐Ÿง Why a tree and not one big hash?
One hash of everything tells you that the data differs, but not where. A tree lets you search for the difference: at each level only the branch with a different hash needs a second look.

03Real-Life Example

๐ŸตTwo Copies of a Thick Book
You and a friend each have a 1,000-page book, and you want to know if the copies are the same. Reading both side by side takes hours. Instead, each of you writes a fingerprint for every 10 pages, then a fingerprint for every group of 10 fingerprints, and so on, until there is one fingerprint for the whole book. You compare that last one. If it matches, you are done. If not, you compare the 10 fingerprints under it, find the one that differs, and go down only that branch, until you reach the exact pages that differ.
The book
Merkle tree
A group of pages
A data block
The fingerprint of those pages
A leaf hash
A fingerprint of fingerprints
A parent hash
The fingerprint of the whole book
The root hash
Same final fingerprint
Data is identical, stop
Going down only the branch that differs
Walking the tree to find changed blocks
Copying only the pages that differ
Syncing only the changed blocks
Finding the difference between two machines
๐Ÿ”Compare rootsone hash each
โ†’โ†“different
๐Ÿ”ฝCompare childrenskip equal ones
โ†’โ†“repeat
๐ŸŽฏReach the leavesthe changed blocks
โ†’โ†“
๐Ÿ“ฆCopy only those

04Why Do We Need It?

๐Ÿ”Find differences fast
With a changed blocks out of n, you need about a ร— log n hash comparisons, not n.
๐Ÿ“‰Save bandwidth
Machines exchange a few hashes first, and copy only the data that really differs.
๐Ÿ›ก๏ธProve data is untouched
A single trusted root lets you check any block later, without trusting the machine that gave it to you.
๐ŸงพProve one item is included
A short list of hashes (a Merkle proof) shows that one block belongs to the tree. It is about log n hashes long.
๐ŸงฑCheck in pieces
You can verify each block as it arrives, without waiting for the whole file.
๐ŸงฎCheap to update
When one block changes, only the hashes on its path to the root are recomputed.
One small hash stands for a huge data set. Equal roots mean equal data, and different roots can be followed down to the exact difference.

05Where Do We Use It?

๐Ÿ—„๏ธDatabase repair
Dynamo-style databases such as Cassandra compare Merkle trees of their replicas to find rows that are out of sync (anti-entropy repair).
๐ŸŒฟGit
Git stores files and folders as objects named by their hash, and each folder hash covers its children. The same idea gives cheap change detection.
โ‚ฟBlockchains
Bitcoin puts a Merkle root of a block's transactions in the block header, so light clients can check one transaction with a short proof.
๐ŸŒIPFS and file sharing
Content-addressed systems and torrent-style tools hash pieces of a file so each piece can be checked as it arrives.
๐Ÿ“œTransparency logs
Certificate Transparency logs use a Merkle tree so anyone can check that an entry is in the log and that the log only grows.
๐Ÿ’พStorage systems
Some file systems and backup tools keep a tree of checksums to catch silent data corruption and to sync changes.

06Types / Parts / How It Works

How the pieces fit

PartWhat it isRole
LeafHash of one data blockThe lowest level. A changed block changes its leaf.
Internal nodeHash of the two child hashes put togetherSummarises a whole branch with one value.
RootThe single hash at the topStands for all the data. Compared first.
Merkle proofThe sibling hashes along one path from a leaf to the rootLets someone check one block without the rest of the data.

Comparing two trees

Only the branch with a different hash is followed
Walk down
Rootdiffers โœ—
Left halfsame โœ“ (skipped)
Right halfdiffers โœ—
Blocks 3-4differs โœ—
Blocks 5-8skipped
Block 3differs: copy it
Block 4same โœ“
Different, keep going Same, stop here Never looked at
Block 3 changed on machine B. Only 5 hashes are compared, instead of all 8 blocks.

Common variations

VariationIdeaTrade-off
Binary Merkle treeEach node has two childrenSimple, with proofs about log2(n) hashes long.
Wider tree (more children per node)Hash many children at onceShallower tree, but longer proofs at each level.
Merkle DAGNodes can be shared between several parents (Git, IPFS)Same data stored once, and links form a graph, not a strict tree.
Sparse Merkle treeA huge fixed-size tree where most leaves are emptyAllows proof that a key is absent, at some extra cost.
VisualizerCompare two trees and find the changed blocksChange one block on machine B, then Play and see how few hashes are compared. Then change four blocks, and then none.
Which blocks are different on machine B? (click to change)
Root
A 6d1b
B 5292
Level 2
A 5a6a
B eeef
A efc4
B efc4
Level 1
A 3741
B 3741
A a50a
B f729
A c39f
B c39f
A 4985
B 4985
Leaves: hash of each block
A 0329
B 0329
A 7dcc
B 7dcc
A 5831
B 5731
A 4a5a
B 4a5a
A 85aa
B 85aa
A 2026
B 2026
A 7ab3
B 7ab3
A ea60
B ea60
Data blocks (A / B)
block1:v1
block1:v1
block2:v1
block2:v1
block3:v1
block3:v2
block4:v1
block4:v1
block5:v1
block5:v1
block6:v1
block6:v1
block7:v1
block7:v1
block8:v1
block8:v1
Hashes compared
0
7 in total
Without the tree
8
blocks to compare
Different blocks
?
found so far at the end
Both machines have built a tree of hashes from their data. Press Play to compare them, starting at the root.

Each leaf hash is hash(block). Each parent is hash(left child + right child). Hashes here are a small 16-bit view of a 32-bit hash, so they are short enough to read. Real systems use long hashes such as SHA-256. Try changing 1 block, then 4 blocks, then none, and compare how many hashes are needed.

07How to Use It / Steps / Implementation

Using a Merkle tree to sync two machines

  1. 1
    Split the data into blocks
    Pick a block size, or a key range for a database. The blocks must be cut the same way on both machines.
  2. 2
    Hash each block
    Use a strong hash (such as SHA-256) when the data may be tampered with. A fast hash is enough for simple sync.
  3. 3
    Build the tree upward
    Hash the two children together to make each parent, until one root is left. Be sure both sides join children in the same order.
  4. 4
    Compare the roots
    Send only the root. If they are equal, stop. The data is the same.
  5. 5
    Walk down the differing branches
    Ask for the two children of every node that differs. Skip children whose hashes match.
  6. 6
    Copy only the differing blocks
    When you reach differing leaves, transfer those blocks and fix the other side.
  7. 7
    Update on change
    When a block changes, recompute just the hashes on its path to the root, not the whole tree.
๐Ÿ’กProving one block belongs
To prove block 3 is part of a tree with root R, send block 3 plus the sibling hashes on the way up. The checker hashes the block, combines it with each sibling in turn, and checks that the result is R. For 1 million blocks that is only about 20 hashes.
โš ๏ธBoth sides must build the same tree
Different block sizes, a different order of children or a different hash function give different roots for the same data. Agree on all three first.

08Key Terms to Know

TermMeaning in easy words
HashA short fixed-size fingerprint of some data. The same data always gives the same hash
LeafA node holding the hash of one data block
Parent / internal nodeA node holding the hash of its children's hashes
Root hashThe single hash at the top that stands for all the data
Merkle proof (audit path)The sibling hashes needed to check one leaf against the root
Anti-entropyA background process that finds and repairs differences between replicas
CollisionTwo different inputs with the same hash. Strong hashes make this practically impossible
Tamper-evidentAny change to the data changes the root, so changes cannot go unseen
Content addressingNaming data by the hash of its content
Merkle DAGA Merkle structure where nodes can be shared by several parents (Git, IPFS)
Block / chunkA piece of the data covered by one leaf

09Pros, Cons and Trade-offs

โœ… Pros
  • Compare huge data sets by exchanging very few hashes
  • Pinpoints exactly which blocks differ
  • Short proofs: about log n hashes
  • Tampering shows up in the root
  • A small change updates only one path
โš ๏ธ Cons
  • Building the first tree means reading all the data
  • Both sides must use the same blocks, order and hash
  • A tree that is out of date gives wrong answers
  • Frequent changes keep forcing hash updates
  • Useless if almost everything differs

Trade-offs

ChoiceWe gainWe lose
Small blocksPinpoint small differences, copy littleA bigger tree, more hashes to store and compute
Large blocksA small treeA tiny change forces a large block to be copied
Strong hash (SHA-256)Safe against tamperingSlower than a simple hash
Fast simple hashVery cheap to computeFine for sync, not safe against an attacker
Keep the tree up to date on every writeAlways ready to compareExtra work on each write
Build the tree only when neededNo cost on writesA slow first comparison, because all data must be read

10Common Problems and Mistakes

Common mistakes

  1. Different tree shapes. Two machines cut the data into different blocks, so no hashes match even for identical data.
  2. Ignoring order. hash(A + B) is not the same as hash(B + A). Both sides must agree on the order.
  3. A weak hash against attackers. A simple checksum can be forged. Use a cryptographic hash when security matters.
  4. Comparing a moving target. Data changes while the tree is built, so the roots never agree. Use a snapshot or accept a few false differences.
  5. Rebuilding from scratch. Recomputing the whole tree after each change wastes the benefit. Update only the path.
  6. Expecting it to fix data. A tree finds where data differs. It does not tell you which copy is right.

Things to watch

๐Ÿ—๏ธCost of building
The first build reads all the data. Plan it for a quiet time, or keep trees per small range.
๐Ÿ”€Odd number of nodes
Decide how to handle a lone node. Different rules give different roots.
๐Ÿ“Wide differences
If most blocks differ, the walk reads nearly the whole tree. Just copy everything.
๐Ÿ”Trust of the root
A proof is only as good as the root. Get the root from a trusted place.

11Real-World Examples

๐Ÿ—„๏ธCassandra repair
Nodes build Merkle trees over their data ranges and compare them, to find and stream only the rows that differ.
๐ŸงฉDynamo-style stores
The Dynamo design describes Merkle trees to detect differences between replicas in the background.
๐ŸŒฟGit
Commits, folders and files are objects named by their hashes, so a changed file changes every folder hash above it.
โ‚ฟBitcoin
Transactions in a block are summarised by a Merkle root in the block header.
๐Ÿ“œCertificate Transparency
Public logs of certificates use Merkle trees to prove that an entry is present and that the log was only appended to.
๐ŸŒIPFS
Files are split into chunks linked in a Merkle DAG, and identified by the hash of their content.
๐Ÿ“Note
Each product has its own details, such as block sizes and hash functions. Check the documentation of the system you use.
Mini case: repairing a replica
๐Ÿ—„๏ธReplica Abuilds a tree
โ†”compare roots, then branches
๐Ÿ—„๏ธReplica Bbuilds a tree
โ†’โ†“differing ranges
๐Ÿ”งRepaircopy only those rows
Two replicas exchange a handful of hashes, then copy just the missing rows.

12Related Topics to Read Next

Checksumsโ†’

A checksum is one hash of data. A Merkle tree is a tree of them.

Replicationโ†’

Replicas drift apart, and Merkle trees help find the drift.

Gossip Protocolโ†’

Dynamo-style systems use gossip and Merkle trees together.

Consistent Hashingโ†’

It decides which node owns a key range. Trees are often built per range.

Bloom Filtersโ†’

Another compact summary, but for set membership instead of exact difference.

Distributed File Systemsโ†’

They use checksums over blocks to catch corruption.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”What: a tree of hashes. Leaf = hash(block). Parent = hash(left + right). Root = summary of everything.
  • โœ”Same root: same data. Stop after one comparison.
  • โœ”Different root: compare children, follow only the branches that differ.
  • โœ”Cost: about log n hashes to find a difference, instead of n blocks.
  • โœ”Proof: sibling hashes on the path to the root, about log n long.
  • โœ”Update: one changed block means recomputing only its path.
  • โœ”Used in: Cassandra and Dynamo-style repair, Git, Bitcoin, IPFS, Certificate Transparency.
  • โœ”One line: โ€œOne small hash stands for a huge data set, and a tree of hashes shows where it differs.โ€
โ† Previous
HyperLogLog
Next โ†’
MinHash