Design a Product Discovery and Ranking Platform
Machine LearningModel answerLast updated
Design an end-to-end search system for a large online marketplace, covering query understanding, retrieval, ranking, indexing pipelines, and serving infrastructure.
Scenario
You are a senior ML engineer at a large online marketplace with hundreds of millions of listed items. The team wants to rebuild the product discovery experience from the ground up.
Shoppers type natural-language queries like noise cancelling headphones under $80, optionally narrow results with filters (price range, brand, average rating, availability), and expect a tight, well-ranked list of relevant items back within a fraction of a second. The catalog is enormous, prices and stock levels shift constantly, and the same query should feel slightly different for a power user who always buys Sony versus a first-time visitor.
Your Task
Walk through the full system design. You are expected to cover:
- Requirements — what the system must do (functional) and how well it must do it (non-functional). Put concrete numbers on scale: catalog size, query volume, acceptable latency, and freshness targets.
- Query-time flow — trace a search request from the moment it leaves the browser to the moment ranked results arrive back, naming every major processing stage.
- Catalog ingestion and indexing — how new listings, price updates, and stock changes flow into the index, and why they may need to be treated differently.
- Retrieval strategy — when to use keyword-based retrieval, when to use embedding-based semantic retrieval, and how to combine them.
- Ranking model — architecture choices, the feature groups you would engineer, the training signal you would use, and one important training pitfall to avoid.
- Serving architecture — caching strategy, how you would scale to holiday traffic spikes, and how the system degrades gracefully when a component is slow or down.
- Evaluation — at least two offline metrics and two online metrics, and what each one actually tells you.
- Trade-offs — pick two meaningful tensions in this design (e.g., freshness vs. cost, recall vs. latency) and explain how you would resolve them.
There is no single correct answer. Interviewers are looking for clear reasoning, concrete numbers, and honest acknowledgment of trade-offs.
Hints
Hint 1
Start by splitting the problem into two clearly separate concerns: getting a manageable candidate set quickly (retrieval, optimizing for recall) and then scoring that set precisely (ranking, optimizing for precision). Many candidates collapse these into one step and get stuck on latency.
Hint 2
Price and stock are written orders of magnitude more often than product descriptions. Ask yourself whether it makes sense to reindex a full document every time a price changes by $0.01, or whether you can decouple fast-changing fields from slow-changing ones.
Hint 3
Your ranking model is trained on historical click and purchase logs, which reflect the order your old ranking showed items — not the true relevance of items. Think about what goes wrong if you train directly on logged positions, and how you would correct for it.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
How to Approach This Problem
A product search system is fundamentally a two-stage pipeline: find candidates cheaply at high recall, then score them expensively at high precision. The whole design flows from that separation. State your assumptions with numbers early — it signals experience and gives the interviewer something concrete to push back on.
1. Requirements and Scale
Functional requirements
- Free-text queries with spell correction and synonym handling (e.g., "earbuds" and "in-ear headphones" should overlap).
- Structured filters applied at retrieval time, not post-hoc, so they don't inflate latency.
- Relevance-based ranking as the default sort; price and recency as alternatives.
- Personalized results for logged-in users.
- Autocomplete and query suggestions.
Non-functional (with numbers)
| Dimension | Target |
|---|---|
| Catalog size | ~200M SKUs |
| Catalog update rate | ~50M changes/day, dominated by price and stock |
| Peak query load | ~60K QPS (holiday spikes 3× average) |
| End-to-end p99 latency | < 200 ms |
| Price/stock freshness | Visible within seconds; surfacing out-of-stock items is a business-critical bug |
| New listing searchability | Within a few minutes |
| Availability | 99.95%; prefer degraded results over timeouts |
2. Query-Time Flow
Browser → API Gateway (auth, rate limit, cache check)
→ Query Understanding Service
→ Retrieval Fan-out (lexical + semantic, parallel)
→ Candidate Merge (~1,000 items)
→ L1 Ranker (~200 items, lightweight GBDT)
→ L2 Ranker (~50 items, full model with personalization)
→ Business Re-ranking (ads, diversity, out-of-stock suppression)
→ Hydration (live price + stock from KV store)
→ Response
Query understanding is worth calling out explicitly. Before touching the index, you normalize the query, correct typos using a noisy-channel model trained on query logs, expand synonyms, extract entities (brand, price intent, category), and encode the query into a dense vector using a two-tower query encoder. This service can be cached aggressively — the same normalized query string produces the same output.
Latency budget (rough): query understanding ~10 ms, retrieval ~50 ms, L1+L2 ranking ~80 ms, hydration and overhead ~60 ms.
3. Ingestion and Indexing
The key insight is that not all fields change at the same rate:
-
Slow fields (title, description, attributes, embeddings): reindex via a streaming enrichment pipeline (Flink or Spark Streaming) that publishes to the inverted index and vector index. Target freshness: minutes. Batch rebuild nightly with a new model version, cutting over with an alias swap for zero downtime.
-
Fast fields (price, stock): writing a full document update for a $0.01 price change wastes enormous I/O. Instead, write price and stock changes directly to a low-latency KV store (Redis or a purpose-built store). At serving time, always re-check this store before returning results. The main index may be slightly stale on price; the KV check ensures you never show an out-of-stock item.
Shard the index by product ID hash across ~100 shards with 3+ replicas each. Add replicas to scale read QPS; add shards to scale catalog size. Place replicas across availability zones.
4. Retrieval Strategy
Use both retrieval modes and merge their outputs:
Lexical (BM25): strongest for exact matches — model numbers, specific brand names, rare tokens. Apply typo tolerance via fuzzy n-gram matching. Expand synonyms on the query side (not the index side) so synonym dictionaries can be updated without a full reindex.
Semantic (two-tower dense retrieval): strongest for vocabulary mismatch — a user who types "ANC earbuds" should find products described as "noise-cancelling in-ear headphones." Train query and product encoders jointly on (query, purchased item) pairs with hard negatives mined from the logs. Store 256-dimensional product embeddings; use HNSW or IVF-PQ for approximate nearest-neighbor search. With product quantization, 200M vectors at 256d fits in ~10–20 GB rather than ~200 GB.
Fusion: reciprocal rank fusion consistently outperforms either source alone on recall@1,000. Merge ~500 candidates from each source, deduplicate, and pass ~1,000 to the ranker.
One practical gotcha: restrictive filters can starve ANN results because most approximate indexes struggle with post-filtering on sparse attributes. Either push filters into the ANN search or over-fetch and filter after.
5. Ranking Model
Architecture: a two-stage ranker.
- L1: a GBDT (~50 features) that cuts ~1,000 candidates to ~200. Optimizes for speed.
- L2: a LambdaMART or small DNN (~500 features) that produces the final top-50, optimizing a listwise NDCG loss. On large-DNN variants, batch the 200 candidates and run on GPU; otherwise CPU is fine.
Feature groups:
| Group | Examples |
|---|---|
| Query–product match | BM25 score, embedding cosine similarity, title token overlap, category match |
| Product quality | Rating, review count, return rate, seller reputation, price vs. category median |
| Behavioral priors | Historical CTR and CVR for this query–product pair (smoothed) |
| User context | Brand affinity, price range history, device, locale |
| Freshness | Listing age, recent sales velocity |
Training signal: graded relevance derived from logs — purchase > add-to-cart > long dwell + no return > click > skip. Supplement with human judgments for tail queries where logged signal is sparse.
Critical pitfall — position bias: clicked items at rank 1 look highly relevant, but that's partly because they were shown at rank 1. Training directly on raw click logs teaches the model to reproduce its own past decisions. Fix this with inverse propensity weighting (divide each sample's weight by the probability it was shown at that position) or by including position as a feature and setting it to a constant at serving time.
6. Serving, Caching, and Reliability
- Result cache: cache non-personalized results keyed on normalized query + filters + locale. Head queries (top ~1% cover ~50% of traffic) benefit enormously. TTL ~60 s; invalidate on major catalog changes.
- Query-understanding cache: deterministic output; cache aggressively with a long TTL.
- Autoscaling: retrieval and ranking services are stateless; scale horizontally behind a load balancer. Pre-scale before anticipated spikes.
- Degradation strategy: if the L2 ranker is slow, return L1 results. If semantic retrieval times out, return lexical-only results. Never return a timeout — a slightly less relevant result is better than no result.
- Circuit breakers on all downstream calls; set timeouts conservatively (don't let one slow shard stall the whole request).
7. Evaluation Metrics
Offline:
- NDCG@10: measures ranking quality weighted by position. The primary offline metric.
- Recall@1,000: checks that the retrieval stage is surfacing relevant candidates at all. A ranker can't fix what retrieval misses.
Online:
- Click-through rate (CTR) and conversion rate (CVR): direct business signals. Track both because CTR can be gamed by clickbait titles that don't convert.
- Query abandonment rate: if a user searches and immediately leaves, the results were probably not useful.
Run A/B tests with proper traffic splits and measure for at least one full week to account for day-of-week patterns. Don't ship a model that improves offline NDCG but hurts online CVR — they don't always agree.
8. Key Trade-offs
Freshness vs. cost: reindexing 50M daily changes as full documents is wasteful. The split fast/slow path above resolves this — slow fields go through the normal pipeline, fast fields bypass it. The cost is a slightly more complex serving path (two lookups instead of one).
Recall vs. latency: wider candidate sets improve ranking quality but cost more time. The two-stage ranker (L1 cut, then L2) lets you spend compute budget where it matters most. ANN with product quantization trades a small recall drop for a 10× memory reduction — usually worth it at catalog scale.
Personalization vs. cacheability: fully personalized results cannot be cached at the query level. A practical middle ground: cache the non-personalized top-200 candidates, then apply a lightweight personalized re-rank on top. Most of the expensive retrieval work is shared; the personalization layer is cheap.