KatInterview

Dedupe a Huge Directory Tree with Tiered Hashing

System DesignModel answer
MediumModel answerSystem Designdeduplicationhashingstreaming-io

Last updated

Design and code a disk-scale deduplicator that filters candidates cheaply, hashes in streams, verifies bytes, and safely hard-links duplicates.

Context

You maintain storage for a backup/build system whose directory trees hold millions of files and many terabytes. The same content is frequently written to many paths, so you want to reclaim space without ever silently corrupting data.

Design and implement a deduplication tool that:

  1. Walks a large directory tree and finds sets of byte-identical regular files. Never load a whole file into memory — even multi-hundred-gigabyte ones.
  2. Uses a tiered strategy: cheap filters first (size, partial hash), then full hash, then a final byte comparison so a hash collision can never cause a wrong merge.
  3. Supports a dry-run report listing each duplicate set and the space that could be reclaimed.
  4. Supports a relink mode that replaces duplicates with hard links, only where doing so is safe (same filesystem, compatible metadata, file unchanged since scan).
  5. Runs over multiple CPU cores, and you should sketch how it would scale to multiple machines.

What to cover

  • Hashing pipeline and collision handling.
  • Chunked streaming for very large files.
  • How you batch disk I/O.
  • Time and space complexity in terms of number of files and bytes read.
  • Edge cases: symlinks, unreadable files, zero-byte files, files that vanish mid-run, pre-existing hard links, cross-device duplicates, and what happens on a crash mid-relink.

Deliverable

A working (or closely pseudo-code) implementation in a language of your choice, plus a short written explanation of the design, trade-offs, and failure handling.

Hints

Hint 1

Most files can be eliminated without reading them — what one-byte-of-metadata property splits the tree into obviously-distinct buckets?

Hint 2

A file that is 10 GB must be read in bounded chunks; think about how head+tail sampling acts as a cheap pre-filter before the full stream hash.

Hint 3

Two identical-looking hashes could in theory differ in bytes. What check do you run before you are willing to point two paths at the same inode?

Hint 4

Hard links are per-filesystem — what stat fields tell you two files can legally share an inode, and how do you make the swap atomic so a crash can't lose data?