Course contents

17. Real-World System Design Lesson 15 of 20

Search Engine

Design web search end to end: crawling, a queue-fed indexing pipeline, sharded and replicated inverted indexes, query fan-out, tail latency and ranking.

25 minAdvanced10 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Search is an offline pipeline (crawl, index) feeding an online query path that answers in milliseconds.
  • A queue between crawlers and indexers absorbs bursts; its depth is the freshness lag.
  • Document-partitioned shards each hold a full index for a subset of pages; every query fans out to all shards and the broker merges.
  • A query is as slow as its slowest shard, so fan-out turns rare slowness into common slowness.
  • Replicas, outlier ejection, hedged requests and partial results keep one machine from setting the pace.
  • Rank cheaply on every shard and expensively on a few hundred candidates.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

A search engine finds the most relevant documents for a short text query out of a very large collection. It has two halves: an offline pipeline that crawls documents and builds an inverted index (for each term, the list of documents containing it, with positions and statistics), and an online query path that looks up the query's terms, combines and scores the matching documents, and returns the top results with snippets.

Why it exists

Scanning billions of documents per query is impossible within a latency budget of a few hundred milliseconds. An inverted index turns a query into a few posting-list lookups and intersections. At web scale the index no longer fits on one machine and the query rate exceeds what one machine serves, so the index is split into shards and replicated, which brings its own problems: every query now depends on many machines.

How it works

Requirements. Functional: crawl, index, answer keyword queries with ranked results and snippets. Non-functional: P95 query latency within a few hundred milliseconds, high availability (partial results beat errors), freshness from minutes (news) to days (long tail).

Estimates (illustrative). 10 billion pages × ~20 KB of text ≈ 200 TB. A compressed inverted index is typically a sizable fraction of the text size, plus forward data for snippets: hundreds of terabytes across thousands of machines once replicated. Billions of queries per day is tens of thousands per second, with peaks a few times higher. Re-crawling 10 billion pages every 30 days needs about 4 000 fetches/s, more for fast-changing sites.

Crawling. A URL frontier prioritises what to fetch (importance, change rate) and enforces politeness: limited connections per host, delays between requests, robots.txt respected. Fetchers resolve DNS (with a local cache), download pages and hand them to the pipeline. Near-duplicates are detected (e.g. by content fingerprints such as SimHash) and links are extracted back into the frontier.

Indexing. Fetched pages go onto a queue consumed by indexers that parse, tokenise and normalise text, and build index entries. Lucene-style engines write immutable segments and merge them in the background; a new segment becomes searchable when it is published (refreshed). Large engines often keep a small real-time index for fresh content beside the big, batch-built one.

Sharding and fan-out. With document partitioning, each shard holds the full inverted index for a subset of documents. A query broker sends the query to every shard (scatter), each shard returns its local top-k, and the broker merges them into the global top results (gather). Term partitioning puts each term's posting list on one shard; a query touches fewer shards, but multi-term queries must move posting lists across machines and popular terms create hot shards, which is why it is rare at web scale.

Tail latency. Because the broker waits for every shard, the slowest shard sets the query's latency. If each of 100 shards is slow 1% of the time, about 63% of queries hit at least one slow shard. Mitigations: replicas behind least-outstanding-requests balancing, outlier ejection of slow machines, hedged requests (send a second copy to another replica if the first has not answered within its P95; take the first answer), per-shard deadlines with partial results, and keeping shards small enough that their work is short.

Ranking. Each shard scores its matches with a cheap function (BM25 term statistics plus static signals such as page quality) and returns a few hundred candidates. The broker merges them and a re-ranker applies a heavier model (often a learned model; in 2026 frequently including neural or embedding-based relevance signals) to the top candidates. Snippets are generated only for the results displayed.

When to use it

This architecture fits any large full-text search: web search, site or product search over millions of items, log and document search. The same shapes (queue-fed indexing, document-partitioned shards, replicas, scatter-gather) appear in Elasticsearch and OpenSearch clusters at much smaller scale.

