Building a Copy-Detection Pipeline for Massive Photo and Video Libraries
System DesignModel answerLast updated
Design a platform that finds re-uploaded or lightly edited photos and videos across billions of items, covering fingerprinting, indexing, match thresholds, evaluation and abuse resistance.
Problem
You are asked to design a service that recognizes when a photo or video is a copy of something already in a very large media collection. Copies may be re-uploads, re-encodes, or lightly altered versions of an original. The results drive three downstream actions: removing content, merging duplicates into one canonical item, and cleaning datasets.
Requirements
- Handle both images and videos.
- Remain robust to resizing, cropping, re-encoding, watermarks or overlays, and small edits.
- Support high-volume ingestion and low-latency lookups for takedown, merge, and dedup decisions.
- Scale to billions of media items.
What to cover
- Fingerprinting strategy. Compare perceptual hashing with learned embeddings, and say what you would actually deploy and why. Explain how the approach extends from images to video.
- Indexing and retrieval architecture. Describe the ingestion path, the query path, index types, memory and storage sizing, sharding, and how fresh uploads become searchable.
- Decisions and operations. Explain how you set thresholds for different use cases, how you evaluate quality offline and online, how you limit false positives, and how you defend against users who deliberately try to evade detection.
State your scale assumptions (corpus size, upload rate, latency targets) explicitly and justify the trade-offs you make.
Hints
Hint 1
Think of a cascade rather than a single method: cheap, exact or near-exact checks first, then a more robust but costlier learned representation, then an expensive verification step on a small candidate set.
Hint 2
For billions of vectors, compressed approximate nearest-neighbor indexes with a full-precision rerank are the usual answer; for compact binary hashes, consider splitting the bits into chunks so that a close match must agree closely on at least one chunk.
Hint 3
Video is the image problem plus time: sample frames, retrieve candidate videos by frame matches, then verify by aligning the frame sequences so trims, speed changes and embedded clips are handled and a matched duration can be enforced.
Hint 4
Different actions need different precision. Calibrate a combined score, choose per-use-case operating points, and be careful that clustering over match edges does not chain unrelated items together.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify use cases and scale
The use case sets the precision target, so settle it first.
| Use case | Precision need | Latency | Note |
|---|---|---|---|
| Takedown / known-bad matching | Very high (99.9%+) | Under ~200 ms at upload | Wrong removals are costly; route borderline cases to humans |
| Merge / canonicalize reuploads | High | Seconds, async fine | Feeds counts and attribution |
| Training-set dedup | Recall-oriented | Batch | Over-removing is cheap |
Assumptions: about 5B images and 500M videos; roughly 20 keyframes per video gives about 10B frame vectors, so ~15B vectors total. Ingest ~50M images/day (~600/s average, ~3k/s peak) and ~2M videos/day. Image query p99 under 200 ms; video results within a minute of transcode.
2. Fingerprinting: a cascade, not a choice
- Exact hash of bytes or decoded pixels. A key-value lookup that catches byte-identical reuploads, often a third or more of duplicates, at almost no cost.
- Perceptual hash (e.g., a 256-bit DCT-based hash such as PDQ). Compact (32 B), explainable, shareable with external hash lists, robust to resize, recompression and mild color changes. Weak against crops, rotations, overlays and picture-in-picture.
- Learned copy-detection embedding (self-supervised, contrastively fine-tuned, 256-d, L2-normalized). This is the main robustness layer. Train with heavy augmentations (crops, text and emoji overlays, flips, blur, borders, screenshots) and with hard negatives such as different photos of the same landmark or one meme template with different captions. Without hard negatives the model learns semantic similarity instead of copy similarity, which produces false positives.
- Local features plus geometric verification (keypoints and RANSAC) only on the small shortlist, for heavy crops and picture-in-picture.
Video extends this along time: decode at about 1 fps, detect shots and keep keyframes, compute a hash and embedding per keyframe, and build a pooled video-level vector for cheap candidate generation. Verify candidates by temporal alignment: a dynamic-programming or Hough-style diagonal search over the frame-similarity matrix. This handles trims, speed changes and a clip inside a longer video, and it returns matched segments. An audio fingerprint is an independent signal when visuals are heavily altered.
3. Architecture
Ingestion (async, via a queue): upload, object store, decode/transcode workers, GPU embedding workers, fingerprint store and index writers (fresh delta index), then a match job that writes edges and updates clusters.
Query path: exact-hash lookup, then hash Hamming search, then embedding ANN top-100, then rerank with full-precision vectors, then verification (local features or temporal alignment), then calibrated score, then policy (auto-action, human review, or ignore).
Index sizing:
- Embeddings: IVF-PQ with roughly 64K to 1M coarse centroids and about 64 B per vector gives ~1 TB of codes for 15B vectors, sharded over tens of memory-heavy nodes with replicas for QPS. Full fp16 vectors (~7.5 TB) stay on SSD for reranking only.
- Hashes: multi-index hashing. Split 256 bits into 16 chunks of 16 bits. If two hashes differ in at most 31 bits, pigeonhole guarantees at least one chunk differs by at most 1 bit, so each query probes about 16 x 17 buckets and then checks full Hamming distance. Storage is about 480 GB.
- Freshness: new items go to an in-memory delta index (e.g., HNSW) searched alongside the main index; a periodic merge rebuilds the big shards.
- Known-bad lists get their own small, high-recall index so takedown never depends on the giant index.
- Sharding: shard by vector ID and fan out to all shards (balanced, simple), or route by coarse centroid to reduce fan-out at the cost of skew.
4. Thresholds and decisions
- Combine signals (hash distance, cosine similarity, inlier count, temporal coverage, audio match) in a small classifier trained on labeled pairs, giving a calibrated probability.
- Pick per-use-case operating points from precision-recall curves. Takedown auto-acts only at a 99.9%+ precision point and sends a middle band to human review. Dedup uses a lower threshold.
- For video, require minimum matched duration (for example 3 s or 20% coverage). Shared intros, logos and black frames otherwise cause false matches.
- Avoid cluster drift. Plain union-find over edges chains A
BC~...~Z into unrelated items. Require members to match the canonical item or medoid, or use community detection with a high edge threshold.
5. Evaluation
- Offline: public copy-detection benchmarks for images and video, plus an internal synthetic augmentation suite and a labeled set of real hard cases. Report precision at fixed recall, recall at fixed precision, and results sliced by transformation type.
- Retrieval quality: compare ANN recall against brute force on a sample to separate index loss from model loss.
- Online: sample auto-actions for human audit, track reviewer overturn rate, appeal rate, and the share of duplicates caught within a time window. Shadow-run new models before switching.
6. Operations and adversaries
- Versioning: store fingerprints per model version, dual-write and dual-query during migrations, then backfill and cut over.
- Adversarial behavior: attackers add borders, mirror, rotate, speed-shift, overlay noise or collage content. Counter with augmentations in training that mirror observed evasions, matching on flipped or rotated query variants, local-feature verification, and audio signals. Monitor misses reported by users and feed them back as training data. Rate-limit and detect probing, since attackers may test variants against the system.
- Cost: a GPU worker handles on the order of 2k images/s at low resolution, so peak ingestion needs only a modest pool; video decode dominates. Skip expensive stages when the exact-hash or a strong hash match already resolves the item.
- Safety: human review for sensitive actions, audit logs of every edge and decision, and a way to purge or correct a bad entry from a hash list quickly.
Common mistakes
- Using only perceptual hashes (fails on crops and overlays) or only embeddings (loses cheap exactness and explainability).
- Training without hard negatives, so semantically similar but different images match.
- One global threshold for all products.
- Matching video on a single frame, so shared intros trigger false positives.
- Unconstrained transitive clustering.
- Ignoring index freshness, leaving new uploads unsearchable until the next rebuild.