Building a Filterable Catalog Search with Live Facet Counts
System DesignModel answerLast updated
Design a billion-item catalog search service with relevance ranking, filters, accurate facet counts, stable pagination, and second-level freshness for fast-changing price and stock data.
Problem
You are designing the search backend for a very large online marketplace. Shoppers type free-text queries such as "wireless noise cancelling headphones" and then refine the results with facets: brand, category tree, price range and minimum customer rating. Besides the ranked list of products, each response must include facet counts showing how many matching products fall into each bucket.
Requirements
Functional
- Relevance-ranked text search across titles, descriptions and keywords.
- Filtering by category, brand, rating and price range, with facet aggregations returned alongside the hits.
- Stable pagination: no item duplicated or skipped across page boundaries while the user browses.
- Price changes and out-of-stock events must show up in results within a few seconds.
Non-functional
- 1 billion active products.
- 50,000 queries per second at peak.
- p99 latency below 150 ms, including facet computation.
- 99.99% availability on the read path.
- 5,000 catalog attribute updates per second, plus up to 50,000 price/stock updates per second.
What to cover
- Overall architecture and API: endpoints, request parameters (query, filters, facets, cursor) and response shape.
- Index layout and storage: inverted index for text, columnar per-document values for filtering and counting, and the sharding approach (document-based vs. term-based).
- The life of a query: coordinator, leaf shards, posting-list intersection, scoring, facet counting and scatter-gather merging.
- Keeping volatile fields fresh: compare naive re-indexing with hybrid designs such as in-memory side stores, delta segments or two-phase hydration.
- Pagination: offset-based vs. keyset/cursor-based paging at this scale, and the trade-offs.
Use back-of-the-envelope numbers to justify your choices.
Hints
Hint 1
Separate the data by rate of change: titles and attributes change slowly and can go through immutable index segments, while price and stock change constantly and should not force a document rewrite.
Hint 2
Partition documents (not terms) across shards so each shard can match, score and count facets on its own; then think about what the coordinator must merge, and which facet dimensions can be merged exactly versus only approximately.
Hint 3
For pagination, ask what happens to deep offsets in a scatter-gather system (each shard must return offset+limit items) and what a cursor needs to encode (a consistent view plus the last sort key with a unique tiebreaker).
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Sizing
- Corpus: 1B products at ~2 KB of indexable data is ~2 TB raw; with postings, positions and column data, ~4-6 TB per full replica.
- Shards: ~15M docs per shard gives ~64-70 document-partitioned shards.
- Fan-out: 50k QPS x ~64 shards is ~3.2M shard-requests/s. At ~1.5k shard-req/s per node that is on the order of 2,000 query nodes across replicas. Result caching and category-based routing reduce this considerably.
- Writes: 5k/s catalog updates are heavy but modest; 50k/s price/stock updates are tiny but relentless. Treating these as two separate paths is the key design decision.
- Latency budget (150 ms p99): network + coordinator ~10 ms, leaf execution ~80 ms, merge ~10 ms, hydration ~20 ms, remainder as slack.
- Availability: at least 3 replicas per shard across zones, no single-shard dependency, and partial results rather than errors when a shard is slow.
2. API
POST /v1/search
{
"q": "wireless noise cancelling headphones",
"filters": {"brand": ["Sony","Bose"], "category": "electronics/audio",
"price": {"gte": 50, "lt": 300}, "rating_gte": 4, "in_stock": true},
"facets": ["brand","category","price_ranges","rating"],
"sort": "relevance",
"page_size": 48,
"cursor": "<opaque token>"
}
The response carries results (id, title, price, price_version, in_stock, score), facets (value/count lists per dimension), total_hits (value plus eq/gte), next_cursor and a partial flag.
3. Index structure and sharding
Each shard contains:
- Inverted index: term to sorted local docIDs, frequencies and positions, compressed with delta/PFOR and equipped with skip lists. Fields (title, description, keywords) get separate boosts; BM25 is the base score.
- Columnar doc values: arrays indexed by docID such as
brand_ord[],category_ord[],rating[]. Counting a facet is a tight loop (counts[brand_ord[doc]]++) that is cache-friendly. Numeric range filters use BKD trees or the columns directly. - Volatile sidecar: price and stock held outside immutable segments (section 5).
Document-based partitioning (hash of product_id) is the right choice. Term-based partitioning forces posting lists to cross the network for multi-term intersections and makes counting facets over the full match set impractical. With document partitioning a shard is self-sufficient; the cost is that every query touches every shard.
Mitigation: add a tier partitioned by top-level category. When a query classifier is confident, the coordinator queries only the relevant tier, cutting fan-out by roughly 5-10x.
Catalog changes flow Kafka -> indexer -> new immutable segments -> segment replication to replicas, with a 1-5 s refresh. Background merges compact segments.
4. Query lifecycle
Coordinator (stateless): normalize and tokenize, apply synonyms and spelling correction, classify to a category tier, check a short-TTL cache keyed on normalized query plus filters, then scatter to one replica per shard chosen by least outstanding requests. Use hedged requests: if a replica exceeds its p95, send a duplicate to another replica to cut tail latency.
Leaf shard:
- Match: conjunctive intersection starting from the rarest term, leapfrogging others with skip lists.
- Filter: apply cheap cached filters first (category/brand as roaring bitmaps), then rating, price and stock via doc values and the sidecar.
- Score: BM25 plus static priors (sales rank, rating) in a top-k heap, using WAND/block-max WAND to skip documents that cannot enter the heap. Keep ~200 candidates for a second-stage re-ranker.
- Facets: count over all matches, not just the top-k, via one pass incrementing ordinal arrays. Dynamic price buckets come from per-shard min/max/percentile sketches.
- Return top-k plus facet maps.
Gather: k-way heap merge of top-k lists. Low-cardinality facets (rating, price buckets, top categories) sum exactly. High-cardinality facets (brand) have each shard return its top 1.5k + 10 values, so sums are approximate; either report an error bound or run a second phase asking shards for exact counts of the final top-N values. If a shard misses its deadline, return partial: true rather than failing.
5. Volatile price and stock
Naive re-indexing: engines in the Lucene family cannot update in place; a price change deletes a document and writes a new one with all postings. At 50k/s times 3 replicas this causes segment churn, merge storms and cache invalidation, with write amplification of 100x or more, and freshness still bounded by refresh.
Hybrid design:
- In-memory sidecar per shard: dense arrays by local docID (
price_cents[], in-stock bitset,version[]) plus a product_id-to-docID map remapped after merges. A consumer reads a Kafka topic partitioned like the shards and applies updates with "highest version wins", which tolerates out-of-order delivery. Filters and facets read the sidecar during traversal, so price-range and in-stock behavior is fresh within ~1-2 s. Memory is small: ~15M docs x ~12 B is ~180 MB per shard. Snapshot periodically for fast recovery. - Two-phase hydration: the index returns IDs; the coordinator batch-fetches display price and stock from the same authoritative price store used by the product detail page, so the listing never disagrees with the page the user clicks into. Only the final page (~48 items) is hydrated, keeping this inside the ~20 ms budget.
- Facet counts based on the sidecar may differ slightly from hydrated values for a second or two; that is an accepted trade-off, and the hydrated price is what the user sees.
6. Pagination
Offset/limit: simple and allows jumping to a page, but each shard must return offset + limit items, so cost and memory grow with depth; results also shift if data changes between requests, causing duplicates or gaps.
Keyset/cursor: the cursor encodes a snapshot or version marker plus the last sort key, with product_id as a unique tiebreaker. Each shard resumes with "after this key", so cost stays constant regardless of depth. Drawbacks: no random page jumps, and the cursor must be opaque and possibly signed. Because scores change when price/stock change, sort on a value frozen into the cursor's snapshot (or cap depth, e.g. 10k results) to keep ordering stable. Recommend cursors for browsing and a hard cap on offset depth.
7. Common mistakes
- Putting price and stock into the regular re-index path.
- Counting facets only over the top-k hits.
- Choosing term-based sharding for a faceted workload.
- Summing high-cardinality facet counts and presenting them as exact.
- Paginating by offset without a tiebreaker or consistent view.
- Failing the whole request when one shard is slow instead of returning partial results.