"Design a search engine" is the largest of the classic questions, and the one most often answered with a single noun: "Elasticsearch". That is the right tool for searching your own product's data. A web search engine indexes a billion pages and answers in a fifth of a second, which turns the problems around.
The search systems lesson explains inverted indexes, text analysis and relevance scoring, and the web crawler question covers how the pages arrive. This page is the serving side: how an index too large for one machine is split, how a query touches every piece and still returns in 200 ms, how ranking is staged so the expensive part sees only a few hundred candidates, and how a page crawled ten minutes ago becomes findable.
The interviewer is mostly testing one idea: fan-out. Every query reaches hundreds of machines, so tail latency, partial failure and cost all multiply. Candidates who see that early do well.
Clarify the requirements
Functional requirements:
- Given a text query, return a ranked first page of 10 results with titles, URLs and snippets.
- Support further pages of results and basic filters (language, site).
- Reflect new and changed pages: news within minutes, the rest within days.
- Return results for the same query consistently enough that a user can click back and see the same page.
Out of scope, said aloud: the crawler and content extraction (previous question), ads, personalization, image and video search, spelling correction beyond a mention.
Non-functional requirements:
- Fast: results in under 200 ms at the 95th percentile, including the time to build snippets.
- Highly available: the engine answers even when machines fail, possibly with slightly reduced coverage.
- Relevant: quality is the product. Ranking must combine text match with authority and freshness.
- Scalable: the index grows with the web, and query volume has sharp daily peaks.
- Fresh: new pages become searchable on a schedule that depends on their importance.
Estimate the scale
Assume an index of 1 billion pages, 5,000 queries per second on average and a 3× peak, and about 300 distinct terms per page.
Query rate: 5,000 per second average, 15,000 per second at peak. That is 432 million queries a day, 100 million users at about 4.3 queries each.
Index size: 1B pages × 300 terms = 3 × 10¹¹ postings, at about 2 bytes each compressed (delta-encoded document ids and term frequency) = 600 GB of postings. Positions for phrase matching, document metadata and per-document signals roughly triple it: about 1.8 TB for one full copy, around 1,800 bytes per page.
Shards: with 5 million pages per shard, 1B ÷ 5M = 200 shards, each about 9 GB, small enough to sit in memory on one machine.
Shard-queries: because every query goes to every shard, 15,000 queries × 200 shards = 3 million shard-queries per second at peak.
CPU: at about 2 ms of CPU per shard-query, that is 3,000,000 × 0.002 = 6,000 cores busy. At a 50% peak utilization target, 12,000 cores, or about 375 servers of 32 cores. Using 3 replicas of each shard for availability across zones gives about 600 servers, each around 31% busy at peak.
The tail: if each shard answers within 20 ms 99% of the time, the chance that at least one of 200 shards is slower is 1 − 0.99²⁰⁰ ≈ 87%.
"The index is only 1.8 TB. It is the fan-out that costs: every query becomes 200 sub-queries, 3 million per second at peak. And the same fan-out means a query is as slow as its slowest shard, so a per-shard 99th percentile becomes the typical query's latency. Latency engineering, not storage, is the hard part."
The capacity estimator reproduces the 5,000 queries per second (ignore its storage line, which here counts one year of changed pages).
API and data model
GET /search?q=distributed+consensus&page=1&lang=en -> { results: [{ title, url, snippet }], total }index shard term -> postings list [ (docId, tf, positions[]) ... ], sorted by docId
doc table docId -> { url, title, length, static_score (link authority), crawl_time }
snippet store docId -> compressed page text (read only for the final ten)A postings list is sorted by document id so that a multi-term query can intersect lists with a linear merge. Static signals such as link authority are computed offline and stored per document, so the query-time scoring does not compute them.
High-level design
The slice to simulate is the serving path: a query frontend checks a result cache and then fans out to a sharded, replicated index.
- The query frontend parses the query and checks a cache of recent results.
- On a miss, it sends the query to every index shard and gathers each shard's best candidates.
- Shards are replicated, so a slow or failed replica can be bypassed.
Describe this diagram
Components
- searchers (Client)
- query frontend (Service)
- result cache (Redis)
- index shards (Search cluster (Elasticsearch))
Connections
- searchers sends to query frontend
- query frontend sends to result cache
- query frontend sends to index shards
Run it, then try removing replicas or shrinking the cache's TTL, and watch latency and errors. Fan-out makes the slowest shard the one that sets the pace.
The query path: the frontend normalizes and parses the query, looks it up in the result cache (head queries repeat heavily), and on a miss sends it to one replica of each shard. Each shard intersects the postings of the query terms, scores its matches and returns its top 20. The frontend merges 200 lists into 4,000 candidates, re-ranks the best few hundred with a richer model, and builds snippets for the final ten.
The index path: a pipeline reads crawled pages, extracts text, builds inverted index segments for each shard, computes link-based scores offline and publishes a new index version to the serving fleet.
The interesting problem: splitting the index
An index of 1.8 TB must be spread across machines. The choice of what to split by determines everything about query cost.
Approach A: partition by term
Give each machine a range of terms and all their postings. A query for distributed consensus goes only to the machines holding those two terms.
Good: a query touches only a few machines, so total work per query is small.
Bad: the postings of a common term like the or system are enormous and live on one machine. Intersecting distributed with consensus means shipping a long postings list from one machine to another over the network, per query. A popular term overloads its machine, and adding a document updates postings on many machines.
Approach B: partition by document
Give each shard a subset of the pages, indexed completely: every term for those pages. Every query goes to every shard, each shard answers it locally over its own pages, and a coordinator merges the per-shard top results.
Good: no postings move between machines. Only short top-K lists cross the network. Adding a page touches one shard, load balances naturally, a failed shard loses a slice of pages instead of a whole term range, and a shard is a self-contained engine that can be built and tested alone.
Bad: every query costs a sub-query on every shard (3 million per second here), and per-shard work for rare terms is wasted on shards that have no match. It makes tail latency the main enemy.
Approach C: document partitioning with tiers and early termination
Keep approach B, and cut the cost within each shard. Sort postings by quality (static score or term impact) rather than docId for the head of each list, so a shard can stop after finding enough strong candidates. Split the corpus into tiers: a small top tier of high-authority pages, searched first, and a larger tier searched only if the first returns too few good results.
Good: most queries finish after the top tier, which holds a fraction of the pages, cutting CPU several times.
Bad: complexity, and a result can be missed if a good page sits in a lower tier and early termination stops too soon.
Diagram, as text
- Query leads to Frontend + cache
- Frontend + cache leads to Shard 1 top 20
- Frontend + cache leads to Shard 2 top 20
- Frontend + cache leads to Shard 200 top 20
- Shard 1 top 20 leads to Merge candidates
- Shard 2 top 20 leads to Merge candidates
- Shard 200 top 20 leads to Merge candidates
- Merge candidates leads to Re-rank top 500
- Re-rank top 500 leads to Snippets for 10
The recommended answer is B, with C's tiers added when CPU cost bites. The sentence to say: "Partition by document so the network carries only small top-K lists, and accept the fan-out, then spend the effort on the tail." Document partitioning is also how Lucene-based systems such as Elasticsearch shard an index.
The second decision: ranking in stages, and freshness
Stage ranking. Scoring every match with an expensive model is impossible: a query like best laptop may match millions of pages. Use a funnel:
- Retrieval, per shard: intersect postings and score with a cheap function (BM25 plus the page's stored link-authority score). Keep the top 20 per shard.
- Merge: the frontend combines 200 × 20 = 4,000 candidates and keeps the best 500.
- Re-rank: a richer model (many features, possibly a learned ranker) scores only those 500, which at 0.1 ms each costs about 50 ms.
- Snippets: fetch text only for the final ten, in parallel.
Link authority (as in PageRank) is computed offline by iterating over the link graph: a page matters if important pages link to it. It runs as a batch job over the crawl, and the result is a number stored per page, so it costs nothing at query time.
Freshness with tiers of indexes. A full rebuild of 1 billion pages takes hours or days, so a new page would wait. Keep a large base index, rebuilt weekly, plus a small fresh index built every few minutes from newly crawled pages. Queries search both and merge, and a page in the fresh index shadows its older version in the base. News and popular pages get recrawled often and appear in the fresh tier within minutes. When a new base index is ready it replaces both (a blue-green swap by version), and the fresh tier restarts small.
Bottlenecks and failures
Tail latency. Send a request to a replica, and if no answer arrives within about 95% of the typical latency, send a hedged copy to another replica and take the first response. Set a hard deadline for the whole fan-out (say 80 ms) and use what has arrived.
A shard is unavailable. With three replicas, a failure is invisible. If all replicas of one shard are down, one of 200 shards is 0.5% of the pages. Return results with a note of reduced coverage rather than failing, and alarm. Decide the threshold (for example, fail over to another region beyond 2% missing).
Head queries. A few hundred queries account for a large share of traffic (a long-tailed, Zipf-like distribution). A result cache with a TTL of one to a few minutes removes that load, and it needs invalidation only through TTL, which fits since the index changes slowly.
Expensive or malicious queries. A query with fifteen common words, or a pathological regex-like pattern, costs far more than average. Cap the number of terms, limit per-shard time and cost and isolate suspect queries so one cannot drag a shard down for everyone.
A bad index version. A build bug can make results empty or wrong. Canary the new index on a small slice of traffic and compare quality and latency against the current one before the swap, and keep the previous version for instant rollback.
Spam and manipulation. Pages stuff keywords and buy links to rank. Spam filtering happens at crawl and index time, and link-based signals discount obviously artificial link patterns. Mention it, and do not pretend it is solved.
Trade-offs to name aloud
- Document partitioning: simple, robust shards, in exchange for a fan-out that makes the tail the main enemy.
- Staged ranking: quality from expensive models on few candidates, in exchange for the cheap stage possibly missing a good page.
- Base plus fresh index: minutes-level freshness, in exchange for a merge step and shadowing logic.
- Caching head queries: big load savings, in exchange for results that can be a few minutes stale.
- Partial results over errors: availability, in exchange for slightly lower recall during failures.
What interviewers listen for
- A working answer: an inverted index, sharded across machines, with a frontend that queries the shards and merges results.
- A strong answer: chooses document partitioning with a reason, estimates fan-out and index size, uses a result cache and replicas, and ranks in stages.
- A standout answer: also does the tail-latency arithmetic, hedges requests with deadlines and partial results, builds a fresh tier beside the base index, canaries index versions and separates offline link analysis from query-time scoring.
Check your understanding
Common mistakes
Answering "Elasticsearch" and stopping. It is the right tool for product search and not an answer at this scale. Explain sharding, fan-out and ranking.
Partitioning by term without noticing the network cost. It looks efficient because queries touch few machines. The long postings lists are what hurt.
Ignoring tail latency. Mean latency per shard says little about a 200-way fan-out. Do the 1 − 0.99²⁰⁰ calculation.
One ranking function for everything. Running an expensive model on every match is impossible. Stage the ranking.
No freshness plan. A weekly rebuild alone means news is invisible for days. Explain the fresh tier.
Failing a query when one shard is down. A missing 0.5% of pages almost never matters to a user. Partial results with an alarm beat an error page.
Practice
Your total latency budget is 200 ms at p95. How do you divide it across the stages of a query, and what do you do when a stage runs over?
Write your own answer first, on paper or in a note. Then compare.
Show a hint
Give the fan-out a hard deadline, and decide which later stages can use a reduced input.
Show a strong answer
Budget it. Parsing and spell handling 10 ms, cache lookup 5 ms, shard fan-out with a hard deadline 60 ms, merge 10 ms, re-ranking 500 candidates 50 ms, snippets for the final ten 40 ms and rendering 15 ms. That sums to 190 ms, leaving 10 ms of slack.
Enforce the shard deadline. At 60 ms the frontend stops waiting and uses the shards that answered. Hedged requests to second replicas at about 30 ms make late shards rare. Record any missing shards and expose coverage in metrics.
Shrink the downstream input when time is short. If the fan-out used its full 60 ms, re-rank only the best 200 candidates instead of 500, which costs about 20 ms. Snippet fetches run in parallel, and a slow one is replaced by a stored short description.
Measure each stage separately. An overall p95 hides which stage is eating budget. Track per-stage percentiles and alert on budgets, not only on the total.
The pattern worth keeping: give each stage a budget and a degradation, so overrunning one stage costs a little quality instead of the whole response.
One shard has lost all three replicas in a zone failure. Do you return results, and how do you decide?
Write your own answer first, on paper or in a note. Then compare.
Show a hint
Compute what fraction of the index is missing and what that does to users.
Show a strong answer
Compute the missing share. One of 200 shards is 0.5% of the pages. For most queries, the best results sit in other shards, and the user cannot tell.
Serve partial results. Return results from the remaining 199 shards, and mark the response internally as reduced coverage so you can measure how often it happens. An error page would harm 100% of queries to protect 0.5% of coverage.
Set a threshold. Define the loss that triggers failover: if more than about 2% of shards (four shards) are unavailable, route traffic to another region's full copy, because navigational queries for specific pages in those shards would start to fail visibly.
Repair. Rebuild the shard's replicas on healthy machines from the stored index files and bring them in gradually. Alert on shard health independently of user latency, since users cannot see this problem.
The pattern worth keeping: in a wide fan-out, degrade coverage gracefully and measure it, instead of treating every missing part as a total failure.
Key takeaways
- Fan-out is the defining cost: 200 shards turn 15,000 queries per second into 3 million shard-queries.
- Partition by document so only top-K lists cross the network.
- Tail latency dominates: with 200 shards a per-shard p99 becomes the typical query's latency, so hedge, set deadlines and return partial results.
- Rank in stages: cheap retrieval per shard, then a rich re-rank of a few hundred candidates.
- Combine a big base index with a small fresh one for minute-level freshness.
- Roll out new indexes by version, canaried and ready for rollback.
Further reading
- J. Dean and L. Barroso, "The Tail at Scale", Communications of the ACM (2013): hedged requests and why fan-out amplifies tail latency.
- J. Dean, "Challenges in Building Large-Scale Information Retrieval Systems", WSDM keynote (2009): sharding, tiers and updates in a web-scale index.
- S. Brin and L. Page, "The Anatomy of a Large-Scale Hypertextual Web Search Engine", WWW (1998): link analysis and index structure in an early search engine.
- C. Manning, P. Raghavan and H. Schütze, "Introduction to Information Retrieval" (Cambridge University Press, 2008).