Design: semantic product search
Hybrid retrieval (BM25 + embeddings) fetches ~1,000 candidates, a learning-to-rank model reorders them with business signals, and LLM query understanding is precomputed for head queries — all within 200 ms p99.
Fundamentals you'll use
How it works
- Scale: ~50M products, ~3.5k QPS at holiday peak, p99 under 200 ms, price and stock fresh within seconds.
- Price and stock never enter the embedding: a stream writes them to an in-memory store for filters.
- Apply filters inside the ANN search; post-filtering 1,000 candidates down to in-stock items leaves near-empty pages.
- The worst failure is a silent relevance regression: track nDCG@10 offline, sliced by head, torso and tail.
- Shortlist rankers with team-draft interleaving, then confirm the winner with an A/B test on revenue per search.
Check yourself
Answer to mark it learned; your answers aren't scored.
Product search: a shopper asks for running shoes, size 7, in stock, under $50. Your system takes the ANN top 1,000, then applies the filters, and the page shows 2 items although the catalog has hundreds that match. Best fix?
Go deeper
Full explanation
Requirements
Functional: free-text search over ~50M products in several languages; filters and facets (category, brand, price, size, in stock); typo tolerance, synonyms and sort options.
Non-functional: p99 < 200 ms at a holiday peak of ~3.5k QPS; price and stock fresh within seconds; 99.95% availability; every ranking change proven on revenue before full rollout.
What I'd ask first:
- What do we optimize — relevance, conversion, revenue or margin — and who owns that trade-off?
- Peak QPS, and how much traffic do the top queries cover?
- How many price/stock updates per second, and how stale may they be?
- Which languages and markets: one catalog or one per country?
- Sponsored results or legal constraints on ranking?
Highest-cost failure: a silent relevance regression on head queries during peak season. Latency dashboards stay green while revenue per search drops.
High-level design
Offline. A catalog pipeline normalizes products, has an LLM fill missing attributes, embeds title + attributes with a multilingual model (Choosing an embedding model), and builds two indexes per shard: an inverted one (Lexical search & BM25) and an ANN one (ANN indexes: HNSW, IVF, PQ). A batch LLM job parses the top ~1M queries into structured intents (category, brand, attributes, spelling fix) cached in a key-value store. Ranking models retrain nightly on click and purchase logs. Price and stock bypass all of this: a stream updates an in-memory attribute store within seconds.
Online. The query hits the parse cache (head) or a small distilled parser (tail), gets embedded, and fans out to every shard. Each shard runs BM25 and filtered ANN in parallel; results fuse (Hybrid search & RRF) into ~1,000 candidates. A gradient-boosted ranker reorders them on relevance, behavior and business features (stock, margin, CTR) from the feature store (Feature stores), and facets are counted on the filtered match set.
Real example
A shopper in Mexico types "tenis para correr mujer impermeables". It is a tail query, so the distilled parser (~15 ms) maps it to category=running_shoes, gender=women, attr=waterproof, lang=es, and a multilingual encoder embeds it (~8 ms). The query fans out to 32 shards; each runs BM25 with the Spanish analyzer and ANN filtered by in_stock_mx=true, fuses both lists with RRF and returns its top 32: ~1,000 candidates in ~45 ms. Features for the 1,000 arrive in ~10 ms, and a LightGBM ranker scores them on ~150 features in ~25 ms on CPU. Facets and assembly take ~10 ms: 48 results in ~115 ms, comfortably under the 200 ms p99.
Trade-offs +4 · −4
+ You gain
- Hybrid retrieval catches both exact tokens (SKUs, brands) and intent; neither alone does.
- LLM-quality parses for head queries at cache-lookup latency and near-zero marginal cost.
- Volatile fields (price, stock) stay out of the embeddings, so they are fresh in seconds without re-embedding.
- Business goals are explicit, reviewable ranking features instead of hidden boosts.
− You pay
- Two indexes (inverted + ANN) plus a fusion step to operate and keep consistent.
- Tail queries get a weaker parser than head queries, and head parses can be a day stale.
- Click-trained ranking inherits position and popularity bias; new products start cold.
- Full fan-out makes p99 hostage to the slowest shard.
Use it when
Large catalogs (millions of items) with a vocabulary gap between how users search and how products are described, a strict latency budget and revenue metrics to optimize.
Avoid it when
Small catalogs (< ~100k items) or exact-lookup search (part numbers, SKUs): tuned BM25 with synonyms and filters is cheaper and often as good.
Numbers to know 5
- Traffic: 30M searches/day ÷ 86,400 ≈ 350 QPS average; ×10 on a holiday evening ≈ 3.5k QPS, and every query hits every shard.
- Vectors: 50M × 768 dims × 4 B ≈ 154 GB in float32; int8 ≈ 38 GB + ~6 GB of HNSW links (M=16) per replica.
- p99 budget 200 ms: parse 15 + embed 10 + retrieval 60 + features 15 + ranking 30 + facets 20 + network/headroom 50.
- Query parses: 1M head queries × (300 in + 100 out) at an assumed $0.15/$0.60 per 1M ≈ $105 per full refresh, ~$50 via batch API; online for 30M searches/day = 30× the tokens + 300 ms.
- Re-embed: 50M products × ~100 tokens = 5B tokens ≈ $100 at $0.02/1M, or ~1 h on 16 GPUs at ~1k products/s each.
Common pitfalls 4
- Putting price and stock in the embedding pipeline: freshness drops to hours and sold-out items top the results. Stream volatile fields into filters and features.
- Post-filtering ANN results: "size 7, in stock, under $50" applied after the top 1,000 leaves 2 items. Filter inside the ANN search or widen k adaptively.
- Training on raw clicks: the ranker learns position bias and a popularity loop. Use randomized top slots or inverse propensity weighting, plus exploration for new items.
- Judging only head queries in one language: tail and Spanish queries regress silently. Stratify judgment sets and dashboards by segment and language.
Interview questions 3
Answer out loud first, then reveal.
Why not call an LLM on every query?Show answer
Latency first, cost second. Even a small model adds ~200–500 ms to a 200 ms p99 budget, and at up to 3.5k QPS it is a real GPU bill. Search traffic is Zipf-shaped, so I precompute LLM parses offline for the top ~1M queries and serve them from a key-value store in ~2 ms; the tail gets a small parser distilled from those LLM outputs. The trade-off: tail parses are weaker and head parses can be a day stale, so I refresh daily and watch zero-result rate per segment.
Marketing wants to boost high-margin products. How do you do it without wrecking relevance?Show answer
I make it an explicit, measured trade-off instead of a hidden boost. Margin becomes a weighted term in the ranker, and I plot offline nDCG against expected margin per search for several weights: a Pareto curve. Product picks a point, say −0.5% nDCG for +3% margin, and we confirm it in an A/B on revenue and conversion with return rate as a guardrail. I cap the boost so it only reorders among relevant items; it can never pull an irrelevant product onto page one, because that costs trust a two-week test doesn't measure.
How do you keep price and stock fresh across 50M products?Show answer
I split fields by volatility. Text and embeddings change rarely, so they go through incremental re-indexing, with blue/green swaps when the model changes. Price and stock change constantly, so they never touch the embedding: a Kafka stream updates an in-memory attribute store within seconds, applied as filters and ranking features at query time. The failure mode is a lagging consumer, so I alert on stream lag and, at render time, re-check stock for the 48 results actually shown: a cheap batched point lookup that catches whatever the stream missed.
Deep dive 5
Indexing & freshness
Two update speeds. Text and attributes change rarely: a pipeline re-embeds only products whose text changed and appends them to ANN segments; a full re-embed of 50M (~1 h on 16 GPUs) runs only when the embedding model changes, built side by side and swapped blue/green (Index freshness & lifecycle). Price and stock change constantly, so they are never in the embedding: a Kafka stream writes them into doc values or an in-memory attribute store within seconds, used as filters and ranking features. Shard by product id (e.g. 32 shards × 3 replicas). Every query hits every shard, so p99 is the slowest shard's p99: send a hedged request to a second replica when the first passes its p95.
Hybrid retrieval & query understanding
BM25 wins on exact tokens: brands, model numbers (WH-1000XM5), sizes. Embeddings win on intent and vocabulary gaps (couch vs sofa, regalo para papá). Run both and fuse with RRF or learned weights. An LLM per request is too slow for the budget, so run it offline over the top ~1M queries (search traffic is Zipf-shaped, so a small head covers much of it; measure your own curve) and cache structured parses: category, brand, attributes, spelling fix, synonyms. Tail queries get a small parser distilled from those LLM outputs (Knowledge distillation), ~10–20 ms. Apply filters (category, price, in stock) inside the ANN search; post-filtering the top 1,000 down to in-stock size-7 items returns near-empty pages.
Ranking with business signals
Stage two is a LambdaMART-style gradient-boosted ranker (LightGBM, XGBoost) over ~1,000 candidates and ~150 features: text relevance (BM25, cosine, field matches), quality (rating, return rate), behavior (CTR and conversion for this query–product pair, smoothed when counts are low) and business (stock depth, margin, delivery time). Train on clicks and purchases with position-bias correction: top slots get clicked because they are on top. Business goals enter as explicit, reviewed terms, such as a margin boost capped so offline nDCG@10 drops < 1%, never as hidden hacks. If the budget allows, a distilled cross-encoder (Reranking (cross-encoders)) re-scores the top 50 on GPU in ~20 ms. New products get an exploration slot so they can earn behavior data.
Evaluation & experiments
Offline: nDCG@10 on human-judged query sets stratified by head, torso and tail and by language (Golden datasets & test sets), plus zero-result rate and empty-after-filter rate as guardrails. Online, an A/B test (A/B testing LLM features) on revenue per search has the final word, but detecting a ~1% lift takes weeks of traffic. Team-draft interleaving is the fast filter: merge rankers A and B into one list by alternating picks, and credit each click to the ranker that supplied the item. Every user sees both, so it detects a ranking preference with an order of magnitude or more fewer users. Use interleaving to cut ten candidates down to one or two, then confirm them with a real A/B on revenue and conversion, guarded by return rate.
Latency, scale & cost
The 200 ms p99 is a budget, not a hope: parse 15 ms (2 ms on a cache hit) + embed 10 + fan-out retrieval 60 + features 15 + ranking 30 + facets 20 + network and headroom 50. Retrieval dominates and is hostage to the slowest of 32 shards, so keep vectors in RAM: 50M × 768 dims in int8 (Quantization (INT8, INT4, FP8)) is ~38 GB plus ~6 GB of HNSW links per replica. Head-query embeddings and parses come from cache, so the GPU only embeds the tail. Cache full result pages for the top queries for ~60 s, invalidated by stock events; that absorbs much of a holiday spike. The LLM bill stays small because it runs offline: ~$50–100 per full refresh of 1M parses.