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.