Natural-Language Image Search Architecture

Medium · ML System Design · Member of Technical Staff, ML Systems · Onsite

Prompt

Architect a multi-tenant image search platform where organizations ingest photo libraries through offline bulk uploads and users search them using free-form natural-language phrases or questions.

Account for several core constraints in your design: - Bulk uploads may contain huge, high-resolution files arriving in large bursts, often with zero human-written captions—so free-text queries must still match raw visual concepts directly from pixel content. - Every query must strictly enforce both tenant boundaries and fine-grained per-folder or per-asset access permissions. - Whenever a source asset is replaced or deleted, that change must cascade reliably across every derived index, cache, and stored representation.

Pin down explicit assumptions around corpus size, search throughput, ingestion-to-searchable freshness, whether relevance combines visual appearance with embedded text (OCR) and structured metadata, and how human judgments or click signals can be collected.

Scope & Expectations

  • Safe bulk ingestion & asset hygiene: Handle high-volume batch uploads, oversized or malformed files, exact and near-duplicate detection, and automated screening for prohibited or unsafe imagery.
  • Multimodal indexing & ranking: Choose visual and lexical representations, approximate vector indexing, permission-aware filtering, and multi-stage reranking that balance recall, precision, and serving cost.
  • Lifecycle consistency: Guarantee zero cross-tenant or unauthorized leakage, propagate edits and deletions across all derived artifacts, and upgrade embedding models without downtime.
  • Evaluation & operations: Define offline ranking benchmarks, online experiments, latency budgets, and graceful degradation paths.

