SYSTEM DESIGN · DESIGN PROBLEMS · AI SYSTEMS · MEDIUM · 56 OF 57

Design Semantic Search for an E-commerce Catalog: Embeddings, Hybrid Retrieval, Filters and Ranking

Search 100 million products by meaning and by exact terms: embedding pipeline with streaming updates, sharded HNSW memory math, filters for price, size and stock inside the vector search, hybrid retrieval with reciprocal rank fusion, ranking and personalization in a 200 ms p99 budget, LLM query understanding for the tail only, NDCG and A/B tests, and re-embedding with dual indexes.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
1 / 22

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • 100 GB sharded HNSW
  • filters inside the walk
  • BM25 + vectors fused by rank
  • 150 ms p99
  • dual-index model changes

Notes

Listen

Listen first. A shopper types free text and gets ranked products. Queries come in two kinds: descriptive ones like shoes for a rainy hike, which need matching by meaning, and exact ones like a model number, a brand or a size, which need literal matching. Shoppers apply filters such as price range, size, colour and in stock. Results can be sorted, paginated and personalized, and obvious typos are fixed.

The qualities. End-to-end latency under two hundred milliseconds at p ninety-nine. Price and stock changes must show up within a minute, because filtering on in stock and then showing a sold-out item is a broken promise. New products should be searchable within fifteen minutes. Search must degrade, never fail, during sale peaks. Out of scope: autocomplete, sponsored results, image search and the recommendations carousel.

Functional
  • free-text query → ranked products
  • meaning: "shoes for a rainy hike"
  • exact: model numbers, brands, SKUs, sizes like "10.5"
  • filters: price, size, colour, in stock, ships to my area
  • sort by relevance, price, rating
  • personalized ranking
  • pagination, spelling fixes
Non-functional + scope
  • p99 under 200 ms end to end
  • price and stock fresh in < 1 min
  • new products searchable < 15 min
  • zero-result rate as low as possible: degrade, not fail
  • 99.95% available, sale peaks
  • one region per market
  • out: autocomplete, ads, image search, recommendations

Ask scale

Ask about scale and do the memory math. A hundred million products, embedding the parent product, with sizes and colours as attributes. At seven hundred sixty-eight dimensions in four-byte floats, that is three kilobytes each, three hundred gigabytes. Quantized to one byte per dimension it is seventy-seven. The HNSW graph with sixteen neighbours adds about thirteen, and filter columns five more. So about a hundred gigabytes per copy: ten shards of ten gigabytes, three replicas each.

Now traffic. A hundred million searches a day is twelve hundred a second, five thousand at peak, double that on sale days. Every query fans out to all ten shards, so fifty thousand shard lookups a second at about two milliseconds of CPU each, roughly a hundred busy cores. Embedding the whole catalog is fifteen billion tokens, about four hours on twenty GPUs. Text edits are only twenty-five a second, but price and stock changes run at six hundred.

Index memory math
100M products, embed the parent
  product; sizes are attributes
vector 768 dims × 4 B = 3 KB
  × 100M ≈ 300 GB as float32
int8 quantized: 768 B → 77 GB
HNSW graph, M = 16:
  32 links × 4 B ≈ 130 B → 13 GB
filter columns ≈ 50 B → 5 GB
RAM per copy ≈ 100 GB
10 shards × 10 GB, 3 replicas
floats on SSD for rescoring
Traffic and embedding math
100M searches/day ≈ 1,200/s
  peak ≈ 5,000/s, sales × 2
each query hits all 10 shards
  → 50k shard lookups/s
  × ~2 ms CPU ≈ 100 cores busy
catalog: 150 tokens × 100M
  = 15B tokens to embed
  1 GPU ≈ 50k tokens/s
  20 GPUs ≈ 4 hours, ~$200
text edits ~2M/day → 25/s
price + stock ~50M/day → 600/s

Define API

Define the API. One search call takes the query text, structured filters such as maximum price, size and in stock, a sort order and a cursor. It returns results, facet counts for the filter sidebar, any spelling fix or rewrite we applied, and a query id. The client reports clicks, add to carts and purchases against that query id, which feeds ranking and evaluation. Indexing has no public API: it follows change events from the catalog database.

API
GET /v1/search
  ?q=shoes for a rainy hike
  &filters=price<=120,size:10,
    in_stock:true
  &sort=relevance&cursor=…
→ { results[], facets,
    rewrite?, query_id }
POST /v1/search/events
  { query_id, product_id,
    type: click | cart | buy }
catalog changes → Kafka (CDC)

Data model

