Practice this topic in a realistic system design interview
A Merkle tree is a tree of hashes. It lets two machines check whether a huge dataset matches by comparing a single hash, and when it doesn't, find exactly which part is different by exchanging only a few more.
In this chapter, we'll learn what a Merkle tree is, how it lets two machines find differences in huge datasets by exchanging only a few hashes, and how systems like Cassandra, Git, and Bitcoin use it.
Suppose you're running a distributed database that stores three replicas of every piece of data. Ideally, all three replicas should contain the same data. But in practice, they can fall out of sync:
Over time, these differences add up, so the replicas need a way to compare their data and bring themselves back into sync.
Now, imagine each replica stores 100 million rows, around 100 GB in total. How can two replicas efficiently figure out which rows are different?
The simplest approach would be for one replica to send all its data to the other, which then compares everything row by row. But that means transferring 100 GB over the network, even if only a few rows are different.
A better approach is to compare hashes instead of the actual data. Each replica computes a single hash of its entire dataset and sends it to the other:
If the hashes match, we can be confident that the data is identical, and no further comparison is needed. This requires transferring only a few bytes.
But if the hashes don't match, we only know that something is different. We still don't know which rows have changed. So we would need to compare all the data again.
What we really need is a way to use hashes to tell us not just whether the data is different, but exactly where the differences are.