When not to

  • A few million documents fit on one well-provisioned node; sharding adds fan-out and merge cost for nothing.
  • Exact lookups by key or structured filters are better served by a database index.
  • Pure semantic similarity search over embeddings needs a vector index (approximate nearest neighbours), often combined with, not replaced by, an inverted index (hybrid retrieval).

Trade-offs

Choice You gain You pay
Document partitioning Local indexing and scoring, simple rebalancing Every query touches every shard; tail latency amplification
Term partitioning Fewer shards per query Posting lists cross the network; hot terms create hot shards
More, smaller shards Shorter per-shard work, faster recovery More fan-out, more merge work, more chances to hit a slow shard
More replicas Throughput, availability, room to hedge Machines and storage multiply
Hedged requests Much lower tail latency A few percent extra load; needs idempotent reads
Faster refresh Fresher results More small segments, more merge I/O

Alternatives

  • Managed or open-source search clusters (Elasticsearch, OpenSearch, Vespa, Solr) implement the same building blocks; at moderate scale, use one instead of building.
  • Database full-text indexes (e.g. PostgreSQL GIN with tsvector) for small, transactional datasets.
  • Vector and hybrid retrieval for semantic search, usually blended with BM25.

Failure modes

  • Slow shard or replica: no errors, but every query waits; visible in P50, not only P99.
  • Replica crash: errors during the health-check detection window unless the broker retries on another replica or returns partial results.
  • Whole shard unavailable: without partial results, every query fails; with them, recall drops silently. Monitor result completeness.
  • Indexing backlog: queries are fine but freshness degrades; alert on queue age, not only depth.
  • Hot queries: a viral query hammers the same posting lists; a result cache in front of the broker absorbs repeats.
  • Bad segment or ranking deploy: relevance regressions are silent failures; canary them with offline and online quality metrics.

In production

Cache popular query results with a short TTL. Give each shard call a deadline and decide explicitly whether to return partial results. Track per-shard and per-replica latency and eject outliers automatically. Size replicas for peak traffic with one replica lost. Monitor crawl politeness and error rates per host. Measure freshness (time from fetch to searchable) and relevance (click-through, offline judgments), not just latency.

Common misconceptions

  • "Sharding makes each query cheaper." With document partitioning, each query does work on every shard; sharding raises capacity and keeps per-shard work short, but adds fan-out.
  • "Tail latency only matters for the slowest 1% of users." With fan-out, per-component tails compound; most queries can hit some slow component.
  • "Health checks fix slow machines." A slow machine usually passes health checks. It needs latency-based outlier detection.
  • "The index is updated in place." Most engines write immutable segments and merge them later.

Interview angle

Split the problem into crawl, index and serve. Give estimates for index size, QPS and crawl rate. Draw the inverted index and explain document vs term partitioning. Interviewers usually push on tail latency at fan-out (answer with replicas, hedging, deadlines and partial results), freshness (real-time index tier, segment refresh), ranking stages, result caching, and politeness and deduplication in the crawler.

Model assumptions

The simulation is a simplified model, not a benchmark, running a small slice of the illustrative scale. Crawlers deliver 140 pages/s; each Indexer has 4 slots and ~80 ms per page; Indexers 3 and 4 come online one second into their step. The single index node has 8 connections and ~30 ms per query; each document shard (and replica) has 32 connections and ~10 ms per query (lognormal), with a 300 ms pool timeout. Once the index is sharded, the broker sends each query to all shards at the same time and merges when the last one has answered, so a query costs the slowest shard's time, not the sum. The slow machine is modelled as 5× service time. Shard balancers use least connections with health checks every 500 ms (2 failures eject, 2 successes restore). The URL frontier, robots.txt fetch, segment shipping and two-phase ranking are scripted illustrations; hedged requests and partial results are described, not simulated. Metric tiles include the crawlers' queue writes, which are fast; the tests measure query latency separately. Numbers show behaviour and orders of magnitude only.