The data model. The catalog in Postgres is the source of truth: title, brand, category path, attributes, description and variants with their sizes. Each index shard holds one document per product: the quantized vector, the model version that made it, a hash of the text it was made from, the keyword fields, and compact filter columns for price, sizes, category and an in-stock bitmap. Search events record the query, product, position and action.

Data model
catalog (Postgres, source of truth)
  product_id, title, brand,
  category_path, attributes{},
  description, variants[]
index doc per product (per shard)
  vector int8[768], model_ver,
  text_hash, BM25 fields
  filter cols: price, sizes,
    in_stock bitmap, category
search_events: query_id, user,
  product_id, position, type

High-level design

Draw the write path first. Change data capture streams every catalog change onto Kafka. Indexing workers build the text to embed: title, brand, category path and key attributes, plus the start of the description. They embed it on a GPU pool and upsert the vector into the right shard of the vector index, and the same document into the keyword index. A nightly batch job can rebuild everything from a catalog snapshot.

Now the read path. The search service checks the query cache, then normalizes the query and pulls any known rewrite from query understanding. It embeds the query and, in parallel, runs keyword search and filtered vector search across all shards. It fuses the two lists into about three hundred candidates, and the ranker scores them with product and shopper features to produce the page. The page is hydrated with live price and stock before it goes back.

Deep dive: vector index

Deep dive one: the vector index. HNSW is a layered graph of nearest neighbours: a query greedily walks from a coarse top layer down to the dense bottom one. The search width, often called ef, is the knob between recall and latency. Keep int8 vectors in RAM, then rescore the top two hundred with the full floats from SSD to win back the recall quantization loses. Shard by a hash of the product id for even sizes. Every query fans out to all shards, so hedge slow ones.

Filters are where naive vector search breaks. Search first and filter afterwards, and if most of the top two hundred are out of stock or the wrong size, the shopper sees nine results. Instead, apply the filter inside the graph walk: every node can be traversed, but only matching ones enter the results. When the filter is very narrow, under one percent of the shard, the graph walk wanders, so the planner reads the bitmap count and simply scans the matching products exactly, which takes a couple of milliseconds.

HNSW at 100M
  • graph of near neighbours, greedy walk from the top
  • ef_search ~100-200: recall vs latency knob
  • int8 in RAM, then rescore top 200 with floats from SSD
  • shard by hash(product_id): even size, every query fans out to all 10
  • tail: hedge slow shards
  • 3 replicas: QPS + failover
Filters without losing recall
  • post-filter: top 200, then drop sold out → 9 results left
  • in-walk: traverse every node, only matches enter results
  • planner uses bitmap counts: > 5% match → filtered HNSW < 1% match → exact scan of the matching ids (20k × 768 int8 ≈ 2 ms) between: widen ef
  • facets from keyword index

Deep dive: freshness

Freshness needs two lanes. Price and stock change constantly but do not change what a product means, so they skip embedding and patch the filter columns in place within seconds. Text edits are rarer: hash the embedding text and skip unchanged products, otherwise re-embed and replace the vector. HNSW handles deletes poorly, so updates become tombstones plus inserts into a small fresh segment, merged into the big one in the background. The final page still reads live stock.

Two lanes of updates
  • attribute lane (600/s): price, stock → patch filter columns in place, seconds
  • text lane (25/s): hash text; unchanged → skip changed → embed, delete + insert in a fresh segment
  • tombstones pile up → merge segments, rebuild nightly
  • page hydrate reads live stock

Deep dive: hybrid

Deep dive two: hybrid retrieval and ranking. Keyword search with BM25 nails exact terms like model numbers and sizes, which embeddings blur. Vector search finds waterproof trail boots for a rainy hike. Their scores are on different scales, so do not add them. Use reciprocal rank fusion: each product earns one over sixty plus its rank in each list, summed. Weight it by query type, so a query that looks like a model number leans on keywords.

Reciprocal rank fusion
BM25: exact terms, SKUs, sizes
  "XR-500 charger" → that item
vector: "rainy hike" →
  waterproof trail boots
scores not comparable:
  BM25 0-40, cosine 0-1
RRF(d) = Σ 1 / (60 + rank_i(d))
  boots: #3 vector, #40 BM25
  → 1/63 + 1/100 ≈ 0.026
weight by query type:
  model number → favour BM25

Deep dive: ranking

Fusion only picks candidates. A learning-to-rank model, usually boosted trees, scores the three hundred with about a hundred features: the retrieval scores, click and conversion rates for this query, ratings and return rate. For tail queries a small cross-encoder rereads the top fifty against the text. Personalization adds features such as the shopper's usual size, favourite brands, price band and a vector of this session's views. Cap that boost so relevance still wins.

