Build a Natural-Language Image Search Service with Access Control
System DesignModel answerLast updated
Design a service that lets users find images from free-text descriptions, handling batch ingestion, joint embeddings, permission filtering, ranking, evaluation, updates, and deletions.
Problem
Your team is building a search product over a large collection of images. Images are loaded in bulk by batch jobs, not through an interactive upload flow. End users type a sentence or phrase describing what they want (for example, "a whiteboard covered in architecture diagrams") and expect the best-matching images back.
Design the end-to-end system.
Requirements and assumptions
- Images can be large, and they arrive in batches.
- A query must find images by what they show, even if nobody ever wrote a caption or tags for them.
- Every result must respect tenant boundaries and per-object permissions.
- When an image is changed or removed, every derived artifact (thumbnails, embeddings, OCR text, index entries, caches) must reflect that.
What to cover
- Ingestion pipeline: validation, safety checks, preprocessing, enrichment, and provenance.
- How images and text queries are represented so they can be compared.
- Metadata and permission handling at query time.
- Candidate retrieval and a more precise ranking stage.
- How you would measure quality, both offline and online.
- Updates, deletions, near-duplicates, and unsafe content.
- Monitoring, failure modes, and fallbacks.
Questions worth raising with the interviewer
- Should relevance be driven by visual content, text inside the image (OCR), metadata, or a mix?
- What are the corpus size, peak query rate, latency target, and freshness expectation for new uploads?
- Is human relevance feedback available, and how much?
Hints
Hint 1
Think of two parallel paths: an offline, batch-oriented pipeline that turns each image into searchable representations, and an online path that embeds the query, retrieves candidates, filters by permission, and reranks.
Hint 2
A contrastively trained image-text model gives a shared embedding space, so a text query can match images with no caption. Decide whether permission filters are applied before, during, or after the approximate nearest-neighbor search, and what each choice costs in recall and latency.
Hint 3
Treat each image as a versioned entity with content hash, ACL version, and derived artifacts keyed to that version. This makes deletes, updates, and dedup tractable, and it gives you a clean way to separate offline relevance metrics from online behavior metrics.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify and size the problem
I would first pin down: what "relevant" means (visual concepts, OCR text, metadata, or a blend), corpus size, QPS, latency budget, and freshness. For a concrete target, assume 100M images, ~200 QPS peak, p95 under 300 ms end to end, new uploads searchable within ~15 minutes, and a tenant-based multi-tenant model with object-level ACLs. I would also ask whether click or rating feedback exists, since it determines how far I can go with learned reranking.
2. Architecture overview
Two paths:
- Offline/batch path: object store -> validation and safety -> preprocessing -> enrichment (embedding, OCR, optional caption) -> index and metadata store.
- Online path: query -> normalization and embedding -> filtered ANN retrieval (plus optional lexical) -> permission re-check -> reranker -> response.
3. Ingestion
- Landing: batches write original bytes to an object store with an immutable key. A manifest per batch lists items; workers pull from a queue, so retries are safe and idempotent.
- Validation: check magic bytes, not just extension; enforce size and dimension limits; decode in a sandboxed worker to guard against decompression bombs and malformed files; strip or record EXIF (and remove GPS if policy requires).
- Safety: run a content-moderation classifier and, where relevant, hash matching against known-bad lists. Unsafe items are quarantined and never reach the index.
- Preprocessing: normalize orientation, color space, and resize to the model's input size; keep a thumbnail for the UI.
- Dedup: exact duplicates via a content hash (SHA-256). Near duplicates via a perceptual hash or by clustering embeddings with a high similarity threshold. Store a
canonical_idand keep duplicates as aliases so ACLs from each owner are still honored, but collapse them at display time. - Provenance: every derived artifact records
image_id,content_hash,version,model_version, and pipeline version.
4. Representation
- Core: a dual-encoder image-text model (CLIP/SigLIP-style) places images and text in the same vector space. Query text goes through the text tower; cosine similarity ranks images. This works with no captions.
- Fine-tuning: if the domain is specialized (e.g., product photos, medical, or screenshots), fine-tune with in-domain pairs and hard negatives; evaluate against the base model before shipping.
- Enrichment for hybrid search: OCR text, auto-generated captions, and user metadata feed a lexical index (BM25). Hybrid retrieval helps with rare names, text in images, and exact attributes that embeddings blur.
- Storage: embeddings of 512-768 dims, stored in float16 or product-quantized form. 100M x 512 x 2 bytes is about 100 GB raw, so it needs sharding and compression.
5. Metadata and permissions
- Store
tenant_id,owner, ACL groups,acl_version, timestamps, and tags with each index entry. - Tenant isolation: the hard boundary. Either separate indexes or shards per large tenant, or a mandatory
tenant_idfilter for small ones. - Object-level filtering: pass a filter into the ANN query (filtered HNSW or IVF with pre-filter bitsets). Post-filtering alone loses recall when the filter is selective, because the top-K might be mostly forbidden items. For highly selective filters, fall back to brute-force scan over the allowed subset.
- Authoritative re-check: index ACLs can lag. Before returning, verify permissions for the final top results against the source-of-truth ACL service. This protects against stale ACL data leaking results.
6. Retrieval and reranking
- Candidate generation: ANN (HNSW or IVF-PQ) returns top ~200-500 using the query embedding; optionally merge with BM25 candidates using reciprocal rank fusion.
- Reranking: a heavier model scores each (query, image) pair: a cross-modal reranker or a vision-language model, possibly combined with features such as OCR match, recency, and quality score. Run on the top ~50-100 to stay in budget.
- Post-processing: collapse near duplicates, apply diversity (MMR) if results are repetitive, and apply safe-search settings.
Trade-off: higher ANN recall (larger efSearch/nprobe) costs latency and CPU; reranker depth costs GPU. Tune on a recall@K versus latency curve.
7. Evaluation
- Offline: build a labeled set of queries with graded relevance judgments (human raters, sampled from production queries). Report recall@K for the candidate stage, and nDCG@10 / MRR / precision@K for the final ranking. Measure ANN recall separately by comparing with exact search.
- Online: click-through, successful-session rate, query reformulation rate, time to first useful click. Run A/B tests.
- Don't conflate: clicks are biased by position and thumbnails; offline gains don't always translate. Use offline metrics as a gate and online tests as the decision. Slice by query type, tenant, and language.
8. Updates and deletions
- Model the image as
(image_id, version). An update creates a new version; a pointer flips atomically once all derived artifacts are built. - Deletes: write a tombstone event consumed by every downstream store (vector index, lexical index, thumbnail cache, OCR store, result caches). Query-time filtering on a "deleted" bitset provides immediate effect while physical removal and index compaction happen later. Keep an audit of deletion completion; for legal deletions, verify all stores.
- ACL changes: propagate via events; apply the authoritative re-check so staleness cannot expose data.
- Model upgrades: re-embedding changes the vector space. Build a new index in parallel, shadow-test, and switch over; never mix embeddings from different models in one index.
- Freshness: a small real-time delta index for new items, merged periodically into the large base index.
9. Failure cases and monitoring
- Duplicates flooding results: handled by dedup and collapse.
- Unsafe images: quarantined at ingestion; also filter at query time in case moderation policies change.
- Bad or empty queries: fall back to lexical/metadata search; return a helpful empty state.
- Index or reranker outage: degrade gracefully to ANN-only ordering, or to cached popular results.
- Drift: monitor the query distribution, embedding norms and score distributions, zero-result rate, and rolling nDCG on a golden query set.
- Privacy: never log raw images or permission-sensitive content in plain form; scope caches by tenant and user.
Common mistakes
- Post-filtering permissions after ANN and silently returning too few or no results.
- Forgetting to delete derived data (embeddings, thumbnails, caches) on removal.
- Mixing embeddings from different model versions.
- Judging quality only with click data, or only with an unrepresentative offline set.
- Ignoring near-duplicates, which wastes the top-K slots.
- Sending every candidate through an expensive reranker without a latency budget.