Hardening a Duplicate-File Finder Against Real Filesystems
System DesignModel answerLast updated
Design a duplicate-file cleanup tool that survives live, messy filesystems: handle errors, races, loops, scale and hash choices, and make deletions provably safe.
You are building a command-line tool that finds identical files across large directory trees and can optionally reclaim space by removing duplicates. The basic idea is simple: bucket files by size, then compare content hashes. Your task is to discuss what makes this hard when it runs on a real, busy machine.
Walk through the problems such a tool is likely to hit and give a concrete mitigation for each. Cover at least these areas:
- Permission failures and I/O errors
- Files being modified, replaced, or removed while the scan runs (time-of-check vs. time-of-use)
- Path length and filename encoding limits
- Symlink cycles, hard links, bind mounts and special files
- Memory and disk throughput bottlenecks at tens of millions of files
- Choice of hash function and the risk of collisions
- Partial hashing versus full hashing, and when each is enough
- Parallelism and throttling so the tool doesn't starve other workloads
- Incremental rescans and crash-safe checkpointing
- Safe cleanup actions (verification before deletion, hard links, reflinks, dry runs)
State your assumptions about scale and environment first, and explain which trade-offs you favor and why.
Hints
Hint 1
Organize your answer as a pipeline (walk, filter by size, cheap partial hash, full hash, byte comparison, action) and attach failure modes to each stage rather than listing problems at random.
Hint 2
Decide on the correctness bar up front: a missed duplicate costs a little disk space, but a false match followed by deletion destroys data. Let that asymmetry drive every decision, including whether to trust a hash alone.
Hint 3
Think about what can change between the moment you inspect a file and the moment you act on it. Record identity and timestamps, re-check them before acting, and consider scanning a filesystem snapshot for busy trees.
Hint 4
Remember that two paths pointing to the same inode are not duplicates of each other, and that opening special files such as FIFOs can hang the scan.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Framing
The interviewer assumes you know the core algorithm (group by size, then hash). The real question is whether you can run it against a live, messy filesystem without losing data. I would organize the answer around a pipeline and attach risks to each stage.
Assumptions to state first: roughly 10M files and 50 TB across local disks and NAS, a long tail of multi-GB files, users writing during the scan, possibly Windows/macOS/Linux, and an action that may delete or link files.
Guiding principle: false negatives are cheap, false positives are catastrophic. Everything below follows from that.
Pipeline
walk -> stat/filter -> group by size -> partial hash -> full hash -> byte verify -> act
| |
state DB (path, dev, inode, size, mtime, ctime, hashes) journaled actions
Each stage shrinks the candidate set. Most files have a unique size and drop out with only a stat. A partial hash removes most of the remainder. Only survivors pay for a full read.
Risks and mitigations
Permission and I/O errors
- Wrap every
open,statandread. Log the error type (EACCES, EIO, ENOENT) and continue; one bad file must not abort a 10-hour run. - A file that errored is treated as "not a duplicate" and is never acted on.
- Retry transient failures (EAGAIN, network timeouts) with bounded exponential backoff.
- Produce an end-of-run report of skipped paths so coverage is explicit.
- Avoid running as root by default.
Files changing mid-scan (TOCTOU)
- Record
(dev, inode, size, mtime_ns, ctime_ns)at stat time. - Open once and use
fstaton the descriptor to avoid path-swap races. - Re-check the tuple after hashing and again immediately before acting. Any difference marks the entry stale and it is skipped.
- For high-churn trees, scan a snapshot (ZFS, Btrfs, LVM, VSS).
Path and name limits
- Windows MAX_PATH is 260: use the
\\?\prefix or long-path support. Linux PATH_MAX is about 4096 and NAME_MAX 255: walk with directory file descriptors (openat,fstatat,os.fwalk) so you never build giant absolute paths. - Treat names as bytes: they may be invalid UTF-8 or contain newlines. Quote them in reports.
- Account for case-insensitive filesystems and Unicode normalization (NFC vs. NFD on macOS).
Symlinks, hard links and special files
- Do not follow symlinks by default (
lstat). If following is enabled, keep a visited set of(dev, inode)for directories to break cycles. - Stay on one filesystem by default and treat bind mounts or overlapping roots as aliases.
- Paths sharing the same
(dev, inode)are already the same data. Deleting one frees nothing, so do not count them as duplicates. - Skip FIFOs, sockets and devices; opening a FIFO can block forever.
Memory
- 10M entries at about 200 bytes each is roughly 2 GB in RAM, which is borderline. Stream the walk into SQLite (indexed on size) or use an external sort, and only load size groups with two or more members.
- Never read a whole file; hash in 1-8 MB chunks.
Disk throughput
- Reads dominate. On HDDs, sort work by inode or extent and use one or two readers per spindle. On SSD/NVMe, parallelism helps up to the queue depth.
- Use
posix_fadvise(SEQUENTIAL, then DONTNEED) so the scan does not evict other workloads' page cache.
Hash choice and collisions
- Use BLAKE3 or SHA-256 for full hashes. Avoid MD5 and SHA-1, since collisions can be crafted and someone could plant a file to get a victim's file deleted.
- A fast non-cryptographic hash (xxHash3) is acceptable for the partial prefilter because a collision only wastes work.
- Accidental 256-bit collisions are negligible (about n²/2²⁵⁷), but since the bar is zero false positives, always do a byte-for-byte comparison before a destructive action. The hash only nominates candidates.
Partial vs. full hashing
- Sample head, middle and tail (for example 64 KB each). Head-only sampling fails on formats with common headers (ZIP, video containers, VM images).
- A partial match is never proof; it only promotes a file to a full hash.
- For large files, compare chunk by chunk and stop at the first difference. Two 50 GB files that differ at 1 MB cost 1 MB of I/O.
Concurrency and throttling
- Separate walker and hasher pools with bounded queues for backpressure. Size hashing per device, not globally.
- Add MB/s or IOPS limits and lower priority (
ionice -c3,nice). Use lower concurrency and longer timeouts on network storage. - Handle SIGINT by flushing the checkpoint and exiting cleanly.
Incremental rescans and checkpointing
- Persist state keyed by
(dev, inode)plus path with size, mtime_ns, ctime_ns and cached hashes. - Reuse cached hashes only if size, mtime and ctime are all unchanged; ctime catches timestamp resets.
- Commit in batches (every 10k files or 30 s) inside transactions so a crash resumes from the last batch.
- Use change journals (inotify/fanotify, FSEvents, NTFS USN) to skip full walks. On coarse-timestamp filesystems (FAT, 2 s), treat files modified near scan time as dirty.
Safe actions
- Default to dry run with a report; require an explicit flag to modify anything.
- Before acting: re-stat, confirm identity unchanged, and byte-compare the keeper and the victim.
- Prefer reflinks (on Btrfs, XFS, APFS) or hard links over deletion. To replace, create the link under a temporary name in the same directory and
renameit over the target, which is atomic, so there is never a moment with no file. - Hard links share content and metadata, so warn about differing permissions or owners, and never hard-link across filesystems.
- Keep a keeper policy (oldest, shortest path, preferred directory), write an append-only action journal, and optionally move to trash rather than unlink.
- Never touch files that are open, locked, or in protected directories.
Common mistakes
- Trusting a hash alone before deleting.
- Hashing the head of the file only.
- Treating hard links as duplicates.
- Following symlinks into cycles.
- Aborting on the first unreadable file.
- Holding the full file list in memory.
- Deleting in place instead of an atomic link-and-rename.
Trade-offs to mention
Byte verification adds a second read of each duplicate group, which is the price of safety. Snapshots give consistency at the cost of setup and storage. Hard links save space but couple the files' future edits, whereas reflinks keep copy-on-write semantics. Choose based on the filesystem and the user's tolerance for risk.