Quick revision
The short answer
Split the key space into many fixed buckets, hash a canonical form of every row on both sides, and build a hash tree over the buckets. Comparing the trees from the top down finds the few differing buckets without reading matching data twice, and only those buckets are compared row by row. Each bucket hash is tagged with the change log position it reflects, so differences are rechecked after change capture catches up, and the persistent ones become a precise repair list and the cutover gate.
What to remember
In this answer, we designed a migration check based on hash trees. We split the key space into a million fixed buckets, hashed a canonical form of every row so that type and time zone differences do not count, and compared the trees from the top down so the work grows with the number of differences. We tagged each bucket hash with a change log position and rechecked differing buckets after CDC caught up, made the hashes incremental so the check runs hourly, and turned persistent differences into a repair list fed through the same pipeline, with zero differing buckets as the cutover gate.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Split the key space into many fixed buckets, hash a canonical form of every row on both sides, and build a hash tree over the buckets. Comparing the trees from the top down finds the few differing buckets without reading matching data twice, and only those buckets are compared row by row. Each bucket hash is tagged with the change log position it reflects, so differences are rechecked after change capture catches up, and the persistent ones become a precise repair list and the cutover gate.
Why this question is asked
When a company moves billions of rows between databases while both stay live, the hardest question at the end is not how to copy the data but how to prove the copy is right. A full row-by-row diff of 2 billion rows takes days and is out of date before it finishes, because rows keep changing. Interviewers ask this at a senior level because the answer combines a data structure (the Merkle tree), practical normalisation problems, and the reasoning needed to cope with a moving target. In this answer, we will recap what a hash tree gives us, design the bucket layout and canonical row form, walk through the top-down comparison, handle rows that change during the check, make the check incremental, and turn its output into repairs and a cutover gate.
1A Quick Recap of Hash Trees
A hash tree, also called a Merkle tree, summarises a large set of data with hashes arranged in levels. The leaves are hashes of small pieces of data. Each parent is a hash of its children's hashes, and the root is a single hash for everything. If two datasets have the same root hash, they are, with overwhelming probability, identical. If the roots differ, we compare the children and follow only the branches whose hashes differ.
The useful property is that the work of finding differences grows with the number of differences, not with the size of the data. Cassandra uses this for anti-entropy repair between replicas, and it suits a migration check for the same reason.
2Buckets and a Canonical Row Form
We start by dividing the primary key space into fixed ranges that both sides can compute independently. With 2 billion rows, a million buckets gives about 2,000 rows per bucket, small enough to diff quickly by reading rows, large enough that the tree has manageable size. We could bucket by key range, or by a hash of the primary key modulo one million, which spreads rows evenly even when keys are skewed. The bucket rule must not depend on how either database stores data, so sharded MySQL and the new database compute the same bucket for the same row.
The harder part is the canonical form, a single agreed text or byte representation of each row. The two databases will disagree in ways that are not real differences: DATETIME without a time zone versus a timestamp in UTC, DECIMAL(18,2) versus a float, trailing spaces, empty string versus NULL, column order, character encoding. If we hash raw values, every bucket will differ. So we write one normalisation function, used by both sides, that orders columns, converts times to UTC with fixed precision, prints numbers with fixed scale, and spells NULL explicitly. Then each row hash is a hash such as SHA-256 or a fast 128-bit hash of that canonical string.
The bucket hash must not depend on row order either. We either sort rows by primary key inside the bucket before hashing, or combine row hashes with an order-independent operation such as addition modulo 2^128, which also makes incremental updates easy, as we will see.
3Comparing From the Top Down
With leaf hashes for a million buckets, we build parents over groups, for example 1,000 buckets per parent and 1,000 parents under the root. The comparison starts at the root. If it matches, we are done. If not, we compare the 1,000 parent hashes and descend only into the parents that differ, then compare their 1,000 leaves, and end with a small list of differing buckets. For each of those, we fetch the roughly 2,000 rows from both sides, compare row hashes by key, and get the exact keys that are missing on one side, extra on the other, or different.
- Compute leaf hashes per bucket on both sidesone parallel scan per shard
- Root hashes equal?YesCopies matchNoCompare the 1,000 parent hashes
- Descend into differing parents onlycompare their 1,000 leaves
- List differing bucketsfor example 300 of 1,000,000
- Diff rows inside those buckets by keymissing, extra or changed
- Recheck after change capture passes the snapshotdrop differences that disappear
6 steps in order. Play them, or step through them one at a time.
Notice the cost. Computing leaf hashes still requires one full read of each side, but that read is a streaming scan that can run in parallel per shard and per range, and it happens once. Everything after that is cheap: if 300 buckets differ, we diff 600,000 rows instead of 2 billion.
4Coping With Rows That Change During the Check
Both databases stay live, and change data capture, which streams each committed change from the source binlog into the target, delivers changes a few seconds or minutes late. So at any moment a bucket can differ simply because a recent update has not arrived yet. If we report those as errors, the check is useless.
The fix is to record a position with every bucket hash. On the source, we note the binlog position (or GTID set) or the highest updated_at value seen while hashing that bucket. On the target, we note the CDC pipeline's applied position. When buckets differ, we wait until the pipeline has applied changes past the source position recorded for that bucket, then recompute both hashes. A difference that disappears was lag. A difference that persists after the lag window, say two rechecks over ten minutes, is real.
So the check never needs a global freeze. It compares each bucket at a point where both sides should agree, and the recheck turns a moving target into a stable one.
5Making It Incremental
A full scan of 2 billion rows on each side might take a few hours with good parallelism. That is acceptable once, but leadership will want proof again the day before cutover, and the day after a fix. So we keep the leaf hashes and update them. Because the bucket hash is an order-independent sum, a change event can update it directly: subtract the hash of the old canonical row and add the hash of the new one. The CDC stream on the source side and the apply log on the target side can both feed these updates.
A simpler alternative is to mark buckets dirty when a change arrives and recompute only those buckets, which takes seconds for a few thousand buckets, so the whole tree can be rechecked hourly until cutover. A weekly full rescan guards against a bug in the incremental path itself.
6From Differences to Repairs and a Cutover Gate
The output of each run is a repair list: for every differing bucket, the primary keys and the kind of difference. We do not patch the target by hand. Instead we re-emit those source rows through the same pipeline, for example by touching them in the source or by publishing them as synthetic change events, so the normal apply code writes them. That way a repair also tests the pipeline, and if a bug in the transformation caused the difference, it shows up again and gets fixed at its root.
The cutover gate is then simple and objective: zero differing buckets after the lag window, on two consecutive runs. The history of difference counts per run is the evidence leadership asked for.
| Finding in a bucket | Likely cause | Repair |
|---|---|---|
| Row missing on target | dropped event or failed initial copy | re-emit the source row |
| Extra row on target | missed delete or wrong key mapping | re-emit the delete, fix the mapping |
| Same key, different values | transformation bug or normalisation gap | fix the code, re-emit the row |
| Difference gone on recheck | CDC lag at hashing time | nothing; it was in flight |
7Follow-up questions
Why not just compare row counts and sums per table?
Counts and sums catch gross errors but miss the common ones: a changed value that keeps the count, two errors that cancel out in a sum, or a timestamp off by an hour. A hash of the canonical row catches any change in any column, and the tree tells us where it is.
What hash function would you use?
For a verification job inside our own systems, a fast non-cryptographic 128-bit hash such as xxHash128 or MurmurHash3 is enough, because we are guarding against bugs, not an attacker. If the result is evidence in an audit, SHA-256 costs more CPU but is beyond doubt. Either way, both sides must use the same function on the same canonical bytes.
8Conclusion
In this answer, we designed a migration check based on hash trees. We split the key space into a million fixed buckets, hashed a canonical form of every row so that type and time zone differences do not count, and compared the trees from the top down so the work grows with the number of differences. We tagged each bucket hash with a change log position and rechecked differing buckets after CDC caught up, made the hashes incremental so the check runs hourly, and turned persistent differences into a repair list fed through the same pipeline, with zero differing buckets as the cutover gate.
Open with
I would build a hash tree over the data on both sides. First I divide the primary key space into fixed buckets, say a million, so each holds about 2,000 rows, using a rule both MySQL and the target can compute.
Then, if they want more
For every row I hash a canonical form: columns in a fixed order, timestamps in UTC with fixed precision, decimals with fixed scale, NULL spelled out, so formatting differences between the databases do not show up as false differences. The bucket hash is an order-independent sum of row hashes, and parents are hashes of groups of buckets.
Then I compare from the root down and only descend into differing branches, so if 300 buckets differ I diff 600,000 rows instead of two billion.
Because both systems are live, each bucket hash records the binlog position it reflects, and differing buckets are rechecked once CDC has applied past that position; anything that persists after the lag window is real. I would keep the hashes up to date from the change stream so the check can run hourly until cutover.
Differences become a repair list by key, and repairs go through the same pipeline by re-emitting source rows, so we also test the pipeline. The cutover gate is zero differing buckets on two consecutive runs.
About this answer
- Last updated
- 13 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Design a verification method based on hash trees that finds differences quickly, copes...": https://scrivio-interview-library.netlify.app/architecture/distributed-systems/10333e8c18/