Design a Reverse-Image Search Index at Scale
System DesignModel answerLast updated
Design a system that accepts an image query and returns visually similar images from a corpus of billions, covering storage, indexing, and retrieval trade-offs.
Reverse-Image Search Index
Background
You are joining a team building a reverse-image search feature for a large media platform. Users can upload or paste any image and instantly receive the most visually similar images from a catalog of 5 billion photos. The catalog grows by roughly 10 million new images per day.
Functional Requirements
- Query: Given an image (upload or URL), return the top-K (default K=20) most visually similar images.
- Ingest: New images added to the catalog are searchable within 5 minutes.
- Delete: An image removed from the catalog (e.g., copyright takedown) must stop appearing in results within 1 hour.
Non-Functional Requirements
- Query latency: p99 < 300 ms end-to-end (including embedding generation).
- Write throughput: sustain ~115 images/second on average with 3× burst headroom (~350/s).
- Availability: 99.9% uptime for queries; ingest may tolerate brief degradation.
- The catalog is read-heavy: roughly 5,000 queries per second at peak.
Out of Scope
- Training the image embedding model itself.
- Content moderation or deduplication logic.
- User authentication.
What is Expected
Walk the interviewer through:
- API design (ingest, query, delete endpoints).
- Data model — what you store and where.
- Architecture — the end-to-end pipeline from image upload to search result.
- Indexing deep dive — how approximate nearest neighbor (ANN) search works here and which data structure / algorithm you'd choose.
- Trade-offs — at least two meaningful decisions with pros/cons.
- Failure modes — what breaks first and how you mitigate it.
Hints
Hint 1
Start by estimating the storage footprint: if each embedding is a 512-dimensional float32 vector, how many bytes is that for 5 billion images? Does it fit in RAM?
Hint 2
Think about why exact nearest-neighbor search (brute-force dot product over 5B vectors) is infeasible at p99 < 300 ms, and what ANN index structures (HNSW, IVF, LSH) trade off recall for speed.
Hint 3
For the freshness requirement (searchable within 5 minutes), consider whether your ANN index supports online inserts or requires periodic rebuilds, and what that means for your architecture.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
1. Capacity Estimation (set the stage)
- Embedding size: 512-dim float32 = 2 KB per vector.
- 5 billion vectors: 5 × 10⁹ × 2 KB = ~10 TB of raw embedding data. This does not fit in a single machine's RAM (typical large servers have 0.5–2 TB RAM), so the index must be distributed or quantized.
- Metadata per image (URL, timestamp, content hash, tags): ~500 bytes → ~2.5 TB additional. Store in a standard key-value or columnar store.
- Write rate: 10M images/day ÷ 86,400 s ≈ 115/s average, 350/s burst.
2. API Design
POST /v1/images
Body: { image_bytes | image_url }
Returns: { image_id, status: "accepted" }
GET /v1/search
Params: image_id | image_url | image_bytes (multipart), k=20
Returns: { results: [{ image_id, score, metadata }] }
DELETE /v1/images/{image_id}
Returns: { status: "accepted" }
All writes are asynchronous — the caller gets an accepted response and the system fulfills the SLA (5-minute indexing) in the background. The search endpoint is synchronous with a target of p99 < 300 ms.
3. Data Model
| Store | Contents | Technology choice |
|---|---|---|
| Object store | Raw image bytes | Cheap blob storage (S3-compatible) |
| Vector store | embedding (float32[512]), image_id, is_deleted flag | Distributed ANN index (see §5) |
| Metadata store | image_id → URL, upload_time, checksum, tags | Key-value store (e.g., DynamoDB or Cassandra) |
| Embedding cache | Recent query embeddings, keyed by image hash | In-process LRU + Redis |
The is_deleted flag allows soft deletes that propagate fast; a background job does hard purges from the index.
4. End-to-End Architecture
Client
│
▼
API Gateway / Load Balancer
│ │
▼ ▼
Ingest Service Query Service
│ │
▼ ▼
Embedding Embedding
Model Server Model Server (GPU fleet, shared)
│ │
▼ ▼
Message Queue ANN Index Cluster
(Kafka) (sharded, replicated)
│
▼
Index Writer Workers
│
▼
ANN Index Cluster ◄──── Metadata Store
Ingest flow:
- API receives image, stores raw bytes in object store, publishes
{image_id, object_key}to Kafka. - Embedding workers consume from Kafka, call the GPU embedding service, publish
{image_id, vector}to a second topic. - Index writer workers consume vectors and upsert into the ANN index cluster. End-to-end this should be well within 5 minutes.
Query flow:
- Query service receives the query image.
- Calls the shared GPU embedding service (~50–80 ms for a single image).
- Issues an ANN search against the index cluster (~20–50 ms at scale with quantization).
- Fetches metadata for top-K results from the metadata store.
- Applies any soft-deleted filter; returns results.
Total budget: ~200 ms leaves headroom for p99 at 300 ms.
5. Indexing Deep Dive — ANN Index Choice
Why not exact search? A brute-force scan of 5 billion 512-dim vectors takes ~5 trillion multiply-adds. Even on optimized SIMD hardware that is ~seconds, not milliseconds.
Candidate algorithms:
| Algorithm | Recall@20 | Query latency | Build / insert cost | Notes |
|---|---|---|---|---|
| HNSW | ~98% | Very low (graph traversal) | High memory, supports online inserts | Best recall/latency; memory-intensive |
| IVF-PQ (Faiss) | ~90–95% | Low | Moderate; needs periodic retraining of centroids | Space-efficient via product quantization |
| LSH | ~80–85% | Low | Cheap | Lower recall, mostly superseded |
Recommendation: IVF-PQ sharded across nodes, with a small HNSW delta index per shard for recent inserts.
- IVF (Inverted File): cluster vectors into ~65,536 centroids; at query time probe the nearest ~256 clusters.
- PQ (Product Quantization): compress 512-dim float32 → 64 bytes (8× compression), reducing 10 TB to ~1.25 TB — now fits in the combined RAM of a modest cluster.
- Delta HNSW: new vectors land here first (supports O(log n) online inserts), satisfying the 5-minute freshness requirement. Nightly a background job merges the delta into the main IVF-PQ index.
- Sharding: partition by image_id hash across, say, 20 shards. Each query fans out to all shards; a scatter-gather coordinator merges top-K results. Shards are replicated 3× for availability.
6. Two Key Trade-offs
Trade-off 1 — Recall vs. latency (IVF probe count) Probing more clusters improves recall but increases latency linearly. At 256 probes out of 65,536, you hit ~93% recall with ~30 ms query time per shard. Increasing to 512 probes raises recall to ~97% but doubles query time. Pick based on product requirements — 93% recall is usually acceptable for "visually similar" use cases.
Trade-off 2 — Online inserts vs. index quality (delta index) HNSW supports fast online inserts but consumes ~60 bytes/vector vs. PQ's ~8 bytes/vector. Keeping the delta small (e.g., last 24 hours ≈ 10M vectors ≈ 600 MB per shard) is acceptable, but if the merge job lags, the delta grows and query fanout latency grows with it. Mitigate with a circuit breaker that pauses ingest if the delta exceeds a size threshold.
7. Failure Modes and Mitigations
| Failure | Impact | Mitigation |
|---|---|---|
| GPU embedding service down | All ingest and queries stall | Multiple GPU replicas; queue-backed ingest decouples write path |
| ANN shard unavailable | Queries return degraded results (miss that shard) | Return partial results with a degraded flag rather than failing; replica failover |
| Delta index grows unbounded (merge lag) | Query latency increases | Alert on delta size; auto-scale index writer fleet; shed low-priority ingest |
| Deleted image still appears (soft delete lag) | Policy / legal risk | Filter is_deleted at query time in metadata lookup as a safety net (adds ~5 ms); hard delete SLA is 1 hour |
Common Mistakes to Avoid
- Proposing a single-node FAISS index — 10 TB of vectors requires distributed sharding.
- Ignoring the embedding step in latency budget — GPU inference is typically the largest single contributor.
- Assuming the ANN index supports instant online inserts without an architectural answer for freshness.
- Forgetting the delete requirement; "hard delete from ANN index" is non-trivial and usually requires a rebuild or delta journal.