Design a Low-Latency Retrieval Layer for a Large-Scale Product Catalog
Machine LearningModel answerLast updated
Design the retrieval stage of a marketplace search system that surfaces relevant listings from tens of millions of items within a tight latency budget.
A marketplace lets shoppers type anything into a search bar — a product name, a vague description, even a use case ("gift for a 5-year-old who likes dinosaurs"). The catalog has tens of millions of active listings, each with a title, description, category, structured attributes (brand, condition, size, etc.), price, and availability status.
Your job is to design the system that takes a raw text query and quickly returns a set of relevant listing candidates. A downstream ranker will re-order those candidates before they reach the user, so you are optimizing for recall and speed rather than precision.
What you are expected to cover:
- Clarifying questions you would ask before designing anything
- How you define "relevance" in this context
- The retrieval architecture: what approaches you combine and why
- How embedding models are trained and kept useful over time
- How the index is built, updated, and served at scale
- How hard filters (category, price, availability) interact with retrieval
- How you measure whether the system is working, both offline and in production
- Where things can go wrong and how you handle degradation
Scope: Focus on the retrieval layer. You may briefly mention ranking, but do not design it in depth.
Hints
Hint 1
Start by asking about latency budget, query volume, and freshness requirements — the right architecture looks very different at p99 = 50 ms vs. 500 ms, and at 100 QPS vs. 100k QPS.
Hint 2
Purely lexical search (BM25) misses semantic matches; purely dense retrieval misses exact keyword matches. Consider how you combine both into one candidate set.
Hint 3
Filtering on price, category, or availability after ANN search can silently kill recall if many listings are filtered out — think about where in the pipeline filters should be applied.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarifying Questions First
Before proposing anything, pin down the numbers that drive every architectural decision:
- What is the latency budget for retrieval alone, and at what percentile (p50, p99)?
- What peak and average query rate must the system sustain?
- How quickly must a new listing, a price edit, or a sold/removed item appear in (or disappear from) results — seconds, minutes, hours?
- Is this retrieval producing candidates for a downstream ranker, or final results?
- Which filters are mandatory (availability, category, location radius, price band, condition)?
- What interaction logs exist: query strings, impressions, clicks, purchases, saves?
Assume reasonable answers: p99 retrieval ≤ 100 ms, ~50k QPS peak, new listings indexed within 5 minutes, output is a candidate set of ~500 listings for a ranker, availability filtering is mandatory.
Defining Relevance
Relevance here is not just topical similarity. A listing is relevant if it matches the user's intent, satisfies any hard constraints (in stock, correct category), and has a realistic chance of converting. That means the retrieval layer needs to balance semantic coverage (recall) with hard-constraint compliance, and leave the precision work to the ranker.
Retrieval Architecture: Hybrid Candidate Generation
Scoring every listing for every query is infeasible. Instead, use two complementary retrieval paths that run in parallel and whose results are merged before handing off to the ranker.
Lexical retrieval (BM25 / inverted index) Build an inverted index over tokenized title, description, and attributes. BM25 handles exact-match queries well ("Nike Air Max 90 size 11") and is fast. Use Elasticsearch or OpenSearch for this; they handle sharding and replication out of the box. Weakness: fails on paraphrases and zero-vocabulary queries.
Dense semantic retrieval (ANN over embeddings) Encode listings and queries into a shared dense vector space using a dual-encoder model (separate towers for query and listing, dot-product similarity). At query time, encode the query (~5 ms with a distilled model) and run approximate nearest-neighbor (ANN) search — HNSW or IVF-PQ via Faiss or a managed service like Pinecone or Weaviate. This handles semantic matches that BM25 misses. Weakness: can surface plausible-but-wrong matches for precise queries.
Merging Take the top-K from each path (e.g., 300 each) and deduplicate by listing ID. Reciprocal rank fusion is a simple, effective merge strategy that does not require a learned combiner. The merged ~500 candidates go to the ranker.
Embedding Model Training
The dual-encoder learns from interaction logs. A straightforward training setup:
- Positives: (query, listing) pairs where the user clicked, saved, or purchased after a search
- Hard negatives: listings shown but not clicked (in-batch negatives are cheap but too easy; mine hard negatives from BM25 results that were not clicked)
- Loss: in-batch softmax cross-entropy (NT-Xent) or a margin-based triplet loss
Use a pretrained language model (e.g., a small BERT or a domain-adapted sentence transformer) as the backbone to handle the long tail of rare queries. Fine-tune on marketplace interaction data. Retrain periodically (weekly is common) as the catalog and query distribution shift. Monitor embedding drift by tracking offline recall metrics after each retrain cycle.
Index Building and Freshness
Batch index build: Offline, embed all listings and build the ANN index. For 50M listings at 256-dim float32, raw vectors are ~50 GB; quantized (PQ) cuts this to ~6–12 GB, which fits in memory across a small fleet.
Incremental updates:
- New / edited listings: publish an event to a stream (Kafka). An indexing service consumes events, embeds the listing, and upserts the vector into the ANN index and the inverted index. Target: < 5-minute end-to-end latency.
- Sold / removed listings: soft-delete from the index on the same event stream. If the ANN index does not support efficient deletes (HNSW does not), maintain a small blocklist checked at retrieval time or schedule periodic full rebuilds overnight.
Serving at Scale
- Sharding: Partition the listing index by consistent hash of listing ID across N shards. Each query fans out to all shards and results are merged — or use a routing layer if listings are partitioned by category.
- Replication: Each shard has at least two replicas for availability and read throughput.
- Query encoding service: A small dedicated fleet runs the query encoder (GPU-accelerated or CPU with ONNX). Keep this stateless and horizontally scalable.
- Filter application: Apply mandatory hard filters (availability, price range) as pre-filters using metadata stored alongside the index. Pre-filtering before ANN search preserves latency but reduces the searchable space; post-filtering is simpler but can gut recall for narrow filters. A practical middle ground: pre-filter for high-cardinality hard constraints (availability = in-stock), post-filter for narrow ones, and monitor recall by filter combination.
- Graceful degradation: If the dense retrieval path times out, fall back to lexical-only results. Surface this fallback in monitoring. Never return an empty result set when a degraded-mode result exists.
Evaluation
Offline metrics (computed against a held-out set of query–listing pairs from interaction logs):
- Recall@K (K = 100, 500): fraction of relevant listings appearing in the candidate set
- MRR and NDCG@K if the candidates are ordered
- Index freshness: mean time from listing event to query-visible
Online metrics (A/B test a new retrieval model or config):
- Click-through rate and purchase rate on search results
- Zero-result rate and abandonment rate
- p99 retrieval latency per experiment arm
Common mistakes to flag:
- Optimizing only precision-oriented metrics while recall collapses — a ranker cannot recover a relevant listing that never made the candidate set
- Treating the ANN index as static while the catalog changes — sold listings surfaced as candidates destroy user trust fast
- Ignoring the cold-start problem: new listings with no interaction history get no signal for hard-negative mining; use content-based initialization for their embeddings
- Underestimating the cost of filter interactions — a "show only available items" filter on a 50M listing index can drop the effective index size by 30–50%, making recall targets much harder to hit
Summary
The core design is a hybrid retrieval layer: BM25 for lexical precision, a dual-encoder ANN index for semantic recall, merged with reciprocal rank fusion. The index is built offline and kept fresh via an event-driven incremental update pipeline. Serving is sharded and replicated with a query encoder service, hard filters applied pre- or post-retrieval depending on selectivity, and a lexical fallback for resilience. Evaluation uses Recall@K offline and click/purchase rates online.