Byte-Level File Equality and Fleet-Wide Deduplication
System DesignModel answerLast updated
Design a hash-based pipeline to decide if two files hold identical bytes, then scale it to deduplicating content across many machines.
Two files are "the same" only if their byte sequences are the same length and identical in content. File names, permissions, ownership, timestamps, extended attributes, and paths must all be treated as irrelevant. You are asked to design, and justify, a system that answers this question — first for a pair of local files, then as a service that performs deduplication across many directories and many machines.
Your design should cover:
- Which hash to trust. Compare cryptographic and non-cryptographic hash families, explain which one is authoritative for declaring equality and which is only a cheap filter, and why.
- Staged checks. A pipeline that combines a length check, an optional cheap prefilter digest, an authoritative full-file digest, and optionally a direct byte comparison — and the conditions under which each stage executes.
- Collision risk. Quantify the chance of a false "identical" verdict, and explain how the threat model (benign data vs. deliberately crafted inputs) changes your choices.
- Metadata as a shortcut, not proof. Which filesystem attributes you inspect to skip work, to recognize two paths that point at the same underlying object, and to decide when a cached digest is still trustworthy.
- Hashing files larger than memory. Streaming reads, buffer sizing, parallelizing a single file's hash, files with holes, and protecting against a file that mutates while you read it.
- Deduplication at scale. Whole-file vs. fixed-block vs. content-defined boundaries, how to persist and query a digest index, and how a shared service would compute, cache, and serve equality answers.
- Where the cost actually is. I/O versus CPU versus memory, and how the design adapts to whichever dominates.
Hints
Hint 1
Metadata can rule files out or let you reuse an old answer, but it can never rule two files in — only bytes (via a strong digest) can do that.
Hint 2
Think about the birthday bound: a 64-bit non-cryptographic hash is fine as a filter at a million files, but the failure probability becomes material at a billion.
Hint 3
A file can change between your first stat and your last read; the fix is to stat the open descriptor before and after, and to key any cached digest on (device, inode, size, mtime, ctime).
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Framing
Identical means: same length, same bytes. Everything else on disk — name, owner, mode, timestamps, ACLs — is noise and must not enter the comparison. The whole design follows from one idea: cheap checks eliminate work; only a strong content digest can conclude equality; and metadata is used exclusively to avoid computation, never as evidence.
1. Choosing the digest
| Candidate | Class | Rough single-core throughput | Verdict |
|---|---|---|---|
| xxHash3 / XXH128 | non-cryptographic | tens of GB/s | filter only |
| MD5, SHA-1 | cryptographic but broken | ~0.5–1 GB/s | never for equality |
| SHA-256 | cryptographic | ~0.5 GB/s plain, ~2 GB/s with SHA extensions | authoritative |
| BLAKE3 | cryptographic | ~1–2 GB/s per core, scales across cores | authoritative |
The authoritative digest must be collision-resistant against an adversary, so it is SHA-256 or BLAKE3. Pick BLAKE3 when CPU throughput on huge files is the constraint, SHA-256 when you need a standardized, widely interoperable primitive (regulated environments, cross-vendor verification). xxHash is a legitimate prefilter: it is fast enough to be nearly free and cheap enough to throw away. MD5/SHA-1 are excluded because practical chosen-prefix collisions exist for both — an attacker can construct a benign document and a malicious one with the same digest, which in a deduplicating store means the malicious payload silently replaces the benign one.
2. The verification pipeline
Each stage runs only on candidates that survived the previous one:
- Type and length. Compare regular files only; resolve symlinks explicitly rather than following them by default. Different
st_size⇒ different content, stop. At fleet scale, bucketing by size eliminates almost everything before any bytes are read. - Same-object check. Equal
(st_dev, st_ino)means hard links to one file — identical by construction, report immediately and never hash twice. - Optional cheap prefilter. Digest the first and last few tens of KiB with xxHash. Files that share a size but differ (logs with a common header, templates) usually diverge there.
- Authoritative full digest. Stream the entire file through SHA-256/BLAKE3. Serve from the digest cache when the cache key is still valid (section 4).
- Optional literal comparison. A streaming byte-by-byte comparison that exits at the first mismatch. Run it when a false positive would be destructive (deleting a "duplicate"), when policy demands proof, or when one side used a weaker hash.
For exactly two local files a direct streaming comparison with early exit is usually the cheapest option — you read in lockstep and stop at the first difference. Hashing wins when one artifact is compared against many, or when the digest is reused later.
3. Collision reasoning
For n files under a b-bit digest, the probability that some pair collides is roughly n² / 2^(b+1).
- 64-bit,
n = 10⁹: about2⁶⁰ / 2⁶⁵ ≈ 3%— unacceptable as proof. - 256-bit,
n = 2⁴⁰: about2⁸⁰ / 2²⁵⁷ ≈ 2⁻¹⁷⁷— far rarer than an undetected hardware memory fault.
With benign data, an unbroken 256-bit digest is authoritative and a byte comparison adds nothing statistically. With adversarial or multi-tenant input, add defense in depth: a per-tenant keyed hash (BLAKE3 keyed mode, or HMAC-SHA-256) prevents cross-tenant dedup probing, where an attacker infers "this file already exists" from upload behavior; and keep literal verification available behind a flag for destructive operations.
4. Metadata: shortcuts and cache keys
Used only to skip work:
S_ISREGvialstat— skip devices, FIFOs, sockets.st_size— primary bucket key.(st_dev, st_ino)— detects hard links, avoids hashing one object twice.- Digest cache key:
(dev, ino, size, mtime_ns, ctime_ns). ctime belongs in the key becauseutimecan reset mtime but cannot reset ctime. Handle the "racy timestamp" case: if the file was modified within the clock granularity at which the digest was cached, mark it unverified and rehash. Inode numbers get reused after deletion, so include size and ctime — or astatxgeneration field — to disambiguate.
5. Hashing a huge file
Open once with O_NOFOLLOW, read sequentially in 1–8 MiB buffers (amortizes syscalls without thrashing the page cache), and advise the kernel about the access pattern (posix_fadvise(SEQUENTIAL), optionally NOREUSE, so a scan does not evict everything else). Memory is O(buffer), independent of file size.
For intra-file parallelism, SHA-256 is inherently serial unless you impose a Merkle tree over fixed blocks and define the file digest as the tree root — consistently, everywhere. BLAKE3 already is a Merkle tree over small chunks, so threads hash disjoint ranges and combine.
Sparse files: holes read as zeros, and the digest must reflect logical content. Use SEEK_DATA/SEEK_HOLE to skip physical reads and feed a precomputed zero-block digest for hole ranges.
TOCTOU: fstat the open descriptor before and after hashing; if size/mtime/ctime moved, discard and retry with backoff or flag the file unstable. For strong guarantees, hash from a filesystem snapshot. Re-check the stat key immediately before acting on a result (unlinking, hard-linking, deleting).
import hashlib, os
def digest_file(path, bufsize=4 << 20):
fd = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
try:
s0 = os.fstat(fd)
if not os.path.stat.S_ISREG(s0.st_mode):
raise ValueError("not a regular file")
h = hashlib.sha256()
while chunk := os.read(fd, bufsize):
h.update(chunk)
s1 = os.fstat(fd)
key = lambda s: (s.st_size, s.st_mtime_ns, s.st_ctime_ns)
if key(s0) != key(s1):
raise RuntimeError("file mutated during hashing")
return h.hexdigest(), (s0.st_dev, s0.st_ino) + key(s0)
finally:
os.close(fd)
6. Deduplication across machines
Granularity trade-off:
| Granularity | Good | Bad |
|---|---|---|
| Whole file | trivial index | misses edited near-duplicates |
| Fixed-size blocks | cheap, parallel | one insertion shifts every later boundary; dedup collapses |
| Content-defined chunking | insertion affects only nearby chunks | more CPU, larger index |
CDC (rolling-hash boundary detection, e.g. a Rabin or gear hash with 2–8 KiB average chunks) is the right default for versioned documents; store per-chunk digests and a file manifest, plus a top-level whole-file digest for fast equality.
The service: clients ask "is artifact X equal to any known artifact?" They send length and, if convenient, a local BLAKE3; the service answers "definitely different" or "candidate — send chunks." A persistent index maps blake3(chunk) → chunk_id, with manifests as ordered chunk_id lists; keep a refcount per chunk for garbage collection. Scope dedup by tenant unless policy allows global dedup, and use keyed hashes per tenant to stop membership probing. Q&A pairs: for a direct comparison, one round trip to a digest service or a content-addressed fetch; for a directory scan, hash locally with a shared cache so repeated scans are near-free.
7. Performance trade-offs
Small files: CPU and per-file syscall overhead dominate — batch, use cheap filters, cache aggressively. Large files: sequential I/O dominates — streaming, fadvise, and parallelism within the file. Whole-fleet scans: memory for the index and network for cross-machine queries dominate — compact keys, batch lookups, and prefilters that shrink the working set. Always state which regime you are optimizing for, and keep the invariant intact: filters and metadata may say "maybe different" or "skip," but only a collision-resistant digest (optionally followed by a literal byte comparison) may say "identical." A common mistake is treating mtime equality or a 64-bit hash as proof — both are wrong at scale, for different reasons.