The lesson as textEvery step of the simulation, written out.
  1. 1. Requirements and estimates

    We are designing web search: type a few words, get the ten most relevant pages out of billions, in a few hundred milliseconds. Functional needs: crawl the web, index what was fetched, answer keyword queries with ranked results and snippets. Non-functional: P95 query latency under about 300 ms, high availability (a partial answer beats an error page), and freshness: new and changed pages searchable within hours, news within minutes.

    Illustrative estimate: 10 billion pages × 20 KB of text ≈ 200 TB of text; the inverted index is a sizable fraction of that, far beyond one machine. Queries: billions per day is tens of thousands per second, with peaks above that. Crawling 10 billion pages every 30 days is about 4 000 pages/s before re-crawls of fast-changing sites.

    The scene starts with the query path only: 150 queries/s against one inverted index node, which maps each term to the list of documents containing it.

    Scene: Searchers send 150 queries per second to a Query Broker that looks them up in a single Inverted Index node. Annotations give the illustrative full-scale estimates.

    Key idea: Search is two systems: an offline pipeline that builds the index, and an online path that must answer from it in milliseconds.

  2. 2. Crawling: fetch politely, queue for indexing

    Before anything can be searched it has to be fetched. A URL frontier decides what to crawl next (priority by importance and change rate) and enforces politeness: one connection per host at a time, a delay between requests, and robots.txt checked first. The scripted packets show one fetch: URL from the frontier, robots.txt, then the page.

    Fetched pages go onto a queue for the Indexers, which parse them, drop near-duplicates, extract terms and links, and build index entries. Here the crawlers deliver 140 pages/s but two indexers manage only about 100. The queue absorbs the difference, so crawling never blocks, but it grows by about 40 pages every second: each page waits longer before it becomes searchable.

    Scene: A URL frontier hands URLs to the Crawlers, which fetch robots.txt and then the page from the web site (scripted). Crawlers put 140 fetched pages per second onto a queue; two Indexers process about 100 per second, so the queue keeps growing.

    Key idea: A queue decouples crawling from indexing. Its depth is your freshness lag.

  3. 3. Scale the indexers, ship immutable segments

    One second in, two more Indexers come online. Together the four handle about 200 pages/s, more than the crawl rate, so the backlog drains within a few seconds and the queue then stays near empty: pages become searchable moments after they are fetched.

    Indexers do not edit the live index in place. They write new, immutable index segments and ship them to the shards, which merge small segments into larger ones in the background (this is how Lucene-based engines work). Readers keep searching the old segments until the new one is published. The scripted packets show a segment being shipped.

    Scene: Indexer 3 and 4 come online one second in. Four indexers process about 200 pages per second, the queue backlog drains within a few seconds and then stays near empty. A scripted packet shows an index segment shipped to the index.

    Key idea: Indexing is embarrassingly parallel: add workers until they outpace the crawl. Publish results as immutable segments.

  4. 4. One index node cannot keep up

    One second in, queries climb to 400 per second. A single index node answers about 270 per second (8 lookups at a time, ~30 ms each). Its connection pool fills, queries wait, and those waiting longer than 300 ms fail.

    And this node is pretending: a real web index does not fit on one machine at all. Both problems, size and query rate, point to the same fix.

    Scene: Queries rise to 400 per second. The single index node saturates and queries fail with pool timeouts.

    Key idea: Index size and query rate both outgrow one machine. Split the index.

  5. 5. Shard by document, fan out every query

    The index is split into three shards by document: each shard holds the complete inverted index for a third of the pages. Any shard may contain matches for any term, so the broker sends every query to every shard; each returns its local top results and the broker merges them into the global top ten.

    Each shard searches only a third of the data (~10 ms here), but it receives every query: 400/s each. Shards are sized for that, and the errors stop.

    The broker asks all three shards at the same time and merges when the last answer is in, so the shard calls overlap instead of adding up: a query is only as fast as its slowest shard. Watch the three packets leave together and the broker wait for the last reply.

    Scene: The index is split into Shard 1, 2 and 3. The Query Broker sends every query to all three at the same time and merges the results once the last one has answered. At 400 queries per second nothing fails.

    Key idea: Document partitioning: every query fans out to every shard and the broker merges. Latency is set by the slowest shard.

  6. 6. One slow shard slows every query

    One second in, Shard 2’s machine becomes five times slower (a noisy neighbour, a long garbage-collection pause, a failing disk). It still answers, so nothing errors.

    But every query waits for Shard 2. Typical latency, not just the tail, jumps by about 40 ms. With fan-out, the tail of one component becomes the common case of the whole: with 100 shards each slow 1% of the time, about 63% of queries hit at least one slow shard.

    Scene: Shard 2 becomes five times slower. Queries still succeed, but every query waits for it: median and P95 latency both rise by about 40 ms.

    Key idea: Fan-out amplifies tail latency: a query waits for the slowest of all the shards it touches.

  7. 7. Replicate each shard, route around the slow one

    Each shard now has two replicas behind a small balancer. The balancer uses least connections: a slow replica holds its queries longer, so it is picked less often, and about three quarters of Shard 2’s traffic moves to the healthy replica B. The median falls back close to normal while replica A is still slow. P95 improves less: a quarter of Shard 2’s queries still land on the slow machine.

    Replicas also double query capacity and keep a shard available when a machine dies. Large engines go further: hedged requests (if a shard has not answered within its P95, ask another replica and take the first answer) and partial results (answer without a shard that missed its deadline). Hedging and partial results are described here, not simulated. Simplest of all: detect the outlier and take it out of rotation.

    Scene: Every shard has replicas A and B behind a least-connections balancer. Shard 2 replica A is still slow, so its balancer sends about three quarters of its queries to replica B. Median latency drops back close to normal; P95 improves less.

    Key idea: Replicas turn a slow or dead machine from everyone’s problem into a routing decision.

  8. 8. A replica crashes

    One second in, Shard 1 · A crashes. The queries it was working on fail, and its balancer does not know yet: queries it keeps sending there are refused. Because every query needs every shard, each of those queries fails. After two missed health checks (at most about a second) the balancer stops routing to it and Shard 1 · B carries the whole shard alone.

    The errors are limited to the detection window. A broker that retried a refused shard call on the other replica, or returned results without that shard, would hide even those.

    Scene: Shard 1 replica A crashes. Some queries fail until Shard 1’s balancer ejects it after two failed health checks; then replica B serves all of Shard 1 and errors stop.

    Key idea: With replicas, a machine failure costs a detection window of errors, not an outage.

  9. 9. Ranking in two phases

    So far a shard returned “its top results”. Ranking is what makes that useful, and it happens in phases. Each shard scores its matches with a cheap function (term statistics such as BM25, plus query-independent signals like page quality) and returns only its top few hundred. The broker merges those and sends the best candidates to a re-ranker, a heavier model that uses many more signals. Snippets are generated last, only for the ten results shown.

    The packets are a scripted illustration of that order. The expensive model never sees billions of pages, only hundreds of candidates, so the latency budget holds.

    Scene: Scripted packets: the broker sends the query to all three shards, which return their locally scored top results; the broker merges them and sends the best candidates to the Re-ranker, which returns the final order.

    Key idea: Rank cheaply and locally on every shard, expensively and centrally on a few hundred candidates.

  10. 10. What this design trades

    Document vs term partitioning: by document (this lesson) every query hits every shard but indexing is local and simple; by term, a query only touches the shards of its terms, but multi-term queries must move long posting lists between machines and popular terms create hot shards. Web-scale engines partition by document and add a tier of replicas.

    Freshness vs cost: crawling and indexing faster costs machines and bandwidth; a small real-time index for news beside the big batch-built one is common. Tail latency vs cost: more replicas, hedging and partial results all spend resources to cut the tail. Recall vs latency: deadlines on shards may drop a good result.

    Scene: The full design: crawlers, a fetched-pages queue and four indexers on the offline side; a query broker fanning out to three replicated shards and a re-ranker on the online side. Shard 1 · A is back; Shard 2 · A is still slow.

    Key idea: A search engine trades fan-out cost for simple indexing, and spends replicas to keep the slowest shard from setting the pace.