Dedupe a Huge Directory Tree with Tiered Hashing
System DesignModel answerLast 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:
- 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.
- 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.
- Supports a dry-run report listing each duplicate set and the space that could be reclaimed.
- Supports a relink mode that replaces duplicates with hard links, only where doing so is safe (same filesystem, compatible metadata, file unchanged since scan).
- 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?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach: a funnel of increasingly costly checks
The core insight is that a duplicate test should spend almost nothing on files that are obviously unique, and only pay for full content reads on files that survive cheaper tests. Each stage filters the survivors for the next:
- Scan + stat. Walk the tree iteratively (a manual stack, not recursion, to survive deep trees). Record
size,dev,ino,mode,uid,gid,mtime_nsfor every regular file. Do not follow symlinks. Collapse entries that share(dev, ino)— they're already hard links. - Size bucket. Group by
st_size. A file whose size is unique in the tree cannot have a duplicate. On real trees this removes the large majority of candidates without a single read. - Partial hash. Within each size group, hash the first 64 KB and the last 64 KB with BLAKE2b-256 (~128 KB of I/O per file). Logs, media, VM images and build artifacts often share size but diverge at the head or tail.
- Full hash. Stream the whole file through the same hasher in 1 MB chunks. Memory stays at
O(chunk)regardless of file size. - Byte verification. Before reporting a set as identical (and always before relinking), compare bytes against the group representative. This removes reliance on collision probability entirely: a 256-bit collision is astronomically unlikely, but bytes are cheap insurance against silent corruption. If a mismatch appears inside a hash group, split the group into true-equality subgroups rather than discard it.
Each stage drops groups of size 1 immediately.
Why it's correct
- No false negatives: identical files have equal size, equal partial hash, equal full hash, equal bytes — no filter can separate them.
- No false positives: with verification enabled, every reported pair was actually compared byte-for-byte. Without it, a 256-bit collision is ~2⁻¹²⁸ per pair for a report, which is fine for a dry run but not good enough for destructive actions.
Safe relinking
Only relink when all of these hold:
- Same
st_dev— hard links cannot cross filesystems. mode,uid,gidmatch — a link shares metadata, so linking would silently change permissions/ownership.- Re-stat shows
(ino, size, mtime_ns)unchanged since scan — guards against TOCTOU races. - Content is treated as immutable (datasets, build outputs, backups), because linked files share future edits.
Swap atomically: create a temp link in the duplicate's directory, then os.replace it over the duplicate. A crash leaves either the old file or the new link — never a missing path.
Complexity
Let N = files, C = candidates surviving the size filter, D = bytes hashed at the full-hash stage.
- Time:
O(N)stats +O(C × 128 KB)partial I/O +O(D)streaming I/O (plusO(D_dup)if verifying). Dictionary grouping isO(N). - Space:
O(N)metadata (path + stat), plusO(workers × chunk)read buffers. File contents are never fully resident.
Batching disk I/O
- Run each stage as a whole pass over all candidates before the next begins — most files get read a little or not at all.
- Use large sequential reads (1 MB) to amortize syscall overhead;
posix_fadvise(SEQUENTIAL)helps readahead on Linux. - On HDDs, order work by inode/path to reduce seeks and keep concurrency low (1–4); on NVMe, raise queue depth (16–64).
- For very large files, hash fixed chunks and compare chunk digests across the group so you can early-exit on the first differing chunk; a Merkle-style combine lets several workers hash one huge file in parallel.
Parallelism
- Single machine:
hashlibreleases the GIL on large buffers, so a thread pool parallelizes I/O and hashing well. If profiling shows CPU-bound hashing, switch to a process pool. Walk subtrees in parallel too. - Many machines (MapReduce shape): Map each worker scans a shard of the tree and emits
(size, path, dev, ino); shuffle by size; Reduce workers on the host that owns the data do partial/full hashing and emit(size, hash) → paths. Only metadata and digests cross the network — never file bodies. Relinking stays local to each filesystem.
Reference implementation (Python)
import os, hashlib
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor
CHUNK = 1 << 20 # 1 MB streaming reads
PARTIAL = 64 * 1024 # head/tail sample size
H = hashlib.blake2b
def walk(root):
stack = [root]
while stack:
try:
with os.scandir(stack.pop()) as it:
for e in it:
try:
st = e.stat(follow_symlinks=False)
if e.is_dir(follow_symlinks=False):
stack.append(e.path)
elif e.is_file(follow_symlinks=False):
yield e.path, st
except OSError:
continue
except OSError:
continue
def partial_hash(path, size):
h = H(digest_size=32)
with open(path, "rb") as f:
h.update(f.read(PARTIAL))
if size > 2 * PARTIAL:
f.seek(size - PARTIAL); h.update(f.read(PARTIAL))
elif size > PARTIAL:
h.update(f.read())
return h.digest()
def full_hash(path):
h = H(digest_size=32)
with open(path, "rb") as f:
while (c := f.read(CHUNK)): h.update(c)
return h.digest()
def split(groups, keyfn, pool):
out = []
for g in groups:
buckets = defaultdict(list)
for f, k in zip(g, pool.map(keyfn, g)):
if k is not None: buckets[k].append(f)
out.extend(v for v in buckets.values() if len(v) > 1)
return out
def same_bytes(a, b):
with open(a, "rb") as fa, open(b, "rb") as fb:
while True:
ca, cb = fa.read(CHUNK), fb.read(CHUNK)
if ca != cb: return False
if not ca: return True
def plan_relink(group):
keep, st_keep = group[0]
actions = []
for dup, st_dup in group[1:]:
if (st_keep.st_dev == st_dup.st_dev and
st_keep.st_mode == st_dup.st_mode and
st_keep.st_uid == st_dup.st_uid and
st_keep.st_gid == st_dup.st_gid):
actions.append((keep, dup))
return actions
def dedupe(root, workers=8, relink=False):
with ThreadPoolExecutor(workers) as pool:
seen, by_ino, by_size = {}, set(), defaultdict(list)
for p, st in walk(root):
k = (st.st_dev, st.st_ino)
if k in by_ino: continue # already a hard link of something
by_ino.add(k)
by_size[st.st_size].append((p, st))
groups = [g for g in by_size.values() if len(g) > 1]
groups = split(groups, lambda ps: partial_hash(*ps[:1] + (ps[1].st_size,)), pool)
groups = split(groups, lambda ps: full_hash(ps[0]), pool)
report, actions = [], []
for g in groups:
rep = g[0]
identical = [rep] + [x for x in g[1:] if same_bytes(rep[0], x[0])]
if len(identical) > 1:
freed = sum(x[1].st_size for x in identical[1:])
report.append((rep[0], [x[0] for x in identical[1:]], freed))
actions += plan_relink(identical)
if relink:
for keep, dup in actions:
tmp = dup + ".dedupe.tmp"
os.link(keep, tmp); os.replace(tmp, dup)
return report
Return value: for each representative path, the list of duplicate paths and the bytes that would be freed by linking. relink=True performs the atomic swap.
Common mistakes
- Loading whole files into memory, or hashing with a single
read()on huge inputs. - Skipping the final byte comparison before destructive operations.
- Following symlinks (cycles, phantom duplicates) or forgetting to collapse pre-existing hard links — otherwise you "relink" files that already share an inode and report phantom savings.
- Relinking across devices or with differing modes, which silently mutates permissions.
- Building a per-file pipeline instead of staged passes, so every file pays the full read cost.
- Ignoring TOCTOU: re-stat before linking, or a file edited mid-scan can be merged with a copy that no longer matches.