Rerank + personalize
  • stage 1: boosted trees, 300 candidates × ~100 features ~15 ms on CPU
  • stage 2: small cross-encoder on top 50 for tail queries
  • features: BM25, cosine, RRF, CTR, conversion, rating, margin, return rate
  • personal: size, brand, price band, session vector
  • cap the boost; keep diversity

Deep dive: latency

The latency budget. Ten milliseconds at the edge, five for the cache and rewrite lookups, fifteen to embed the query on a micro-batched GPU. Keyword and vector search run in parallel across shards, about fifty with hedging and float rescoring. Fusion is two, features fifteen, ranking thirty-five, and hydrating live price and stock fifteen. About a hundred fifty in total, leaving fifty of slack. If a request is running late, skip the cross-encoder rather than miss the deadline.

Search traffic is heavily skewed: the top hundred thousand queries are about half of all searches. Cache the fused candidate list, not the final page, keyed by the normalized query, the filters and the model version. On a hit, skip embedding and retrieval, but still re-check stock and run the ranker with this shopper's features, so caching never kills personalization. Use a short TTL of minutes, and cache query embeddings separately as well.

p99 latency budget
edge, auth, parse          10 ms
cache + rewrite lookup      5 ms
query embed (batched)      15 ms
BM25 ∥ ANN, 10 shards,
  hedged, + float rescore  50 ms
fuse 2 lists               2 ms
feature fetch (batched)    15 ms
trees 300 + encoder 50     35 ms
hydrate live price, stock  15 ms
total ≈ 150 ms; slack 50 ms
over budget → skip stage 2
Caching popular queries
  • top 100k queries ≈ 50% traffic
  • key: normalized query + filters + model version
  • value: fused candidates, not the final page
  • per request: re-check stock, run ranker with my features
  • TTL ~10 min; purge on big catalog or model changes
  • also cache query embeddings

Deep dive: LLM queries

Deep dive three: query understanding. Rules and a small classifier handle most queries in a millisecond. Hard ones, long and vague like a gift for a ten year old who likes space, or ones that returned nothing, benefit from a language model. Calling one inline costs hundreds of milliseconds, so parse yesterday's tail queries offline each night into category, attributes, price and a rewrite, stored for a two millisecond lookup. Unseen hard queries get a small model with a strict deadline.

LLM for hard queries only
  • hard: long, vague, zero results or a reformulation (~5%)
  • offline: each night, LLM parses yesterday's tail queries → category, attrs, price, rewrite stored in a KV, 2 ms lookup
  • online, unseen + hard: small model, 120 ms deadline, else normal results; cache parse
  • validate attrs vs the catalog schema; drop unknown values

Deep dive: evaluation

Deep dive four: evaluation. Offline, keep about ten thousand queries across head, torso and tail, with products graded zero to three by raters, and an LLM judge to scale labelling, checked against humans. Measure recall at three hundred for retrieval and NDCG at ten for the final page. Online, watch click-through, add to cart, revenue per search, zero-result rate and reformulations. Ship ranking changes through user-level A/B tests, using interleaving to screen ideas quickly.

Measuring relevance
  • offline: 10k judged queries, head, torso and tail graded 0-3 by raters + an LLM judge checked vs humans
  • NDCG@10 for the ranked page
  • recall@300 for retrieval alone
  • online: CTR, add to cart, revenue per search, zero results, reformulations
  • A/B per user, 1-2 weeks; interleaving to screen fast

Deep dive: new model

Changing the embedding model is a migration. Vectors from two models live in different spaces, so the query encoder and the index must always match. Snapshot the catalog, note the Kafka offset, and backfill all hundred million products into a new index, about four hours of GPUs plus the graph build. Meanwhile, every edit is embedded twice. Gate the cutover on offline recall and NDCG, shadow traffic for latency, then an A/B test. Flip the alias, keep the old index a week for rollback.

Re-embedding: dual indexes
  • v3 and v4 vectors don't mix: query and index must match
  • snapshot catalog, note Kafka offset, backfill 100M into v4 (~4 h on 20 GPUs + build)
  • dual-write: edits embed twice until cutover
  • gate: recall, NDCG offline, shadow latency, then A/B
  • flip alias; keep v3 a week
  • cost: 2x RAM during switch

Trade-offs

