Design a visual search system like Pinterest or Google Lens

    Visual search (Pinterest Lens / Google Lens) finds visually similar items from a query image. It converts images to embeddings and does approximate nearest-neighbor search over a huge vector index, then re-ranks.

    AI & Machine Learning, 7 components, about 35 min

    1. Scope

    In scope

    • • Search by image
    • • Deep feature extraction
    • • ANN retrieval at scale
    • • Re-ranking

    Out of scope

    • • Model training
    • • Text search
    • • AR overlay

    2. Functional requirements

    Must have

    • • Upload an image → similar results
    • • Sub-second retrieval
    • • Scale to billions of images
    • • Rank by visual + business relevance

    Nice to have

    • • Object detection (search a region)
    • • Filters
    • • Personalization

    3. Non-functional requirements

    Latency< 500 ms end-to-end
    ScaleBillions of indexed images
    RecallHigh via ANN tuning
    FreshnessNew images indexed continuously

    4. Back-of-envelope estimation

    Assumptions

    • • 2B images indexed
    • • Embedding 512-dim
    • • Top-100 candidates → re-rank
    • • HNSW/IVF-PQ index

    Derived numbers

    Vector index~4 TB— 2B × 512 × 4B (pre-PQ)
    With PQ~128 GB— 64-byte codes: 32× smaller than 2 KB float32 vectors
    ANN latencysub-ms per shard

    5. API design

    POST/api/visual-search

    Upload image → ranked similar items

    6. High-level design

    What each box in the reference diagram is responsible for:

    Search API — Coordinates extract → ANN → re-rank → enrich.
    Feature Extractor — CNN (ResNet) / ViT → 512-dim embedding.
    Vector DB — ANN index (Milvus/Pinecone), sharded.
    Re-ranker — Precision ranking (LightGBM) on top candidates.
    Image Store (S3) — Original images.
    Metadata DB — Item attributes for enrichment.

    7. Data model

    Vector DB: image_id → embedding[512]— PQ-compressed, sharded

    8. Deep dives

    Image embeddings

    A deep vision model (ResNet/ViT) maps an image to a fixed-length vector where visual similarity ≈ vector closeness. The same model embeds both the catalog (offline) and the query (online), so search becomes nearest-neighbor in embedding space.

    ANN over billions of vectors

    Exact nearest-neighbor over billions of 512-dim vectors is infeasible per query. Approximate indexes — HNSW (navigable small-world graphs) or IVF-PQ (inverted file + product quantization) — give sub-millisecond retrieval at high recall. PQ also compresses vectors ~10×, making the index fit in memory.

    Two-stage retrieve + re-rank

    Stage 1: ANN returns ~100 visually similar candidates fast (recall-oriented). Stage 2: a heavier re-ranker (LightGBM with visual + business features like popularity/availability) precisely orders the small candidate set. This balances speed and quality.

    Sharding & freshness

    Shard the vector index (by id or cluster) and replicate for QPS; queries scatter-gather across shards. New images are embedded and upserted continuously so the index stays fresh.

    9. Bottlenecks

    • Index memory → product quantization
    • Query fan-out → sharding + replication
    • Re-rank cost → only on top-k candidates

    10. Trade-offs

    Index type

    Choose: IVF-PQ for billions of vectors (compressed in memory) or HNSW for up to hundreds of millions where memory allows.

    Instead of: Exact search: perfect recall, linear cost per query.

    Approximate search gives >95% recall at a tiny fraction of the cost.

    Compression

    Choose: Product quantization to 64 bytes per vector (32× smaller than 512 float32), with full-precision re-scoring of the top candidates.

    Instead of: Store full vectors in memory: ~4 TB for 2B images.

    Memory decides the fleet size; reranking recovers most lost accuracy.

    Embedding model updates

    Choose: Version embeddings; a new model means re-embedding the corpus into a new index and switching over.

    Instead of: Mix old and new embeddings: vectors from different models are not comparable.

    Every model upgrade is a full backfill; plan the compute for it.

    11. Failure modes

    Recall drops after index rebuild

    Relevant matches missing.

    Mitigation: Measure recall@k against exact search on a sample before swapping indexes.

    Hot shard

    Latency spikes.

    Mitigation: Replicate shards and spread queries; balance by vector count.

    Inappropriate images surface

    Trust and safety issue.

    Mitigation: Safety classifiers at ingest and filtering at serve time.

    12. What interviewers probe

    Answer each one yourself before opening it.

    How do you search a crop of an image (for example a lamp in a room photo)?Show a strong answer

    Run object detection first, embed each detected region, and search per region.

    How do you shard 2B vectors?Show a strong answer

    Split into shards of ~100M, query all shards in parallel, merge top-k; or route by IVF cluster to fewer shards.

    How do you combine visual similarity with filters like price?Show a strong answer

    Pre-filter with attributes inside the ANN index when supported, or over-fetch and post-filter.

    How are embeddings trained?Show a strong answer

    Contrastive learning on image pairs (and image-text pairs) so similar items are close; fine-tuned on product click data.

    Sign in to track this guide in your curriculum progress.