Step-by-step walkthrough

  1. Clarify requirements, scale, and hard guarantees

    Start by pinning down concrete production assumptions for the platform's open parameters:

    • What signals define relevance? All three: visual content inside the pixels (primary, since most uploaded photos have no human-written caption), text visible inside the image via OCR (optical character recognition)—software that detects and reads printed or handwritten words in pictures—and structured metadata (tags, filenames, capture dates, folder names). That immediately calls for hybrid retrieval: combining dense visual embeddings with exact keyword matching.
    • Who uses the platform and at what scale? Assume a multi-tenant B2B platform where 5,000 organizations store private image libraries:
      • Total corpus: 1 billion images (100 million in the largest tenant; 90% of tenants have < 1 million).
      • Ingestion rate: 10 million new images/day (~116 images/s average), arriving in bursty offline batches of up to 1 million images. File sizes average 8 MB and reach up to 200 MB (150 megapixels).
      • Query rate: 500 queries/s average, 2,000 queries/s peak.
    • Can we use human relevance feedback? Yes: paid human raters build offline evaluation sets, and implicit user actions (preview opens, downloads, document inserts, and "not relevant" clicks) are logged from tenants that opt in.

    Non-functional targets and hard invariants:

    • Search latency: p95 <= 400 ms server-side (95% of searches finish within 400 ms).
    • Ingestion freshness: p95 <= 30 minutes from batch commit to searchable via visual embeddings and OCR; heavier AI-generated captions may lag up to 24 hours.
    • Zero permission leaks (hard invariant): every query enforces both tenant isolation and object-level ACLs (access control lists)—rules specifying which users or groups may view each folder or file. Revoking access takes effect on the very next search.
    • Deletion SLA: deleted images vanish from search results within 60 seconds and are physically purged from every derived index, thumbnail store, and cache within 24 hours.
    • Availability: 99.9% for search; batch ingestion can queue during spikes without ever dropping committed files.
  2. Back-of-the-envelope storage and GPU sizing

    Work out storage and GPU fleet numbers early so every architectural choice is grounded in hardware reality:

    Storage across 1 billion images
    -----------------------------------------------------------------------------------------------
    Originals (object store)   10M/day * 8 MB = 80 TB/day;   1B * 8 MB              = 8.0 PB
    Derivatives (object/SSD)   256-px thumb (20 KB) + 512-px model input (60 KB)    = 80.0 TB
    Exact vectors on NVMe SSD  768 dims * 2 bytes (fp16) = 1,536 B/image            = 1.54 TB
    In-RAM ANN vector index    int8 vector (768 B) + HNSW layer-0 links (32 * 4 B)
                               + filter metadata (32 B) = 928 B/image               = 0.93 TB
    
    • Index sharding and small-tenant packing. Here HNSW (Hierarchical Navigable Small World) is an in-memory graph index where each vector links to nearby neighbors so searches hop rapidly toward the closest match instead of scanning every item, and int8 scalar quantization compresses each 16-bit float (fp16) coordinate into 1 byte (int8) to halve RAM. At 50 million vectors per shard (50M * 928 B = 46.4 GB RAM), 1 billion images fit in 20 logical shards (40 servers with 2x replication for availability). The 100M-image tenant gets 2 dedicated shards; thousands of smaller tenants each get their own isolated per-tenant mini-index packed onto shared multi-tenant nodes so we never mix tenants in one graph and never waste 5,000 separate machines.

    GPU sizing (throughput benchmarks to validate on target hardware):

    • Ingestion visual embedding (ViT-L at 336 px, ~400 images/s per GPU): average 116 images/s needs < 1 GPU, but clearing a 1M-image batch within 30 minutes (1,800 s) requires 1,000,000 / 1,800 = 556 images/s. Keep 4 GPUs warm and autoscale worker pools on queue depth so decode, OCR, and indexing comfortably share the 30-minute window.
    • OCR and background captioning: run a fast text-box detector on every image and invoke heavier text recognition only on regions containing words; run slow vision-language captioning (~20 images/s per GPU -> ~6 GPUs for 116 images/s) asynchronously on a 24-hour SLA.
    • Full-corpus re-embedding on model upgrade: 10^9 / 400 = 2.5M GPU-seconds = 694 GPU-hours (~7 hours on 100 GPUs). Storing the 512-px (60 KB) derivative is crucial here: reading 60 TB instead of 8 PB avoids petabyte network transfers and CPU bottlenecking on 150-megapixel image decodes.
    • Online query serving (2,000 peak QPS): encoding 2,000 short text queries/s takes 2-3 GPUs. Reranking the top 50 candidates per query means scoring 2,000 * 50 = 100,000 image-text pairs/s:
      • Option A (compact image tower at query time): fetch 60 KB derivatives from an NVMe SSD cache (100,000 * 60 KB = 6 GB/s), decode JPEGs directly on GPU hardware (nvJPEG so CPUs do not choke), and run a compact ViT-B (224 px) + cross-attention scorer at ~5,000 pairs/s per GPU = 20 peak GPUs with zero extra index storage.
      • Option B (precomputed patch tokens): store 64 compressed visual patch tokens per image (64 * 256 int8 B = 16 KB/image = 16 TB SSD) at ingestion and run only lightweight cross-attention layers at query time (~4 peak GPUs, trading 16 TB of SSD for 16 fewer GPUs). Either way, cross-modal reranking is the dominant serving cost and the first stage shed under overload.
  3. ML framing, training labels, and API contracts

    ML problem framing. Cast retrieval as multi-stage learning-to-rank: given (tenant_id, user_id, query_text, filters), return up to K permitted images ordered by calibrated relevance probability. Because users browse visual grids, top-heavy ranking quality in positions 1..20 matters most.

    Training and evaluation labels:

    • Human graded judgments (0 = off-topic to 3 = exact match): sampled across query slices (objects, attributes/colors, spatial relations, text-in-image, long natural-language questions, rare domain terms) from opted-in tenants, pooling candidate images from multiple models so raters judge unbiased pools (3 raters per pair).
    • De-biased implicit feedback: downloads and document inserts are strong positives; preview clicks are weak positives; explicit "hide / not relevant" clicks are negatives. Users click top-left thumbnails far more often regardless of quality—a distortion called position bias. Correct for it by randomizing adjacent pairs in the top results on a tiny traffic slice to estimate position examination probabilities, then weighting training clicks inversely by those probabilities.
    • Hard negatives: mine permitted images from the same tenant that scored high in approximate vector search (for example, a blue pickup truck on snow when the query asked for a red pickup truck) so models learn fine attribute distinctions.

    External REST API (extract tenant_id and user_id strictly from the verified authentication token, never from client JSON):

    POST /v1/search
      Body: { "query": "cracked turbine blade serial B-19",
              "filters": { "collection_ids": ["col_9"], "date_from": "2025-01-01" },
              "page_size": 50, "cursor": null, "safe_mode": "default" }
      200:  { "query_id": "q_81a", "next_cursor": "cur_50", "degraded": [],
              "results": [{ "image_id": "img_3", "score": 0.94,
                            "thumbnail_url": "https://cdn.../img_3?sig=...&exp=300s",
                            "matched_by": ["visual", "ocr"], "similar_count": 4 }] }
    
    POST   /v1/feedback            { "query_id", "image_id", "position", "action" }
    POST   /v1/batches             { "manifest": [{ "client_ref", "sha256", "bytes" }] } -> { "batch_id", "upload_urls" }
    POST   /v1/batches/{id}/commit
    GET    /v1/batches/{id}        -> { "indexed": 998120, "duplicate": 1800, "blocked": 5, "failed": 75 }
    PUT    /v1/images/{id}         (replaces image bytes -> increments content_version)
    DELETE /v1/images/{id}
    PUT    /v1/collections/{id}/acl
    

    Pagination caches the top 200 light-ranked IDs for 10 minutes under query_id. Page 1 (1..50) gets expensive cross-modal reranking; deeper pages use the light ranker's order, re-verifying permissions and deletion status on every page fetch.

  4. Data model and artifact registry

    Make the relational metadata database the single source of truth; every search index, cache, and thumbnail is a disposable derived view tracked in an explicit registry:

    images             (tenant_id, image_id) PK, content_version INT,
                       status: uploading | processing | active | blocked | deleted,
                       sha256, phash64, width, height, bytes, original_uri,
                       collection_id, owner_id, safety_labels, dup_cluster_id, created_at, exif
    
    tenants            tenant_id PK, acl_version INT (+1 on any ACL or group change)
    collections        (tenant_id, collection_id) PK, parent_id
    collection_acl     (tenant_id, collection_id, principal_id)   # principal = user_id or group_id
    image_acl_extra    (tenant_id, image_id, principal_id)         # rare single-file overrides
    group_members      (tenant_id, group_id, user_id)
    
    derived_artifacts  (tenant_id, image_id, kind, model_version, content_version, uri, status)
                       # kind in {thumbnail, input_512px, tile_vec, main_vec, ocr_doc, caption, phash}
    
    vector_index_row   key = (image_id, content_version, model_version)
                       ram_vec: int8[768], ssd_vec: fp16[768]
                       attrs: { collection_id, has_extra_acl, status, safety_class, dup_cluster_id }
                       inverted_list: collection_id -> sorted array of internal vector IDs
    
    keyword_index_doc  key = (tenant_id, image_id, content_version)
                       fields: ocr_text, generated_caption, tags, filename + same filter attrs
    

    Two schema decisions prevent operational nightmares later:

    1. Store collection_id on vectors, never expanded user lists. Sharing a 5-million-image folder with a new engineering group updates one row in collection_acl and bumps tenants.acl_version, rather than re-indexing 5 million vectors.
    2. Track every generated representation in derived_artifacts. When an image is updated or deleted, background workers have an exact checklist of files and index entries to replace or wipe.
  5. Draw the end-to-end ingestion and serving architecture

    OFFLINE BATCH INGESTION
      Client --(pre-signed multipart PUT)--> Object Store [quarantine/]
        | POST /v1/batches/{id}/commit
        v
      Batch Coordinator --> Per-Tenant Weighted Fair Queues (one idempotent task per image)
                                         |
            +----------------------------+----------------------------+
            v                            v                            v
      Sandbox Validator            Hash & Dedup                 Safety Gate
      (magic bytes, header         (SHA-256 content-addr,       (CSAM hash block, NSFW/gore
       pixel cap, safe decode)      64-bit pHash cluster)        classifiers, review queue)
            +----------------------------+----------------------------+
                                         v  (blocked images stop here — zero embeddings created)
                 Derivatives (256-px thumb, 512-px input, high-res tiles for >4000-px images)
                                         v
                 GPU Pools: ViT-L Embedder (30m SLA) | OCR (30m SLA) | VLM Captioner (24h SLA)
                                         v
                 Metadata DB (commits status=active, increments content_version)
                                         |  ordered per-image change-data-capture (CDC) log
                    +--------------------+--------------------+
                    v                                         v
          Tenant-Partitioned Vector Shards            BM25 Keyword Index Shards
    
    ONLINE SEARCH (p95 <= 400 ms)
      User --> API Gateway (auth token -> tenant_id, user_id) --> Search Orchestrator
                 1. Resolve user groups -> allowed collection_id bitmap (cached by acl_version)
                 2. Parse query intent + encode query text on GPU (768-d vector)
                 3. Parallel retrieval inside tenant partition:
                      [Selectivity Planner: Exact Scan vs Filtered HNSW]  ||  [Filtered BM25]
                 4. Fuse top 800 dense + top 200 BM25 via RRF -> GBDT Light Ranker (top 200)
                 5. Cross-modal GPU reranker on top 50 (reads 512-px inputs from NVMe SSD cache)
                 6. Collapse dup_cluster_id + diversify (MMR) + batched DB final ACL/version check
                 7. Mint 5-minute signed thumbnail URLs --> 200 OK (+ async impression log)
    
  6. Deep dive 1: safe batch ingestion, duplicates, and large or unsafe images

    Direct-to-quarantine upload and sandboxed decoding. Clients upload 200 MB raw files directly to object storage via pre-signed multipart URLs so API servers never buffer gigabytes of image traffic. Tasks are keyed by (tenant_id, batch_id, sha256) so retrying a batch commit never creates duplicate work. Before decoding any image:

    • Verify file magic bytes against an explicit format allowlist (JPEG, PNG, WebP, TIFF) and read only the image header to reject dimensions above 150 megapixels. Without a header check, a tiny malicious 50 KB file called a decompression bomb can expand into 40 GB of blank pixels in RAM and crash the host.
    • Decode inside a memory- and seccomp-sandboxed subprocess, using JPEG scale-on-decode, applying EXIF rotation, converting color profiles to sRGB, and stripping GPS coordinates unless tenant policy opts in.

    Exact vs. near-duplicates (without cross-permission information leaks):

    • Exact duplicates (SHA-256): within a single tenant, store raw bytes and 512-px / embedding derivatives by content hash with a reference count so identical uploads skip GPU work. Crucially, still create a separate images row in the new collection, and report "duplicate" in the batch summary only if the uploader already has read permission on the earlier copy—otherwise an attacker could probe whether confidential images exist in restricted folders or other tenants!
    • Near-duplicates (resizes, recompressions, slight crops): compute a 64-bit perceptual hash (pHash)—a compact fingerprint of low-frequency visual structure that stays nearly identical under resizing or JPEG compression. Candidate matches within Hamming distance <= 8 bits and embedding cosine similarity >= 0.95 share a dup_cluster_id. Keep all copies indexed (different teams may own different crops), and collapse duplicates at search time.

    Unsafe images and giant high-resolution scans:

    • Match perceptual hashes against known illegal-content databases (such as PhotoDNA / NCMEC lists) to quarantine, block from all indexes, and report automatically without human engineer exposure. Run NSFW/violence classifiers to populate safety_labels; blocked images never enter GPU embedding or OCR queues, guaranteeing zero vector leakage. Treat any OCR text passed to vision-language captioners strictly as untrusted data so embedded "ignore previous instructions" text cannot hijack prompts.
    • Because downscaling a 15,000 x 10,000 engineering blueprint to 336 px erases tiny parts and labels, an optional tenant setting slices images > 4,000 px into overlapping tiles (+40% index vectors if 10% of images use 4 tiles), running both tile embeddings (max-pooled per image) and full-resolution tile OCR.
    • Schedule tasks across per-tenant weighted fair queues so one customer's 1M-image migration never delays another customer's 20-photo upload past the 30-minute freshness SLA.
  7. Representations, hybrid retrieval, and three-stage ranking

    Why a dual encoder powers stage-1 visual retrieval. We cannot run heavy cross-attention between a query and 100 million images in 400 ms. Instead, use a dual encoder (such as CLIP or SigLIP)—two separate neural networks trained so matching images and text descriptions land near each other in one shared 768-dimensional vector space. Image vectors are precomputed once offline; at search time we encode the text query once and find nearby vectors via dot product, retrieving "forklift parked on wet loading dock" even when the photo has zero text metadata. Fine-tune on in-domain (image, caption/clicked-query) pairs from opted-in tenants using mined hard negatives.

    Why pair dense vectors with BM25 keyword search. Dense visual vectors struggle with exact part numbers ("B-19"), proper names, and quoted signs. Index OCR words, async VLM captions, tags, and filenames in an inverted keyword index scored by BM25—a classic term-frequency ranking formula that rewards rare, exact word matches while normalizing for document length.

    Three-stage fusion and ranking funnel:

    1. Candidate retrieval + Reciprocal Rank Fusion (1,000 candidates): fetch top 800 permitted vectors from dense search (re-scored from int8 to exact fp16 vectors on SSD) and top 200 from BM25. Merge them using Reciprocal Rank Fusion (RRF): RRF_score(d) = 1 / (60 + rank_dense(d)) + 1 / (60 + rank_bm25(d)). Because RRF uses rank positions rather than raw cosine or BM25 numbers, it needs zero fragile score calibration.
    2. Light learned ranker (1,000 -> 200 in ~1 ms on CPU): a Gradient-Boosted Decision Tree (GBDT) combining fp16 cosine score, per-field BM25 scores, exact OCR phrase match, query-type features, image resolution/sharpness, recency, and de-biased historical click features.
    3. Cross-modal reranker (top 50 in ~120 ms on GPU): a joint image-text transformer (ViT-B or precomputed patch tokens + cross-attention layers) lets every query word attend directly to every image region, accurately catching counts, negations, and spatial relationships ("worker WITHOUT hard hat next to ladder") that single-vector dot products blur together.
  8. Deep dive 2: permission-aware vector search at any selectivity

    Combining vector search with strict ACLs is the hardest systems problem in enterprise retrieval.

    Layer 1 — Physical/logical tenant partitioning. Route every search strictly to the authenticated tenant_id's dedicated shard(s) or isolated per-tenant mini-index. Because two tenants never share an HNSW graph or vector array, an indexing bug can never leak images across companies.

    Layer 2 — Selectivity-aware collection filtering. Expand the user's user_id and group_ids into a compressed bitmap of allowed collection_ids, cached in memory under (tenant_id, acl_version, user_id). Whenever any folder ACL or group membership changes, incrementing acl_version invalidates stale bitmaps immediately. Define selectivity as the fraction of the tenant's active images the user may view (N_allowed / N_tenant):

    User's allowed set in tenant          Planner strategy                    Why it wins
    ------------------------------------  ----------------------------------  -------------------------------------
    All collections (selectivity ~ 100%)  Standard HNSW traversal             Fastest (~5-15 ms), full >=95% recall
    Moderate share (selectivity >= 5%     Filter-aware HNSW (traverse all     Graph stays well-connected while
      and N_allowed > 200,000)            nodes, emit only bitmap matches)    collecting enough permitted neighbors
    Small set (N_allowed <= 200,000,      Exact SIMD int8 scan via inverted   Avoids empty post-filter pages AND
      e.g. 0.2% of a 100M-image tenant)   list collection_id -> vector_ids    disconnected graph walks (<10 ms!)
    

    See why naive post-filtering (fetching global top 1,000 from HNSW and dropping forbidden hits afterward) breaks: if an intern may view only 0.2% (200,000 images) of a 100M-image tenant, global top 1,000 yields 1,000 * 0.002 = 2 results on average—returning an almost blank page despite 200,000 valid images! Conversely, because each shard maintains an inverted list collection_id -> vector_ids and compacts vectors contiguously by collection_id, scanning 200,000 int8 vectors reads 200,000 * 768 B = 154 MB sequentially from RAM in < 10 ms on a few CPU cores with 100% exact recall.

    Layer 3 — Fail-closed final verification. Before returning the top 50 results, perform one batched primary-key lookup against the metadata DB to verify current collection_id / image_acl_extra access, status = active, and content_version. Backfill any dropped slot from ranks 51..200. If the permission store is unreachable, fail closed (return 503, never unverified images). Serve thumbnails exclusively via 5-minute cryptographic signed URLs.

  9. Deep dive 3: propagating updates, deletions, and model upgrades

    A single uploaded photo fans out into thumbnails, 512-px inputs, tiles, int8/fp16 embeddings, OCR docs, captions, pHash clusters, CDN edges, and training logs. Keep every copy consistent with three mechanisms:

    • Ordered per-image change log. Every mutation in the metadata DB increments content_version and emits a Change-Data-Capture (CDC) event partitioned by (tenant_id, image_id). Downstream index writers process versions idempotently, ignoring any event whose content_version is older than what they already store. On image byte replacement (PUT /v1/images/{id}), the final DB check suppresses the old content_version immediately until the new version finishes indexing (<= 30 min), so stale pixels never match queries.
    • Two-phase deletion (< 60 s hide, < 24 h physical purge):
      1. Phase 1 (Hide <= 60 s): set status = deleted in the metadata DB and broadcast image_id to an in-memory per-tenant deny-list on search orchestrators. Both the deny-list and the Layer-3 DB check block the image immediately.
      2. Phase 2 (Purge <= 24 h): async workers iterate through derived_artifacts for that (tenant_id, image_id), tombstoning vector/BM25 segments (physically erased on segment compaction), invalidating CDN thumbnails, decrementing content-addressed blob refcounts (deleting bytes at refcount 0), and scrubbing feedback/training tables.
      3. Audit reconciler: a daily background job diffs every index shard and bucket prefix against the metadata DB, purging orphans and paging on-call if "deleted > 24 h ago yet present anywhere" > 0.
    • Zero-downtime model upgrades (blue/green dual indexing). A v2 text encoder cannot query v1 image vectors because their coordinate spaces do not align. Spin up a parallel v2 index from the 512-px derivatives (~7 hours on 100 GPUs, temporarily doubling index RAM to ~1.86 TB), dual-write live uploads to both v1 and v2, validate offline slices and online tenant A/B metrics, cut traffic over to v2, and drop v1 after a safe rollback window.
  10. Evaluate, monitor, and handle production failures

    Evaluation and online experimentation:

    • Offline metrics by funnel stage: measure ANN recall@100 >= 0.95 against exact brute-force search across every selectivity bucket (isolating index approximations from model quality), fused recall@1000, and final nDCG@10 (Normalized Discounted Cumulative Gain)—a 0.0 to 1.0 ranking score that awards high credit when 3-rated exact matches appear near rank 1 and logarithmically discounts matches buried lower down. Slice results by query category (OCR text, fine attributes, rare classes) and enforce hard release gates (0 permission leaks on synthetic adversarial ACL tests; near-zero unsafe results).
    • Online testing: screen pure ranking tweaks quickly with interleaving (blending ranker A and ranker B into one deduplicated result grid per search to compare click preference with 10x higher statistical power), then run a 2-week user-level (or tenant-level for index changes) A/B test optimizing search success rate (share of searches followed by a download/insert within 5 minutes) under latency (p95 <= 400 ms) and zero-result guardrails.
    • Continuous production monitoring: track upload-to-searchable p95 lag (<= 30 min), deletion lag, embedding cluster drift, Layer-3 DB drop rate (signals CDC index lag), and continuous shadow exact-search recall on 0.1% of live queries.

    Latency budget (p95 <= 400 ms) and graceful degradation:

    Online stage                                               Planned ms   Failure / overload fallback
    ---------------------------------------------------------  ----------   -------------------------------------------
    1. Auth + resolve user groups -> cached ACL bitmap              15 ms   Fail closed (503) if auth/ACL DB unreachable
    2. Query parser + GPU text encoder                              15 ms   Fall back to BM25 keyword search only
    3. Tenant-partitioned ANN  ||  BM25 search (parallel)           40 ms   Fail over to replica; else BM25-only flagged
    4. RRF merge + CPU GBDT light ranker (1,000 -> 200)             10 ms   Serve raw RRF order
    5. Fetch top-50 512-px inputs from NVMe SSD cache               40 ms   Skip reranker if cache/storage slow
    6. GPU cross-modal reranker on top 50 (single GPU batch)       120 ms   First shed under load -> flag rerank_skipped
    7. Dedup clusters, MMR diversify, batched DB ACL re-check       20 ms   Fail closed if final DB ACL check errors
    8. Sign 5-min thumbnail URLs + JSON serialize                   10 ms   -
    ---------------------------------------------------------  ----------
    Planned server total                                           270 ms   (130 ms headroom for tail queueing <= 400 ms)
    
  11. Summarize the design trade-offs

    • Dual encoder + cross-modal reranker. Precomputed int8/fp16 dual-encoder vectors make billion-scale visual search fast without captions, while limiting joint cross-attention reranking to the top 50 captures fine spatial/attribute accuracy on just ~20 GPUs (~4 with precomputed patch tokens) and degrades cleanly under load.
    • Hybrid dense + BM25 via RRF. Pairing visual vectors with OCR/metadata BM25 handles both "snowy mountain cabin" and "invoice #INV-8841" without brittle score normalization.
    • Partitioned tenants + selectivity-planned ACLs + fail-closed DB check. Storing collection_id on vectors makes folder ACL updates instant, switching between filtered HNSW and contiguous collection_id exact scans prevents empty pages at low selectivity, and the final DB check guarantees zero leaks.
    • Versioned CDC + artifact registry + reconciler. Tracking content_version and every derived object lets soft-deletes hide images in < 60 s, physical purges complete in < 24 h with cryptographic/audit proof, and blue/green indexes upgrade models safely.