Review the trade-offs. Int8 quantization saves four times the memory for about a point of recall, which rescoring wins back. HNSW in RAM is fast but expensive; at a billion products, move to a disk-based index. Hash sharding keeps shards even but makes every query fan out, so hedge the tail. For failures, keyword search is the safety net: if vectors or the encoder fail, serve BM25 results. Monitor p99 per stage, index lag, zero-result rate and recall against an exact brute-force sample.

Trade-offs and failures
  • int8: 4x less RAM, ~1% recall lost, won back by rescoring
  • HNSW in RAM vs disk-based ANN: at 1B products, go to disk
  • hash shards: even, but fan-out to all → hedge the tail
  • vector index down → BM25 only encoder down → cached vectors + keywords
  • ranker down → RRF order
  • watch: p99 per stage, recall

Interview summary

The thirty-second summary. A hundred million products and five thousand searches a second. Quantized vectors plus the HNSW graph are about a hundred gigabytes, in ten shards with three replicas. Text edits re-embed; price and stock patch filter columns. Filters run inside the graph walk, with an exact scan when they are narrow. Fuse keyword and vector lists by rank, rank with boosted trees, cache head queries, use an LLM offline for the tail, and switch models with dual indexes.

Interview summary
  • 100M products, 5k searches/s
  • 768-d int8 + HNSW ≈ 100 GB, 10 shards × 3 replicas
  • two lanes: re-embed on text, patch price + stock in place
  • filters inside the walk, exact scan when very narrow
  • BM25 + vector → RRF → trees
  • p99 ≈ 150 ms, cache head
  • LLM offline for tail queries
  • NDCG, A/B, dual-index switch

Interview questions

Q1Why not use only vector search?

Embeddings capture meaning but blur exact tokens such as model numbers, SKUs, sizes and rare brand names, so a query for a specific part can return similar but wrong items. BM25 matches those exactly; running both and fusing with reciprocal rank fusion gives better recall than either alone.

Q2How much memory does the vector index need for 100 million products?

At 768 dimensions, float32 is about 3 KB per product or 300 GB. Int8 quantization brings that to about 77 GB, the HNSW graph with M of 16 adds about 13 GB and filter columns a few more, so roughly 100 GB per copy, split into about 10 shards and replicated three times. Full floats stay on SSD for rescoring.

Q3How do you apply filters like size and in stock in a vector search?

Not by post-filtering, which can leave a handful of results. Apply the filter inside the HNSW traversal so only matching products enter the result set. When the filter matches a tiny fraction of the shard, a planner switches to an exact scan of just the matching ids, which is cheap for tens of thousands of vectors.

Q4Do you re-embed a product when its price or stock changes?

No. Price and stock do not change what the product means, so they update filter columns in place within seconds. Only changes to the embedding text, detected by hashing it, trigger a new embedding. The result page also reads live stock at hydration time.

Q5Why reciprocal rank fusion instead of adding the scores?

BM25 scores are unbounded and depend on the query, while cosine similarity sits between minus one and one, so a weighted sum is fragile. RRF uses only ranks, summing one over a constant such as 60 plus each rank, which is robust and needs no calibration. It can be weighted by query type.

Q6Where would you use an LLM, and why not on every query?

For hard queries only: long, vague or zero-result queries, about 5 percent of traffic. An inline LLM call costs hundreds of milliseconds and real money at 5,000 queries a second, so parse tail queries offline into structured attributes and rewrites, look them up in milliseconds, and use a small model with a strict deadline for unseen hard queries. Validate its output against the catalog schema.

Q7How do you stay under 200 ms at p99?

Run keyword and vector retrieval in parallel, hedge slow shards, micro-batch query embedding on GPUs, use cheap boosted-tree ranking on a few hundred candidates and a cross-encoder only on the top 50 when time allows, and cache fused candidates for head queries while still personalizing per request.

Q8How do you evaluate search quality?

Offline with a judged query set graded by humans and a calibrated LLM judge, measuring recall at the candidate depth for retrieval and NDCG at 10 for ranking. Online with click-through, add to cart, revenue per search, zero-result and reformulation rates, and ship changes through A/B tests, using interleaving for faster screening.

Q9How do you switch to a new embedding model without downtime?

Build a second index: snapshot the catalog, record the stream offset, backfill all products with the new model, and dual-write every edit to both indexes. Validate offline, shadow live traffic, run an A/B test, then flip an alias so the query encoder and index switch together. Keep the old index briefly for rollback; this needs about twice the memory during the switch.

Q10How do you personalize without breaking caching or relevance?

Keep retrieval mostly non-personalized so candidate lists are cacheable, and personalize in the ranking stage with features such as preferred size, brand affinity, price band and a session vector. Cap the personalization weight and keep some diversity so relevance still dominates.