Intuition & how it works

Imagine organizing a 1-billion-photo archive shared by 5,000 separate companies, where most photos were dumped off cameras with cryptic filenames like IMG_4092.JPG and zero captions. You want an employee to type "forklift near wet floor sign B-12" and get matching photos in under 400 ms—without ever glimpsing a rival company's photo or a restricted HR folder inside their own company. To make that fast and accurate, we combine two fast "index cards" built ahead of time when each photo is uploaded—a visual meaning vector (capturing objects, colors, and scenes) and an OCR keyword card (words read off signs and labels inside the photo)—enforce security badge checks right inside the index, and hand only the top 50 finalists to a slower, eagle-eyed "art curator" neural network that inspects image regions and query words side by side.

A naive design fails in three ways: searching only human-written captions misses 90% of uncaptioned visual content; running a heavy vision-language model across 100 million photos per search would take hours of GPU time per query; and searching globally first, then filtering out forbidden photos afterward (post-filtering), returns empty pages whenever a user only has permission to view a small folder. Deleting a photo only from the main database also leaves ghost copies behind in vector indexes, thumbnails, and CDN caches.

Trace one search from an employee in Tenant 7 who has permission to view only 2 folders (120,000 photos out of Tenant 7's 80 million photos) and types "red safety valve tag 404":

  1. Permission setup (15 ms): The search service reads tenant_id = 7 and user_id from the auth token and fetches the user's cached bitmap of 2 allowed collection_ids.
  2. Parallel hybrid retrieval (55 ms): Because 120,000 allowed photos is small (<= 200,000), the query planner skips approximate graph search—which would waste hops on 79.88M forbidden nodes—and scans Tenant 7's contiguous collection_id int8 vectors directly (92 MB in < 8 ms with 100% recall), while BM25 (exact keyword search) matches "404" in OCR text across those same 2 folders.
  3. Fusion and GPU reranking (170 ms): Reciprocal Rank Fusion (RRF) merges the top visual and OCR hits into 1,000 candidates, a fast CPU tree model trims them to 200, and a cross-modal reranker (a joint image-text neural network) inspects the top 50 512-px thumbnails on GPU to confirm the valve is red and the tag reads 404.
  4. Deduplication and fail-closed check (30 ms): Near-duplicate burst shots collapse into one card ("+3 similar"), one batched database read re-verifies live ACLs and status = active, and 5-minute signed thumbnail URLs return at 270 ms.

Key trade-offs

  • Dual encoder vs. cross-modal reranker. A dual encoder (separate image and text towers like CLIP or SigLIP) precomputes one 768-d vector per image offline so searching 100M images takes one text forward pass plus a fast dot-product lookup, but compresses the whole image into one vector that can confuse attributes and negations ("helmet on" vs. "no helmet"). A cross-modal reranker jointly attends across query tokens and image patches for high precision, yet costs ~20 peak GPUs at 2,000 QPS even on just the top 50 candidates (~4 GPUs if we trade 16 TB of SSD to precompute compressed patch tokens)—so we restrict it to Page 1's top 50 and shed it first under overload.
  • Dense visual embeddings vs. BM25 keyword search. Dense embeddings capture uncaptioned visual concepts ("rusted pipe flange"), while BM25 over OCR (optical character recognition) text, tags, and filenames nails exact serial numbers and quoted text. Maintaining two indexes adds ingestion and storage overhead but eliminates each method's blind spots.
  • Post-filtering vs. filter-aware HNSW vs. exact scan. Post-filtering after ANN (approximate nearest neighbor) search is trivial to code but collapses to near-zero results when a user's selectivity (fraction of tenant images they may access) is tiny. Filter-aware HNSW (a multi-layer proximity graph index) handles medium-to-high selectivity well, while an exact SIMD scan over collection_id -> vector_ids lists guarantees 100% recall in < 10 ms below 200,000 allowed images, at the cost of maintaining a selectivity planner and collection-clustered segments.
  • Collection-level vs. per-image ACLs in the index. Storing only collection_id inside vector attributes makes folder ACL or group-membership edits take effect on the very next query via a lightweight acl_version cache bump; stamping expanded user lists onto every vector would trigger multi-million-document rewrites whenever a team changes folders.
  • Tiered ingestion freshness vs. GPU fleet cost. Running fast ViT-L embeddings and OCR within 30 minutes (~4 warm GPUs autoscaled for 1M-image batch bursts) makes uploads immediately searchable, while deferring heavy vision-language caption generation (~20 images/s per GPU) to a low-priority 24-hour queue avoids 5x GPU overprovisioning.
  • Quantization and high-resolution tiling. Compressing in-RAM vectors from 16-bit floats (fp16) to 8-bit integers (int8) cuts memory from 1.54 TB to 0.77 TB while SSD fp16 re-scoring recovers accuracy. Slicing > 4,000-px images into tiles preserves tiny visual details at the price of 3-5x more vectors per tiled image, so tiling is offered as an opt-in tenant policy.
  • Two-phase soft hide + async purge for deletions. Rewriting immutable HNSW and inverted-index segments on every DELETE call would thrash disk I/O; combining an immediate < 60 s in-memory deny-list + final DB check with < 24 h background compaction and a daily orphan reconciler meets strict privacy SLAs cheaply.

Common mistakes

  • Searching only generated captions instead of pixel embeddings. Captioners omit background objects, subtle textures, and domain-specific parts, violating the core requirement to match uncaptioned visual concepts.
  • Post-filtering permissions after global vector search. Fetching global top K and dropping unauthorized hits leaves narrow-access users staring at empty pages—or worse, sharing one HNSW graph across tenants where a filter bug leaks another company's images.
  • Trusting tenant_id or user_id from request payloads rather than extracting them exclusively from verified authentication tokens and failing closed (503) if the permission store is down.
  • Deleting only the primary database row, leaving deleted photos retrievable or viewable via stale vector shards, BM25 segments, CDN thumbnail caches, or future model training sets.
  • Querying v1 image vectors with a v2 text encoder during a model upgrade instead of building a blue/green shadow index from stored 512-px derivatives.
  • Decoding untrusted uploads inside main service processes without reading header dimensions first, allowing a 50 KB decompression bomb (a tiny compressed image that expands to tens of gigabytes of pixels) to crash workers with out-of-memory errors.
  • Leaking file existence through deduplication. Reporting "duplicate" across tenants—or across folders the uploader cannot read—lets an attacker test whether confidential images exist elsewhere.
  • Training rankers on raw click logs without correcting position bias (users clicking row 1 simply because it is row 1), causing the ranker to reinforce existing ordering mistakes.

Follow-up questions

  • How should the pipeline index and rank searches targeting words printed on signs, labels, or documents inside a photo? At ingestion, run text detection + OCR—including on full-resolution tiles for > 4,000-px images where downscaling blurs small lettering—and store recognized words, bounding boxes, and confidence scores. Index OCR text in BM25 using exact phrases, character n-grams, and character-confusion normalization (mapping "0"/"O" and "1"/"l"/"I" to canonical tokens at both index and query time so noisy OCR still matches). At search time, a lightweight query classifier spots text-intent signals (quotation marks, "sign saying ...", alphanumeric part codes) and boosts BM25 OCR weight in both RRF and the GBDT ranker, returning matching bounding boxes so the UI highlights the exact text region on the thumbnail.
  • How can you prevent bursts of nearly identical shots from crowding out diverse matches on the first results page? Group near-duplicates once at ingestion using a 64-bit perceptual hash (pHash) candidate check plus >= 0.95 embedding cosine confirmation to assign a shared dup_cluster_id, then collapse each cluster at query time to its highest-scoring permitted image with a "+N similar" expansion badge. Next, greedily reorder the top results using Maximal Marginal Relevance (MMR)—an algorithm that picks each next image d to maximize lambda * relevance(d) - (1 - lambda) * max_similarity(d, already_picked), penalizing candidates that look overly similar to results already chosen above them. Tune lambda (typically around 0.7) against offline nDCG@10 (graded top-10 ranking quality) plus distinct-cluster coverage before confirming in an online A/B experiment.
  • How would your ingestion, indexing, and serving paths adapt if users could search by uploading a reference photo? Pass the uploaded query image through the exact same magic-byte, header pixel-cap, sandboxed decode, and safety checks in memory without persisting it beyond the request lifecycle. Encoding a query image with our ViT-L image tower costs ~10x more GPU compute than encoding short text, but produces a 768-d vector in the exact same shared embedding space—so our tenant-partitioned, selectivity-planned vector search and permission checks work unchanged! For "find exact copies" queries, also check the pHash index directly; for fine-grained visual instance matching ("find this exact shoe SKU"), add or blend a self-supervised vision backbone (such as DINO-style features), and for multimodal queries ("this chair, but in green leather"), combine image and text embeddings via a lightweight composed-image-retrieval adapter trained on (reference_image, modification_text, target_image) triplets.

Follow-up questions

Similar questions

More Gimlet Labs interview questions

All 4 Gimlet Labs questions →