Skip to content

Design a Web Search Engine (Google Search)

Advanced 96 min read Part 17 of 18

Design web search: crawl-to-index pipeline, sharded inverted index, BM25 + PageRank + learning to rank, tiered serving, result caching, freshness, spelling.

The Problem#

Design a system where anyone types a few words and, in a fraction of a second, gets back the ten most useful pages on the whole public web:

  • A user types best way to store passwords into a search box. About 200 ms later they see ten links. Each has a title, a URL and a two-line snippet that shows the query words in context. The first result is very likely the one they wanted.
  • The system has read and indexed tens to hundreds of billions of web pages. It has to answer tens of thousands to over a hundred thousand queries per second around the clock, from every country, in many languages.
  • The results must be relevant, not just "pages containing these words". Millions of pages contain "store passwords". The engine must rank the page from a respected security site above a spam page that repeats the phrase 500 times.
  • The results must be fresh. If an earthquake happened ten minutes ago, a query for it should show news about it, not pages from last year. If a page was deleted yesterday, it should stop appearing soon.
  • The engine must be forgiving. pasword hashign should still find pages about password hashing, and the search box should suggest completions as the user types.

Google, Bing, Baidu, Yandex, Naver, DuckDuckGo (which mostly uses Bing's index plus its own sources) and Brave Search all solve this problem. The original design of Google is public. "The Anatomy of a Large-Scale Hypertextual Web Search Engine" (Sergey Brin and Lawrence Page, WWW 1998) describes a system that crawled about 24 million pages, stored them in a 53 GB compressed repository and built a 37 GB inverted index. Later papers describe how the design evolved. "Web Search for a Planet: The Google Cluster Architecture" (Barroso, Dean and Hölzle, IEEE Micro 2003) covers the serving cluster. "Large-scale Incremental Processing Using Distributed Transactions and Notifications" (Peng and Dabek, OSDI 2010) introduced Percolator, the system behind incremental indexing. We use these as anchors and hedge anything that is not public.

What makes the problem interesting:

  • Two very different systems in one. There is a huge offline pipeline that crawls, parses, deduplicates, analyses links and builds indexes. It processes petabytes and is measured in pages per day. There is also an online serving system that answers one query in about 100–300 ms by fanning it out to thousands of machines. The two meet at the index, and almost every design decision is about how the index is built, split, stored, updated and read.
  • Ranking is the product. Finding the pages that contain the words is the easy part, thanks to the inverted index. Choosing the best ten out of a million matches is the hard part. It combines text-match scores (such as BM25), link-based authority (such as PageRank), hundreds of other signals, and machine-learned models, all inside a strict latency budget.
  • Fan-out makes tail latency the enemy. A query touches every index shard. If each of 1,000 shards is slow 1% of the time, almost every query hits at least one slow shard. The serving design must make the whole system fast even though some machines are always slow.
  • The web is adversarial and messy. Pages are broken HTML, duplicates, spam, link farms, infinite calendars, cloaking and content that changes every minute. The pipeline must survive all of it.
  • Freshness fights efficiency. Building an index in one big batch is efficient but leaves results days old. Updating it continuously is fresh but much harder. Real engines use both.

Analogy. Think of the largest library ever built, where new books arrive every second and old ones are rewritten or thrown away constantly. A fleet of collectors (the crawler) roams the world bringing back copies of every book. Clerks (the indexer) read each book and add every word to a giant card catalogue. Each word gets a drawer listing every book and page where it appears (the inverted index). A panel of critics notes which books are cited by many other respected books (PageRank). When a visitor asks a question, a team of librarians (the serving tier) splits the catalogue between them. Each searches their own drawers at the same time and sends back their best candidates. A head librarian merges them, using everything they know about quality to pick the ten best (ranking). Popular questions are written on a whiteboard by the door with their answers (the result cache). A special shelf by the entrance holds this morning's newspapers so that news questions get today's answers (the fresh tier).

Background: a few terms used in this design#

  • Crawler: the system that downloads web pages by following links, respecting robots.txt and politeness limits. Designed in depth in the case study Design a Web Crawler. Here we treat it as the input to the indexing pipeline.
  • Document (doc): one indexed unit, usually one canonical web page. Each document gets a compact integer docID.
  • Term: a normalised word or token (for example, running might be stored as run). Each term gets a termID in the lexicon (the dictionary of all terms).
  • Inverted index: a map from each term to the list of documents that contain it. That list is called a posting list, and each entry is a posting: a docID plus, optionally, the term frequency and the positions of the term in the document.
  • Forward index: the opposite map, from each document to the terms it contains. It is an intermediate product of indexing and is also used for snippets and features.
  • Term frequency (tf): how many times a term appears in a document.
  • Document frequency (df): how many documents contain a term. Rare terms (low df) carry more information than common ones.
  • IDF (inverse document frequency): a weight that grows as a term gets rarer, roughly log(N / df) for N documents.
  • BM25: the standard text-relevance formula. It combines tf, IDF and document length, with saturation so that repeating a word 500 times does not help much.
  • PageRank: a score of a page's importance computed from the link graph. A page is important if important pages link to it.
  • Anchor text: the clickable text of a link pointing to a page. It is often a better description of the page than the page's own text.
  • Learning to rank (LTR): training a machine-learning model to order results using many features (BM25, PageRank, clicks, freshness and others), with labels from human raters and user behaviour.
  • Query processing: turning raw user input into an executable query. Steps include tokenising, normalising, spelling correction, expansion with synonyms and understanding intent.
  • Index shard: one slice of the index held by one group of machines. A document-partitioned index splits by documents; a term-partitioned index splits by terms.
  • Root, aggregator and leaf servers: the serving tree. The root receives the query; aggregators (also called mixers or brokers) fan it out and merge results; leaves each search one shard.
  • Top-k retrieval: finding the k highest-scoring documents without scoring every match. Uses algorithms such as WAND and Block-Max WAND.
  • Tiered index: splitting the index by quality or freshness into tiers, so most queries are answered from a small, high-quality tier and only some fall through to the full index.
  • Snippet: the short extract shown under each result, chosen to show the query words in context.
  • SERP (search engine results page): the full page of results, including ads, news boxes, images and knowledge panels.
  • Freshness: how up to date the index is relative to the live web. Measured as the age of indexed copies, or as the delay from a page changing to the change being searchable.
  • Incremental indexing: updating the index document by document as pages change, instead of rebuilding it in periodic batches.
  • Near-duplicate detection: finding pages that are almost the same (mirrors, printer-friendly versions, scraped copies) using fingerprints such as SimHash or MinHash.
  • NDCG (normalised discounted cumulative gain): the standard metric of ranking quality. It rewards putting highly relevant results near the top.

Clarifying Questions#

QuestionWhy it mattersAssumed answer
Is this general web search or search inside one site or app?Web search needs a crawler, link analysis and spam defence. Site search can sync from a database and use Elasticsearch directly.General web search. We also explain the smaller "site search" ladder, because it is a common interview variant.
How many documents should the index hold?Drives index size, shard count and machine count.About 50 billion documents in the main index (the visible web has far more URLs, but most are duplicates or junk).
What query volume?Drives replica count, cache size and data-centre footprint.About 100,000 queries per second at peak, 50,000 on average. That is roughly 4–5 billion queries per day.
What latency target?Sets the per-tier budget and forces in-memory serving and fan-out.p50 under 150 ms and p99 under 400 ms at the server, excluding the user's network.
How fresh must results be?Decides whether batch rebuilding is enough or we need incremental and real-time tiers.Breaking news searchable within minutes. Popular pages re-indexed within hours to a day. The long tail within weeks.
Is ranking personalised?Personalisation lowers cache hit rates and needs user data at query time.Light personalisation only (language, country, location for local intent, safe-search setting). Mostly the same results for the same query.
Which result types?Images, video, news and maps are separate verticals with their own indexes.Web pages ("ten blue links") with snippets. We sketch how verticals blend in, but do not design them.
Do we need autocomplete and spelling correction?Each is a sub-system with its own data and latency budget.Yes. Spelling correction ("did you mean") and query autocomplete.
How many languages?Tokenisation, stemming and spelling models are per language.Many languages; we design language-aware text processing but do not detail each language.
Do we serve ads?Ads are a separate auction system that runs in parallel.Out of scope, except as a parallel call on the results page.
Do we build the crawler?It is a full system on its own.No. We assume a crawler that delivers fetched pages and change signals, and we design what happens after fetch.
How available must search be?A search outage is front-page news.99.99% for serving, served from several regions. The indexing pipeline can be down for hours without users noticing, as long as serving continues.

Requirements#

Functional requirements#

  1. Search: given a text query, return the top results (title, URL, snippet) ranked by relevance and quality, with pagination.
  2. Index the web: turn fetched pages into a searchable index. This covers parsing, cleaning, deduplication, link extraction, text analysis and inverted-index building.
  3. Rank well: combine text relevance, link authority, freshness, user-behaviour signals and spam signals into one ordering.
  4. Stay fresh: reflect new, changed and deleted pages quickly. Recency-sensitive content should be searchable in minutes.
  5. Correct and complete queries: suggest spelling corrections and autocomplete query prefixes.
  6. Respect removals: remove pages that are blocked by robots rules, marked noindex, deleted, or subject to legal removal requests.

Out of scope: the crawler internals, ads, image and video search, the knowledge graph, and question answering with LLMs (mentioned only as an extension).

Non-functional requirements#

  • Low latency: p50 under 150 ms and p99 under 400 ms server-side for a full results page. Autocomplete under 50 ms, because it runs on every keystroke.
  • High throughput: 100,000 queries per second at peak across regions, with headroom for spikes (big news events can double traffic in minutes).
  • High availability: 99.99% for search serving. Degrade gracefully. Losing a shard should make results slightly worse, not make the query fail.
  • Scale of data: about 50 billion documents, a few petabytes of raw content and hundreds of terabytes of index.
  • Freshness: minutes for news and fast-changing sites, hours to days for most popular pages, weeks for the long tail.
  • Relevance: measured offline with human ratings (NDCG) and online with user behaviour (clicks, abandonment, reformulation) in controlled experiments.
  • Cost efficiency: every byte of index is multiplied by its replica count, and every microsecond of CPU per document is multiplied by billions. Compression and early termination are cost features, not just speed features.
  • Robustness to spam and abuse: ranking must resist keyword stuffing, link farms and cloaking.

Capacity Estimation#

These are order-of-magnitude numbers to drive the design. The method is in Back-of-the-Envelope Estimation. Google has said publicly that its index holds "hundreds of billions" of pages. We size a smaller but still web-scale engine, with 50 billion documents in the main index.

Query traffic.

  • 4.3 billion queries per day ÷ 86,400 s ≈ 50,000 queries per second on average. Assume 100,000 per second at peak (a 2x daily peak, plus spikes during major news).
  • Each query fans out to every index shard (we will reduce this with tiers). With 1,000 shards and no cache, the peak is 100,000 × 1,000 = 100 million leaf lookups per second. This one number explains why caching, tiering and early termination matter so much.
  • Autocomplete runs on keystrokes. If the average query causes 4–6 suggestion requests (clients debounce, so not every keystroke), that is 400,000–600,000 suggestion requests per second at peak. Each must be cheap.

Documents and raw content.

  • 50 billion documents. A typical HTML page today is tens of kilobytes of markup (the median is around 30 KB) plus much larger scripts and images, which we do not store. Assume 60 KB of HTML per page, compressed about 4:1 to 15 KB.
  • Raw repository: 50 × 10⁹ × 15 KB ≈ 750 TB for one copy of the latest version of every page. With 3x replication and a few historical versions for change detection, about 3–5 PB.
  • Extracted visible text averages about 600 tokens (roughly 4–6 KB of text). Compressed, that is about 2 KB per document, so about 100 TB for the document store that feeds snippets.

The inverted index.

  • Token occurrences: 50 × 10⁹ docs × 600 tokens = 3 × 10¹³ (30 trillion) positions.
  • Postings (unique terms per document, about 300 on average): 50 × 10⁹ × 300 = 1.5 × 10¹³ (15 trillion) docID entries.
  • With delta encoding and a good integer codec (Deep Dive 2), a docID gap costs about 1 byte and a term frequency about 0.5 bytes. That gives 15 × 10¹² × 1.5 B ≈ 22 TB for a non-positional index.
  • Positions for phrase and proximity scoring cost about 1.5 bytes each: 30 × 10¹² × 1.5 B ≈ 45 TB.
  • Field information (title, anchor, URL, body), skip data and block-max metadata add perhaps 30%. About 90–100 TB for one full copy of the index.
  • Per-document "forward" data used by ranking (static quality score, PageRank, spam score, language, length, a few hundred packed features): about 200 bytes per document, so 10 TB.
  • Optional dense embeddings for semantic retrieval: 50 × 10⁹ × 128 dimensions × 1 byte (int8 quantised) ≈ 6.4 TB.

Serving machines (one region).

  • Split the index into 1,000 document-partitioned shards of 50 million documents each. Each shard is about 100 GB of index plus 10 GB of per-document data. That fits in the RAM of one 256–512 GB server, with room for the OS and caches.
  • Leaf cost: assume a leaf evaluates a typical query against its 50 million documents in about 10–20 ms of single-core time, thanks to top-k pruning. A 64-core leaf at 50% target utilisation then handles 64 × 0.5 ÷ 0.015 s ≈ 2,000 leaf queries per second.
  • Suppose 50% of queries are answered by the result cache (Deep Dive 8) and the rest go to the index. Peak load reaching the index is then 50,000 queries per second. If split across 3 serving regions, each region needs about 17,000 queries per second per shard. That means 17,000 ÷ 2,000 ≈ 9 replicas of each shard, so about 9,000 leaf servers per region. Add a spare replica or two per shard, plus aggregators and document servers.
  • Tiering (Deep Dive 4) cuts this further. If 70% of index queries are answered from a first tier holding the best 20% of documents, most queries touch 200 shards instead of 1,000.
  • The whole fleet is tens of thousands of servers for serving, across regions. Barroso, Dean and Hölzle (2003) described a single query reading hundreds of megabytes of data and using tens of billions of CPU cycles across many machines. The same "huge fan-out over commodity servers" shape still applies.

Response sizes and the merge.

  • Each leaf returns its top 50 candidates as (docID, score, a few features), about 32 bytes each. That is 1.6 KB per leaf.
  • With 1,000 leaves this is 1.6 MB per query arriving at aggregators. With a two-level tree (the root, then 30 aggregators, then about 33 leaves each), no single machine receives more than about 50 KB per query.
  • Snippets: the final 10 results need 10 document-server lookups of about 2 KB of text each. These are cheap.

Indexing throughput.

  • If the average document is re-crawled every 10 days, the pipeline must process 50 × 10⁹ ÷ 10 = 5 billion pages per day, about 58,000 pages per second.
  • Inbound bytes: 58,000 × 60 KB ≈ 3.5 GB/s (28 Gbit/s) of HTML.
  • Processing at about 50 ms of CPU per page (parsing, language detection, tokenising, deduplication, link extraction, feature extraction) is 58,000 × 0.05 ≈ 2,900 cores. Computing embeddings adds GPU time on top. Indexing is far cheaper than serving.
  • News and other fast-changing pages are a small share of documents but a large share of updates. A real-time tier might absorb tens of thousands of updates per second.

Link graph.

  • About 20 distinct out-links per page after deduplication gives 1 trillion edges. Stored as compressed adjacency lists at about 2–4 bytes per edge (sorted, delta-encoded targets), that is 2–4 TB.
  • One PageRank iteration streams every edge once. With 40–50 iterations on a few hundred machines, a full computation takes hours. Brin and Page reported that PageRank for 26 million pages took "a few hours on a medium size workstation" in 1998.

A smaller worked example: the query cache. A classic version of this problem asks only for the cache in front of a search engine. Assume 10 million users and 10 billion queries per month:

  • 10 × 10⁹ ÷ 2.5 × 10⁶ seconds per month ≈ 4,000 requests per second.
  • A cache entry holds the query (about 50 bytes), a title (20 bytes) and a snippet (200 bytes) per result. That is about 270 bytes for a single result. If every query were unique and cached, that would be 270 B × 10 × 10⁹ = 2.7 TB per month.
  • Real query streams are heavily skewed, so a much smaller cache of the popular queries captures most hits. We design this cache in Deep Dive 8.
QuantityEstimate
Documents in main index50 billion
Peak search QPS100,000
Peak autocomplete QPS400,000–600,000
Raw HTML repository (one copy, compressed)about 750 TB
Inverted index (one full copy)90–100 TB
Per-document ranking dataabout 10 TB
Document store for snippetsabout 100 TB
Index shards (50M docs each)1,000
Leaf servers per regionabout 9,000–12,000
Pages processed per secondabout 58,000
Link graph edgesabout 1 trillion
Server p50 / p99 target150 ms / 400 ms

Core Entities#

  • Url / Host: a URL known to the system, its canonical form, its host, the crawl state, the last-fetch time, the HTTP status and the robots status. Hosts carry per-host politeness and quality data.
  • Document: one canonical, indexed page. Fields: docID (dense integer), URL, title, language, length, content hash, near-duplicate fingerprint, static quality score, PageRank, spam score, first-seen and last-changed times.
  • Term: an entry in the lexicon. Fields: termID, the normalised string, document frequency and a pointer to its posting list in each shard.
  • Posting list: for one term in one shard, the sorted list of (docID, tf, positions, field flags), compressed in blocks with skip pointers and per-block maximum scores.
  • Link: a directed edge (fromDocID, toDocID, anchor text). It feeds PageRank and anchor-text indexing.
  • Index segment: an immutable chunk of a shard's index, built at a known time. Shards are made of segments that are merged over time. Deletes are recorded as tombstones.
  • Shard / Tier: a shard is a document range or hash bucket with its replicas. A tier is a set of shards with a role (fresh, best-quality, full).
  • Query log entry: query text, normalised form, time, locale, results shown, clicks and dwell time. It feeds spelling, autocomplete, ranking features and evaluation.
  • Result cache entry: a key (normalised query plus locale, page number, safe-search setting and index version) and a value (the ranked list of docIDs with snippets, or the rendered page), with a TTL.
  • Suggestion: a query prefix mapped to its top completions with scores, built from the query log.

API Design#

The public API is small. Most of the design is internal RPCs between serving tiers.

GET /search?q=best+way+to+store+passwords&start=0&num=10&hl=en&gl=IN&safe=moderate
200 OK
Cache-Control: private, max-age=0
{
  "query": "best way to store passwords",
  "corrected_query": null,
  "estimated_total": 48300000,
  "results": [
    { "rank": 1, "url": "https://example.org/password-storage",
      "title": "Password Storage Cheat Sheet",
      "snippet": "Use a slow, salted hash such as Argon2id, bcrypt or scrypt to store passwords ...",
      "doc_id": "d_8f3a...", "last_crawled": "2026-11-30T08:12:00Z" }
  ],
  "next_start": 10,
  "search_id": "s_01HF..."
}
 
GET /complete?q=best+way+to+st&hl=en&gl=IN
200 OK
Cache-Control: public, max-age=300
{ "prefix": "best way to st", "suggestions": [
    "best way to store passwords", "best way to study", "best way to start a business" ] }
 
POST /removals                (authenticated, site owners and legal)
{ "url": "https://example.com/old-page", "reason": "outdated" }
202 Accepted

Notes on the public API:

  • start and num give offset pagination. This is acceptable here because users rarely go past page 2, and each page is re-ranked anyway. Most engines cap deep pagination at a few hundred results. The estimated_total is a rough estimate from posting-list sizes, never an exact count.
  • hl (interface language) and gl (country) feed ranking and caching. They are part of the cache key.
  • search_id ties later click logs to this result list, so learning to rank can join impressions with clicks.
  • Autocomplete responses are not personalised in this design, so they are cacheable at the CDN for a few minutes. Full result pages carry private caching because they may contain light personalisation.

Internal RPCs between serving tiers (shown as protobuf-style signatures):

Root.Search(QueryRequest) -> ResultPage
Aggregator.Search(QueryPlan, shards[], k) -> Candidate[]           // merges its leaves
Leaf.Search(QueryPlan, shard_id, k, deadline_ms) -> Candidate[]     // top-k on one shard
DocServer.GetSnippets(doc_ids[], QueryPlan) -> Snippet[]
Speller.Correct(raw_query, locale) -> Correction
Suggest.Complete(prefix, locale, k) -> Suggestion[]
IndexWriter.Apply(DocumentUpdate | Delete) -> Ack                   // fresh tier
  • A QueryPlan is the parsed, corrected and expanded query: a tree of terms with operators (AND, OR, phrase), weights and filters (language, safe search, site restriction). Building it once at the root means every leaf does the same work.
  • Every internal call carries a deadline. A leaf that cannot finish in time returns its best partial answer or nothing, and the aggregator proceeds without it (Deep Dive 3).

High-Level Design#

We build the design one requirement at a time, then combine the pieces. The offline side (crawl to index) and the online side (query to results) are separate systems that share the index.

1) Fetched pages are turned into a searchable index#

The crawler delivers raw fetched pages (URL, HTTP headers, body, fetch time) into a durable log. The indexing pipeline turns each page into an indexable document:

  1. Parse the HTML robustly. Real pages have broken tags, wrong character sets and megabytes of inline script. Extract the title, headings, visible body text, out-links with their anchor text, meta tags (including noindex and the canonical link), and structured data.
  2. Normalise and canonicalise. Decode the character set into Unicode, detect the language, and resolve the page's canonical URL (from rel=canonical, redirects and URL normalisation rules) so that ten URL variants of one page become one document.
  3. Deduplicate. Compute an exact content hash and a near-duplicate fingerprint (SimHash). If the page duplicates one already indexed, keep only the best copy as the canonical document and merge their signals (Deep Dive 11).
  4. Analyse text. Tokenise per language, normalise case and accents, optionally stem, and record each token's position and field (title, heading, body, URL, anchor).
  5. Extract links. Write (from, to, anchor text) edges to the link graph. Anchor text is attached to the target document's index entry, because it describes the target.
  6. Compute document features. These include length, language, freshness, a spam score from content classifiers and, later, the PageRank and quality scores computed offline.
  7. Build the index. Group the analysed documents into index shards and, inside each shard, invert the forward data (doc → terms) into posting lists (term → docs). Compress them and publish an immutable index segment (Deep Dive 1).

Two outputs leave this pipeline: the index segments shipped to serving leaves, and the document store (clean text and metadata) used for snippets and features.

The pipeline is a classic large-scale batch-plus-stream system. Each stage is idempotent and keyed by URL or docID, so it can be retried and re-run. The same code runs in a batch mode that rebuilds everything and a streaming mode that processes changed pages as they arrive (requirement 4). Batch and stream trade-offs are discussed in Batch vs Stream Processing.

2) Users search by keywords#

The online path is a tree of servers. A root server receives the query, does query processing once, and fans out to aggregator servers. Each aggregator fans out to a group of leaf servers, each holding one document-partitioned shard of the index in memory. Every leaf finds the top candidates in its shard, aggregators merge their leaves' lists, and the root merges the aggregators' lists. The root then fetches snippets for the final ten results from document servers and renders the page.

  • Why document partitioning? Each leaf holds complete posting lists for its own documents. It can evaluate a whole query, including AND, phrases and scoring, locally, and return a small top-k list. Network traffic per query is tiny and independent of posting-list length. The cost is that every query touches every shard. We compare this with term partitioning in Deep Dive 3.
  • Why replicas? Each shard is copied onto several leaves. The aggregator sends each query to one replica of each shard, chosen by load. Replicas give throughput (more queries per second) and availability (a dead leaf is skipped).
  • Why a tree? A single root merging 1,000 responses would be a network and CPU hotspot. A tree with fan-out of 30–50 per level keeps each merge small and lets aggregators apply deadlines to their own leaves.

3) Results are ranked well#

Ranking happens in stages, because the best models are far too expensive to run on every match:

  1. Retrieval and first-pass scoring at the leaf. For each matching document, compute a cheap score from BM25-style text relevance (with field weights, so a title match counts more than a body match), term proximity and a precomputed static score (PageRank, quality, spam). Keep the top 50–200 per shard using pruning algorithms that skip documents that cannot make the top k (Deep Dive 4).
  2. Second-pass ranking at the aggregator or root. Merge the shard results into the top 1,000 or so. Score them with a learning-to-rank model, typically gradient-boosted trees over hundreds of features (Deep Dive 7). Features come with the candidate from the leaf or from a fast per-document feature store.
  3. Final re-ranking of the top 20–100. Optionally run a neural model (a transformer cross-encoder that reads the query and the document text together). Apply diversity rules (not ten results from one site), freshness boosts for news-seeking queries, and blending with other verticals (news, images).

The static score is computed offline for every document. PageRank comes from the link graph (Deep Dive 6), and quality and spam come from classifiers. It is stored next to the posting lists, so a leaf can use it at no extra cost. Better still, documents can be numbered in static-score order, so the best documents come first in every posting list and early termination finds them sooner.

4) The index stays fresh#

A single monolithic index rebuilt every few days cannot show news from ten minutes ago. Instead we split the index into tiers by update rate:

  • Base tier. Most of the web, rebuilt or merged in large batches every few days to weeks. It is highly compressed and optimised for read speed.
  • Daily or incremental tier. Pages that changed since the last base build, re-indexed continuously and merged into new segments hourly.
  • Real-time (fresh) tier. News, social and fast-changing pages, plus pages from sitemaps and pings. They are searchable seconds to minutes after fetch. This tier is small (millions to low billions of documents) and lives in memory with an index format that accepts writes.

Every query searches all tiers in parallel and merges the results. When a document appears in more than one tier, the newest version wins. Deletes are recorded as tombstones in a small, fast-replicated "deleted docIDs" set that every leaf checks. Removal is therefore immediate even before the segment containing the page is rewritten. Google's 2010 move to incremental indexing (the Caffeine update, built on Percolator) is the landmark here. Peng and Dabek report that replacing the batch-based system with incremental processing cut the average age of documents in search results by 50% while processing the same number of documents per day (Deep Dive 9).

5) Queries are corrected and completed#

Two small services sit in front of the main search:

  • Spelling correction runs inside query processing at the root. It proposes a corrected query when the original looks misspelled. It uses a noisy-channel model: how likely is this correction as a query (learned from the query log), times how likely the user is to type the observed string when they meant it (an edit model). If the correction is very confident, the engine searches it directly and shows "Showing results for X". Otherwise it searches the original and offers "Did you mean X?" (Deep Dive 10).
  • Autocomplete is a separate, very fast service called on keystrokes. It maps each prefix to the top completions, built offline from the query log. The structure is a trie or finite-state transducer with precomputed top-k lists at each node, served from memory and heavily cached. It is designed in depth in the case study Design Search Autocomplete (Typeahead).

Query popularity follows a heavy-tailed, roughly Zipf-like distribution. A small set of head queries ("weather", "news", celebrity names) accounts for a large share of traffic. Caching their results is the cheapest capacity win in the whole system:

  • A result cache at the root maps a normalised query key to the final ranked list (docIDs, titles, snippets). A hit skips the whole fan-out and costs about 1 ms.
  • A posting-list cache on leaves keeps hot posting lists (or their decoded blocks) in memory, helping queries that share terms.
  • The CDN or edge can cache autocomplete responses and, for non-personalised results, even full result pages for a short TTL.
  • Entries expire by TTL and are also invalidated or refreshed when the index version changes. For news-sensitive queries the TTL is short (seconds to a minute); for stable queries it can be hours (Deep Dive 8).

The full high-level design#

Components:

  • Crawler: fetches pages, respecting politeness and robots rules, and schedules re-crawls by predicted change rate. It writes fetched pages to the fetched-page log. See the case study Design a Web Crawler.
  • Fetched-page log: a durable, partitioned log (Kafka-like for streaming, files on a distributed file system for batch) that decouples crawling from indexing.
  • Indexing pipeline: parsing, canonicalisation, deduplication, text analysis and feature extraction. Horizontally scaled stateless workers, keyed by URL.
  • Link graph and PageRank jobs: a large graph store and periodic batch jobs that compute PageRank, link-spam scores and aggregated anchor text per target.
  • Index builders: invert, compress and segment the forward data into per-shard index segments, published to the segment store on a distributed file system (see Distributed File Systems: GFS, HDFS and Successors).
  • Real-time index writers: apply streaming updates to the fresh tier's in-memory indexes.
  • Document store: cleaned text and metadata per docID, for snippets and ranking features. A sharded key-value store (Bigtable-like, or Cassandra or a similar wide-column store).
  • Front end: TLS termination, rate limiting, bot detection, and rendering of the results page.
  • Root servers: query parsing, spelling correction, query rewriting, cache lookup, fan-out, final ranking and snippet assembly.
  • Result cache: a sharded in-memory cache keyed by the normalised query.
  • Aggregators: fan out to a group of leaves with deadlines, merge top-k lists, and run second-pass ranking.
  • Leaves: hold one shard of one tier in memory and run first-pass retrieval and scoring.
  • Document servers: fetch document text and generate query-dependent snippets.
  • Suggest service: in-memory autocomplete over precomputed prefix tables.
  • Learning loop: logs every query, the results shown and the clicks. This trains ranking models, rebuilds suggestions and the speller, and powers offline evaluation and online experiments. Its outputs (ranking models, suggest tables, speller models and quality scores) flow back into serving and indexing.

Key Flows#

Flow 1: a query that misses the cache#

The user searches best way to store passwords. Nothing is cached for this exact key, so the query goes through the whole tree.

Timing budget for a typical miss, server-side:

StepTypical time
Front end, TLS already established, routing5–10 ms
Query parsing, spelling, rewriting5–15 ms
Cache lookupabout 1 ms
Fan-out to leaves and back (including the slowest leaf that is waited for)40–100 ms
Leaf retrieval and first-pass scoring (inside the above)10–50 ms
Merge and second-pass ranking10–30 ms
Neural re-ranking of the top 20–50 (if used)10–30 ms
Snippet generation5–15 ms
Rendering5–10 ms
Totalabout 100–250 ms

Flow 2: a misspelled query with a confident correction#

The user types pasword hashign. The speller finds that password hashing is far more likely and confident enough to auto-correct.

If the confidence had been moderate (say 0.6), the root would search the original query and show "Did you mean: password hashing?" above the results. Some engines search both in parallel and decide based on the result quality of each.

Flow 3: a news article becomes searchable in minutes#

A news site publishes an article and updates its sitemap. The crawler fetches it within a minute because the site is on a high-priority, frequently polled list.

The base tier does not know about this article yet. Queries see it because every query also searches the fresh tier. Days later, when the base build includes the article, the fresh-tier copy is dropped.

Flow 4: a new base index is rolled out#

Every few days a new base index (or a large merged set of segments) is built. Serving switches to it without downtime.

Key points: leaves load the new version next to the old one, or a replica group is taken out of rotation, loaded and returned. Traffic shifts gradually with automatic rollback, as in any canary deployment (see CI/CD and Deployment Strategies). The result cache key includes the index version, or the cache is flushed gradually, so that stale results from the old version are not served forever.

Flow 5: autocomplete on a keystroke#

Data Model#

The index itself is not stored in a database. It is a set of custom, immutable, compressed files loaded into memory. Around it are several ordinary stores.

The per-document metadata is a wide-column table keyed by URL hash (or docID), updated by the pipeline. It is shown in SQL-like form, but in practice it lives in a Bigtable-style store:

CREATE TABLE documents (
  url_hash        BINARY(16) PRIMARY KEY,   -- e.g. first 128 bits of SHA-256(canonical URL)
  doc_id          BIGINT,                   -- dense ID assigned at index build
  canonical_url   TEXT,
  language        CHAR(5),
  title           TEXT,
  clean_text_ref  TEXT,                     -- pointer into document store
  content_hash    BINARY(16),
  simhash         BIGINT,
  pagerank        REAL,
  quality         REAL,
  spam_score      REAL,
  first_seen      TIMESTAMP,
  last_changed    TIMESTAMP,
  last_indexed    TIMESTAMP
);
-- Query log for learning to rank and suggestions (append-only, in a data lake)
CREATE TABLE query_log (
  search_id   TEXT, ts TIMESTAMP, query TEXT, norm_query TEXT, locale TEXT,
  shown_doc_ids BIGINT[], clicked_ranks INT[], dwell_ms INT[]
) PARTITIONED BY (date);

The posting list on disk and in memory is a binary layout, not rows:

lexicon:     term_id -> (df, offset into postings file, max_score)
postings:    [block 0][block 1]...   each block = 128 postings
block:       header(last_doc_id, block_max_score, byte_len)
             doc gaps   (128 ints, bit-packed or PForDelta)
             tfs        (128 ints, bit-packed)
             positions  (separate stream, delta-encoded per doc)
skip list:   one entry per block -> (last_doc_id, offset)  lets WAND jump
DataStoreWhy
Fetched raw pagesDistributed file system or object storage, plus a logHuge, sequential writes and reads, cheap per byte
URL and host stateSharded wide-column store (Bigtable, HBase, Cassandra)Billions of rows, point updates by URL hash, scans for scheduling
Document metadata and featuresWide-column store, also exported to serving as packed arraysPoint lookups and batch exports
Clean text for snippetsSharded key-value store keyed by docID (in memory or SSD)Low-latency lookups of 10 docs per query
Inverted index segmentsCustom immutable files on a distributed file system, loaded into leaf RAMMust be compressed and read at memory speed
Fresh-tier indexIn-memory writable index (Lucene-style segments or custom)Supports appends and fast visibility
Link graphCompressed adjacency files for batch jobsScanned whole by PageRank iterations
Result cacheSharded in-memory cache (custom, or Memcached or Redis)Sub-millisecond reads, TTLs
Query and click logsData lake (Parquet on object storage) plus a streamTraining, analytics and suggest building
Suggest tablesImmutable in-memory tries or FSTs, rebuilt daily or hourlyPrefix lookups in microseconds

For a general framework on choosing among these, see Choosing a Database: A Decision Guide.

Deep Dives#

1. Building the inverted index: from pages to posting lists#

The simple idea. An inverted index answers "which documents contain this word?" by storing, for every term, the list of documents that contain it. Picture three tiny documents:

  • doc 1: "store passwords safely"
  • doc 2: "passwords and hashing"
  • doc 3: "store hashing results"

Inverting them gives:

TermPosting list (docID: positions)
and2: [1]
hashing2: [2], 3: [1]
passwords1: [1], 2: [0]
results3: [2]
safely1: [2]
store1: [0], 3: [0]

A query store AND hashing intersects the lists for store (1, 3) and hashing (2, 3) and finds doc 3. Because posting lists are sorted by docID, the intersection is a linear merge, and with skip pointers it is much less than linear (Deep Dive 4). The same structure powers Lucene, Elasticsearch and every web engine. It is introduced in Database Indexing and Elasticsearch and Search Systems. The rest of this section is about doing it for 50 billion documents.

Why you cannot just build a hash map. A hash map from term to a growing list works for a million documents in RAM. At our scale the postings are about 15 trillion entries, far larger than any machine's memory. Lists also have to be compressed and sorted, which is awkward to do while appending. So every large engine builds the index with external sorting: generate (term, docID, payload) records, sort them by term and docID in chunks that fit in memory, and merge the sorted chunks.

How the original Google did it. Brin and Page (1998) describe a pipeline that is still a good mental model:

  • The indexer parsed each page, turned each word into a wordID using an in-memory lexicon, and wrote the word occurrences (hits) into 64 "forward barrels". Each barrel covered a range of wordIDs, so a document's hits were spread across barrels by word.
  • A hit took just 2 bytes. "Plain" hits packed a capitalisation bit, a relative font size and a 12-bit word position. "Fancy" hits (in the URL, title, anchor text or meta tags) used a special font-size value as a flag plus a type and a shorter position.
  • The lexicon held 14 million words and fit in 256 MB of RAM. Parallel indexers shared a fixed base lexicon and logged new words to a side file, avoiding a shared mutable dictionary.
  • The sorter then took each forward barrel and re-sorted it by wordID to produce the inverted barrels, one barrel at a time, so little temporary space was needed. Multiple sorters worked on different barrels in parallel.
  • There were two sets of inverted barrels. A small "short" set held only title and anchor hits, and a full set held everything. The paper's statistics list a 4.1 GB short inverted index and a 37.2 GB full one. Queries first searched the short barrels and fell back to the full ones only if there were not enough matches. This was an early form of index tiering.

The modern batch version: MapReduce or a dataflow job. Dean and Ghemawat's MapReduce paper (OSDI 2004) reports that Google's production indexing system was rewritten as a sequence of MapReduce operations. For a document-partitioned index, the job looks like this:

  1. Map over analysed documents. For each document, compute its shard (by docID range) and emit records keyed by (shard, termID, docID) with the term frequency, positions and field flags as the value.
  2. Shuffle so that each reducer receives one shard's records, sorted by termID then docID.
  3. Reduce: stream through the sorted records, write each term's postings into compressed 128-posting blocks with skip entries and block-max scores, and write the shard's lexicon.
  4. Publish the shard files to the segment store with a manifest and checksums.
// One reducer builds one shard's segment from records sorted by (term, doc)
build_shard(records):
  writer = SegmentWriter(shard_id)
  current_term = None; block = []
  for (term, doc, tf, positions, fields) in records:     // already sorted
    if term != current_term:
      if current_term: writer.finish_term(current_term, block)
      current_term = term; block = []
    block.append(doc, tf, positions, fields)
    if len(block) == 128:
      writer.write_block(compress(block), max_score(block))
      block = []
  writer.finish_term(current_term, block)
  writer.write_lexicon(); writer.write_doc_table(); writer.seal()

Single-pass in-memory indexing (SPIMI). Lucene, Elasticsearch and most single-node indexers use a different but equivalent trick. They accumulate postings for a batch of documents in an in-memory buffer (term → growing list). When the buffer is full, they sort the terms, write a small immutable segment, and start again. Later, a background merge combines small segments into larger ones, just like compaction in an LSM tree (see Storage Engines: B-Trees vs LSM Trees). This is the natural model for the incremental and fresh tiers (Deep Dive 9).

Assigning docIDs is a design decision. DocIDs are dense integers local to a shard, and the order matters:

  • Static-rank order. Number documents so that higher-quality documents get smaller docIDs. Then every posting list is naturally ordered best-first. A query can stop early once it has enough good matches, because later documents have lower static scores (Deep Dive 4).
  • URL order. Sorting by URL puts pages from the same site next to each other. They share vocabulary, so the gaps between docIDs in a posting list become small and compress better. Research on docID reassignment (for example, Silvestri, ECIR 2007) found that simply sorting by URL gives a large part of the possible compression gain.
  • Engines often combine the two. They split documents into quality tiers (static order between tiers) and sort by URL inside each tier.

Anchor text goes to the target. When page A links to page B with the text "password hashing guide", the words belong in B's index entry, in a special anchor field. The pipeline therefore needs a join: group all inbound anchors by target docID (a big shuffle over the link graph) before or during the index build. Brin and Page reported indexing over 259 million anchors for their 24 million pages. Anchor text is one of the strongest relevance signals, because it is written by other people and summarises what the target is about. It also lets the engine index pages it could not fetch, such as images or pages blocked by robots rules (the URL can appear as a result with no snippet).

What goes in the index besides postings. Each shard ships with:

  • the lexicon (term → df, offset, max score),
  • the posting files (doc gaps, frequencies, positions, field flags),
  • a document table (docID → static score, length, language, URL hash, and packed features used by first-pass ranking),
  • per-field statistics (average field length, needed by BM25),
  • and live-docs bitsets for deletes.

A sanity check against our estimates: about 100 GB of postings per 50-million-document shard is 2 KB per document. That is consistent with about 300 unique terms per document at roughly 1.5 bytes per posting plus positions.

2. Posting lists and compression: why every byte counts#

Why compress at all? Uncompressed, a posting with a 4-byte docID and a 4-byte frequency costs 8 bytes. That makes 15 trillion postings 120 TB per index copy, and with ten replicas, more than a petabyte of RAM. Compression shrinks this 4–6x. Just as important, decoding compressed integers from memory is faster than reading uncompressed ones, because query evaluation is bound by memory bandwidth, not CPU. Compression is therefore a speed feature as well as a cost feature.

Step 1: store gaps, not docIDs. A sorted posting list such as 1000, 1003, 1010, 1100, 1101 becomes the d-gaps 1000, 3, 7, 90, 1. For a term that appears in a fraction p of documents, the average gap is about 1/p. Common terms have tiny gaps; rare terms have large gaps but short lists. Small numbers need few bits.

Step 2: encode the gaps with a variable-length integer code. The main families:

  • Variable byte (varint, VByte). Seven data bits per byte plus a continuation bit. Gaps under 128 take 1 byte; under 16,384, 2 bytes. It is simple and byte-aligned, but decoding branches on every byte.
  • Group varint. Encodes four integers with one prefix byte holding their four 2-bit lengths, then the 1–4 bytes of each. Decoding uses a lookup table on the prefix byte and avoids per-byte branches. Jeff Dean described this format in his WSDM 2009 keynote on Google's retrieval systems as considerably faster to decode than plain varint.
  • Bit packing per block (frame of reference). Take a block of 128 gaps, find the largest, and pack every gap in that many bits. If the largest gap in the block needs 7 bits, the block costs 128 × 7 bits = 112 bytes. With SIMD instructions this decodes several billion integers per second per core (Lemire and Boytsov, "Decoding billions of integers per second through vectorization", Software: Practice and Experience, 2015).
  • PForDelta (patched frame of reference). Like bit packing, but chooses a bit width that fits about 90% of the values and stores the few large ones as exceptions patched in afterwards. This means one outlier does not inflate the whole block (Zukowski, Héman, Nes and Boncz, ICDE 2006). Variants of PForDelta were widely used in web search engines.
  • Elias-Fano. Splits each value into high bits, stored in unary in a bitmap, and low bits, packed. It achieves close to the information-theoretic minimum for monotone sequences and supports fast "next value ≥ x" queries without full decoding, which is exactly what intersection needs (Vigna, "Quasi-succinct indices", WSDM 2013).
  • Roaring bitmaps. For very dense lists or filters (for example, "all documents in language = en"), a compressed bitmap is smaller and faster than a list. Roaring splits the docID space into 65,536-ID chunks and stores each chunk as an array, a bitmap or runs, whichever is smaller (Chambi, Lemire and others, 2016). Lucene and many engines use it for filters.

A worked example. Take the term passwords in one shard: 50 million documents, df = 500,000 (1%). The average gap is 100.

EncodingBits per docIDSize of this list
Raw 32-bit integers322.0 MB
Varint on gaps (most gaps under 128, some under 16,384)about 9–10about 0.6 MB
Bit packing per 128-block (most blocks need 8–9 bits)about 8–9about 0.53 MB
PForDelta (7–8 bits plus exceptions)about 7.5–8about 0.48 MB
Elias-Fano (about 2 + log2(100) ≈ 8.6 bits)about 8.6about 0.54 MB, with fast skipping

Frequencies are usually small (1–3) and pack into 2–3 bits each. Positions are delta-encoded inside each document and cost the most in total, because there is one per occurrence instead of one per document.

Blocks, skips and block-max scores. Lists are cut into blocks of 128 postings. For each block, a small header stores the last docID in the block, the byte length and the maximum score any document in the block could get for this term. This layout gives three things:

  • Skipping. To find the first docID ≥ x, binary-search or linearly scan the block headers, then decode only one block.
  • Block-level pruning. If a block's max score cannot lift any document into the current top k, skip the whole block without decoding it (Block-Max WAND, Deep Dive 4).
  • SIMD-friendly decoding. Each block decodes in one tight loop.

Keep positions separate. Most documents are rejected or scored without needing positions. Storing positions in a separate stream means the hot loop (docIDs and frequencies) stays small and cache-friendly. Positions are decoded only for the few hundred documents that survive first-pass scoring and need phrase or proximity checks.

Index in memory or on SSD? Brin and Page's 1998 engine read posting lists from disk over NFS and answered most queries in 1–10 seconds. Modern engines keep the hot index in RAM for consistent sub-10 ms leaf latency. Dean's 2009 keynote described Google moving to fully in-memory serving in the early 2000s. A middle ground is to keep the first tier (best documents) and all lexicons in RAM, and the long tail on NVMe SSDs. A random 4 KB SSD read takes about 100 µs. That is fine for the few queries that reach the tail tier, but too slow if every query had to read many blocks from SSD.

3. Sharding the index and taming tail latency#

Two ways to split an index. The general sharding trade-offs are covered in Partitioning and Sharding. For an inverted index there are two classic choices:

Document-partitioned (local index)Term-partitioned (global index)
What a shard holdsAll terms, for a subset of documentsAll documents, for a subset of terms
Machines per queryEvery shard (fan-out to all)Only the shards holding the query's terms (2–5)
Network per queryTiny: each shard returns its top kLarge: whole posting lists (or big parts) must move between machines to intersect
Load balanceEven: every shard does similar work for every querySkewed: the shard holding "the" or a trending term is a hotspot
ScoringEach shard scores fully, with local or global statisticsNeeds a coordinator to combine partial scores
UpdatesAdding a document touches one shardAdding a document touches the shard of every term in it
Failure of one shardLose a fraction of documents; results slightly worseLose some terms entirely; queries with those terms break
Used byEssentially all large web engines, Lucene, Elasticsearch, SolrMostly research (for example, pipelined query evaluation); some special-purpose systems

Document partitioning wins because it turns every query into many small, independent, local computations. It also degrades gracefully. The price is fan-out, which is managed with a serving tree, replicas, tiers and deadlines.

Global statistics. BM25 uses IDF, which depends on how many documents in the whole corpus contain a term. If each shard used its own counts, the same document would score slightly differently depending on its shard. With random or hash assignment of documents to shards, local statistics are very close to global ones for common terms. Engines nevertheless often push global df values to every shard as part of the index build, so scores are comparable when merged. Elasticsearch exposes the same choice as its dfs_query_then_fetch search type.

How big should a shard be? It is a balance:

  • Smaller shards mean a faster per-leaf search and more parallelism, but higher fan-out, more per-query overhead (RPCs, merging) and a higher chance that some leaf is slow.
  • Larger shards mean less fan-out, but each leaf takes longer and needs more memory.

A useful rule: pick the shard size so that a leaf's p99 is a small fraction (for example, a quarter) of the end-to-end budget. Then choose the replica count from QPS. With 50 million documents per shard and 10–50 ms per leaf, we get 1,000 shards and a two-level tree.

Replicas and load balancing. Each shard has R replicas. An aggregator picks one replica per shard per query. Picking by least outstanding requests, or by the power of two choices (sample two replicas and pick the less loaded), keeps load even and routes around slow machines. Replicas of one shard are spread across racks and power domains, so a rack failure removes at most one replica of each shard.

The tail-at-scale problem. Suppose each leaf has a 1% chance of being slow (more than 100 ms) on any query because of garbage collection, a background merge, a noisy neighbour or a network hiccup. A query waits for all 1,000 leaves:

  • P(no slow leaf) = 0.99^1000 ≈ 0.00004. Almost every query hits at least one slow leaf.
  • Even with 100 leaves, 1 − 0.99^100 ≈ 63% of queries hit a slow one.

Dean and Barroso made this point in "The Tail at Scale" (Communications of the ACM, 2013), using exactly this kind of fan-out arithmetic. Their remedies are now standard in search serving:

  • Hedged requests. If a leaf has not answered within, say, its p95 latency, send the same request to another replica and use whichever answers first. Their paper reports a Bigtable benchmark where hedging after 10 ms cut the 99.9th-percentile latency for a 1,000-key read from 1,800 ms to 74 ms while sending only 2% more requests.
  • Tied requests. Send to two replicas at once, each told about the other, and the first one to start the work cancels the other. This avoids the hedge delay at the cost of a little coordination.
  • Deadlines and good-enough results. Each aggregator waits until its deadline (for example, 80 ms) and then merges whatever arrived. Missing 0.5% of shards loses 0.5% of documents. That rarely changes the top 10, because the best results are usually spread across shards. The response is flagged so that it is not cached as a complete answer.
  • Micro-partitioning. Use many more shards than machines (for example, 20 per machine), so that a slow or overloaded machine can shed load by moving a few small shards rather than one big one.
  • Selective replication. Give extra replicas to shards that hold especially popular documents or are hot because of a news event.
  • Latency-induced probation. Temporarily take a consistently slow replica out of rotation and probe it with shadow traffic until it recovers.

Capacity math with hedging. Hedging at p95 sends about 5% extra requests. Taking replicas out on slowness adds a few percent more. Plan replica counts with at least 20–30% headroom over measured peak, plus one extra replica per shard for planned maintenance (rolling index updates, kernel upgrades). The planning method is in Capacity Planning and Load Testing.

Across regions. Each serving region holds complete replicas of all tiers. A query is served entirely inside one region (cross-region fan-out would add 50–150 ms). Global load balancing (anycast or DNS-based) sends users to the nearest healthy region, and a region can be drained for maintenance. Index builds happen once and are copied to every region. With a 100 TB index, an intercontinental copy at an effective 40 Gbit/s takes about 6 hours, so base builds are distributed in advance and switched on together, while the fresh tier is fed by a separate low-latency stream into every region.

4. Query processing and fast top-k retrieval#

From text to a query plan. The root turns raw input into a structured plan before any leaf sees it. A compact version of the steps:

  1. Clean the input. Remove markup and control characters and limit the length.
  2. Parse operators: quoted phrases ("store passwords"), exclusions (-bcrypt), site: and filetype: restrictions, and OR.
  3. Tokenise and normalise with exactly the same analyser used at index time (same tokeniser, lowercasing, accent folding, stemming per language). A mismatch here silently breaks recall.
  4. Fix typos with the speller (Deep Dive 10).
  5. Segment and expand. Recognise multi-word units (new york times is one concept), and add weighted synonyms and variants (store ~ storing, password ~ passcode with a lower weight).
  6. Understand intent. Is the query navigational (the user wants one site, such as github login), informational (how does tls work) or transactional (buy running shoes)? Andrei Broder's "A taxonomy of web search" (SIGIR Forum, 2002) proposed this three-way split. Also detect freshness intent (earthquake today), local intent (pizza near me) and the language.
  7. Build the boolean and weighted tree. For example: AND(store~, OR(password, passwords, passcode^0.3), safely?) where ~ means "variants" and ? means "optional, boosts if present".

AND, OR and the soft middle. A strict AND of all terms loses good pages that miss one word. A pure OR matches nearly everything. Web engines use a "soft AND": require the most important terms (rare, high-IDF terms), treat common terms as optional boosts, and score proximity. A query plan also says which tier to search first.

Term-at-a-time versus document-at-a-time. There are two ways to walk the posting lists:

  • Term-at-a-time (TAAT): process one term's whole list, adding partial scores into an accumulator per document, then the next term. It is simple, but needs memory for millions of accumulators.
  • Document-at-a-time (DAAT): open cursors on all the query's posting lists and advance them together in docID order, fully scoring one document at a time. It needs little memory, keeps a small top-k heap, and supports dynamic pruning. Modern engines use DAAT.

Pruning: score only documents that could make the top k. Most matching documents cannot beat the current 10th-best score. Pruning algorithms use upper bounds to skip them without scoring:

  • MaxScore (Turtle and Flood, 1995). Sort terms by their maximum possible score contribution. Once the top-k threshold exceeds the sum of the smallest terms' maxima, those terms become "non-essential": a document that only matches them cannot enter the top k. So the algorithm only iterates over documents in the essential lists and looks up the others.
  • WAND (Broder, Carmel, Herscovici, Soffer and Zien, "Efficient query evaluation using a two-level retrieval process", CIKM 2003). Keep the term cursors sorted by their current docID. Walk the cursors in that order, adding up their maximum scores, until the sum exceeds the threshold. The cursor where that happens is the pivot, and no document before the pivot's docID can make the top k. Advance all earlier cursors directly to the pivot docID, skipping everything in between, and fully score only the pivot.
  • Block-Max WAND (Ding and Suel, SIGIR 2011). Use the per-block maximum scores from Deep Dive 2 instead of one maximum per list. This gives much tighter bounds, so many more blocks are skipped. It is often several times faster than WAND on long queries. Lucene adopted a block-max approach (from version 8) for top-k queries.
// WAND (simplified). cursors: one per query term, each with doc(), next(), seek(d), max_score
wand_topk(cursors, k):
  heap = MinHeap(k); threshold = 0
  loop:
    sort cursors by doc()                       // smallest current docID first
    acc = 0; pivot = None
    for c in cursors:
      acc += c.max_score
      if acc > threshold: pivot = c; break
    if pivot is None or pivot.doc() == END: return heap
    d = pivot.doc()
    if cursors[0].doc() == d:                   // all earlier cursors are on d
      s = full_score(d, cursors)                // BM25F + proximity + static score
      if s > threshold:
        heap.push(d, s); threshold = heap.min() if heap.full() else 0
      for c in cursors where c.doc() == d: c.next()
    else:
      for c in cursors before pivot: c.seek(d)  // skip docs that cannot qualify

A worked example of the pruning win. The query store passwords safely in one shard has lists of 4 million (store), 500,000 (passwords) and 800,000 (safely) postings. A naive OR scores about 5 million documents. With top-10 and WAND, the threshold rises within the first few thousand documents. After that, a document must contain passwords (the highest-IDF term) plus one other term to qualify, so the cursors on store and safely mostly seek in big jumps. Typical experimental results show that WAND-style algorithms fully score only a small percentage of the candidates, and block-max variants skip most blocks without decoding them. The leaf time drops from hundreds of milliseconds to a few milliseconds.

Early termination with static ranking. If docIDs are assigned in decreasing static-score order (Deep Dive 1), the best documents come first in every list. A leaf can stop after it has seen, say, the first 20,000 matches, or once the best possible remaining score (a low static score plus the maximum text score) cannot beat the threshold. Brin and Page's 1998 searcher capped evaluation at 40,000 matching documents to bound latency, accepting slightly sub-optimal results. That is the same idea in its simplest form.

Tiered indexes. Split documents into tiers by static quality. Tier 1 is the best 10–20%, small enough to search on every query. The full tier is searched only if tier 1 returns too few good results, for example fewer than 100 matches above a score threshold, or for rare queries. Most head and torso queries are answered entirely from tier 1. That cuts the average work per query several-fold, and it is why our capacity estimate can assume that most queries touch about 200 shards, not 1,000. The risk is missing a great document that sits in a lower tier. Monitoring the fall-through rate and periodically promoting documents whose click signals rise keeps this in check.

Leaf-level caches. A leaf keeps an LRU cache of decoded posting blocks for hot terms, and an intersection cache for frequent term pairs (for example, new york). These help the torso of queries that miss the result cache but share terms.

5. Text relevance: from TF-IDF to BM25 and BM25F#

The intuition. A document is more relevant to a query when:

  1. it contains the query terms more often (term frequency),
  2. those terms are rare in the collection (inverse document frequency: matching hashing says more than matching the),
  3. it is not just long: a 50,000-word page mentions everything, so frequency should be normalised by length,
  4. and the terms appear in important places (title, headings, anchor text, URL) and close together.

TF-IDF captures points 1 and 2 with a product like tf × log(N / df). It has two flaws. Term frequency grows without limit, so repeating a word 500 times wins. And it has no principled length normalisation.

BM25 (from the Okapi system of Stephen Robertson, Steve Walker and colleagues, presented at TREC-3 in 1994, and grounded in the probabilistic relevance framework) fixes both:

score(D, Q) = sum over terms t in Q of
              IDF(t) * tf(t,D) * (k1 + 1) / ( tf(t,D) + k1 * (1 - b + b * |D| / avgdl) )
 
IDF(t) = ln( (N - df(t) + 0.5) / (df(t) + 0.5) + 1 )
 
k1 ~ 1.2 to 2.0   controls tf saturation  (k1 = 0 means presence only)
b  ~ 0.75         controls length normalisation (b = 0: none, b = 1: full)
  • Saturation. As tf grows, the term's contribution approaches a ceiling of IDF × (k1 + 1). The second occurrence helps a lot, the tenth a little, the five-hundredth almost nothing. That alone defeats crude keyword stuffing.
  • Length normalisation. A document longer than average gets a larger denominator, so it needs more occurrences to score the same. The parameter b controls how strongly.

A worked example. One shard has N = 50 million documents and an average length of avgdl = 600 tokens. The query is password hashing. password is in df = 500,000 documents and hashing in df = 50,000. Use k1 = 1.2 and b = 0.75.

  • IDF(password) = ln(49,500,000.5 / 500,000.5 + 1) = ln(100) ≈ 4.61.
  • IDF(hashing) = ln(49,950,000.5 / 50,000.5 + 1) = ln(1,000) ≈ 6.91. The rarer term is worth 50% more.

Document X is a genuine guide: 800 tokens, password 6 times, hashing 3 times.

  • Length factor: k1 × (1 − b + b × 800/600) = 1.2 × (0.25 + 1.0) = 1.5.
  • password: 6 × 2.2 / (6 + 1.5) = 1.76, times 4.61 = 8.11.
  • hashing: 3 × 2.2 / (3 + 1.5) = 1.47, times 6.91 = 10.13.
  • Total: 18.2.

Document Y is a spam page: 2,000 tokens, password 500 times, hashing once.

  • Length factor: 1.2 × (0.25 + 0.75 × 2,000/600) = 1.2 × 2.75 = 3.3.
  • password: 500 × 2.2 / 503.3 = 2.19, times 4.61 = 10.07. That is close to the ceiling of 2.2 × 4.61 = 10.1, so 500 repetitions buy almost nothing more than 20 would.
  • hashing: 1 × 2.2 / 4.3 = 0.51, times 6.91 = 3.53.
  • Total: 13.6, well below X.

BM25F: fields matter. A web document has several fields: title, headings, URL, body and anchor text (aggregated from inbound links). The naive approach of computing BM25 per field and adding the results breaks saturation, because a term in five fields gets five near-maximum scores. BM25F (Robertson, Zaragoza and Taylor, "Simple BM25 extension to multiple weighted fields", CIKM 2004) instead combines weighted term frequencies across fields first, each normalised by its own field length, and then applies saturation once. Typical relative weights put the title and anchor well above the body, for example title 3–5, anchor 2–4, URL 2, body 1, tuned on rated data.

Proximity. For multi-term queries, documents where the terms appear close together or as an exact phrase are more relevant. Brin and Page's 1998 ranker grouped the distance between matched hits into 10 proximity "bins", from an exact phrase match to "not even close". It counted hits per (hit type, proximity bin), converted the counts into count-weights that rise linearly at first and then taper off, and took a dot product with a matrix of hand-tuned type-prox-weights. They then combined this IR score with PageRank. Modern engines compute proximity features (minimum window covering all terms, number of ordered bigram matches) and feed them to the learned ranker. They use positions from the separate position stream, only for the surviving candidates.

What text relevance cannot do. BM25 needs the same words in query and document. how to keep logins safe and a page about credential storage best practices share no terms. This vocabulary mismatch is addressed by query expansion (synonyms mined from the query log and from co-clicked pages), by document expansion (for example, appending predicted queries to a document at index time) and by dense retrieval (embedding queries and documents into vectors and searching with approximate nearest neighbours). The last is covered in Vector Databases and Similarity Search. Real engines run hybrid retrieval: lexical (BM25-style) plus dense candidates, fused before ranking. That is because lexical matching remains unbeaten for rare terms, names, codes and exact phrases.

The intuition. A link from page A to page B is a vote by A's author that B is worth reading. Votes from pages that are themselves important should count more. And a page that links to 1,000 others is spreading its vote thin, so each of its links should count less. PageRank formalises this.

The random surfer model. Imagine a surfer who starts on a random page and keeps clicking a random link on the current page. With probability 1 − d at each step, they get bored and jump to a completely random page. A page's PageRank is the long-run fraction of time the surfer spends on it. Brin and Page used d = 0.85. Written for N pages:

PR(p) = (1 - d) / N  +  d * sum over pages q linking to p of  PR(q) / outdegree(q)

(The 1998 paper writes the first term as (1 − d) without dividing by N. The paper also says that the ranks form a probability distribution summing to 1, which holds only for the normalised form. The two differ only by a constant factor, so the ranking is the same.) Mathematically, the PageRank vector is the principal eigenvector of the "Google matrix", a stochastic matrix mixing the link structure with uniform random jumps. The random jump guarantees that the matrix is irreducible and aperiodic, so a unique stationary distribution exists and power iteration converges to it.

Power iteration. Start with PR = 1/N for every page and apply the formula repeatedly. The error shrinks by roughly a factor of d per iteration, so after 50 iterations it is about 0.85^50 ≈ 3 × 10⁻⁴ of the start. In practice the ranking stabilises sooner than the exact values.

A worked example. Four pages: A links to B and C. B links to C. C links to A. D links to C. D has no in-links. Take N = 4 and d = 0.85, so the jump term is (1 − 0.85)/4 = 0.0375.

IterationABCD
00.2500.2500.2500.250
10.2500.1440.5690.0375
20.5210.1440.2980.0375
converged0.3730.1960.3940.0375

For example, in iteration 1, C = 0.0375 + 0.85 × (A/2 + B/1 + D/1) = 0.0375 + 0.85 × (0.125 + 0.25 + 0.25) = 0.569. Two lessons:

  • C has the most in-links (three) and ranks highest.
  • A has only one in-link, yet ranks almost as high as C. Its single link comes from C, the most important page, which gives A its whole vote. Quality of links beats quantity.

The converged values come from solving the four linear equations directly. Note that they sum to 1.

Dangling pages. Pages with no out-links (PDFs, pages not crawled yet, dead ends) leak probability mass. The standard fix is to treat them as linking to every page, that is, redistribute their mass uniformly or by a teleport distribution on each iteration.

Computing it at web scale. With 50 billion pages and a trillion edges, each iteration is a giant sparse matrix-vector multiply. A MapReduce-style implementation does this per iteration:

  • map over each page's adjacency list, emitting PR(q)/outdegree(q) to each target;
  • reduce by target, summing the contributions and adding the jump term.

The edges stay on disk and stream through once per iteration. The rank vector (50 billion floats, 200 GB) is partitioned with the graph. Graph-processing systems such as Pregel (Malewicz and others, SIGMOD 2010), which used PageRank as a running example, keep the vertices in memory across iterations and only send messages along edges, avoiding rewriting the graph each round. Partitioning the graph by host keeps most links (which are within a site) local, cutting network traffic. This is the same trick as sharding the person servers of a social graph by location. Incremental PageRank, which re-iterates only in the region around changed links, is a research topic. In practice, full recomputation every few days is usually acceptable, because PageRank changes slowly for most pages.

Variants and descendants.

  • Topic-sensitive / personalised PageRank (Haveliwala, WWW 2002). Replace the uniform random jump with a jump to pages on a topic, or to a user's favourite pages. This gives a different importance vector per topic. Brin and Page already noted that biasing the jump to specific pages allows personalisation and makes manipulation harder.
  • HITS (Kleinberg, SODA 1998, and JACM 1999). This gives each page two scores: hub (it links to good authorities) and authority (good hubs link to it). It is computed on a query-specific subgraph, which made it more expensive at query time than PageRank's single offline computation.
  • TrustRank (Gyöngyi, Garcia-Molina and Pedersen, VLDB 2004). Start from a small, human-vetted set of trustworthy seed pages and propagate trust along links with personalised PageRank. Spam pages rarely receive links from good pages, so they get low trust.
  • Host-level and domain-level rank. Aggregate the link graph by host to get a site-authority score that is more robust than page-level rank and available immediately for new pages on known sites.

Link spam, and why PageRank is one signal among hundreds. Once links counted, people manufactured them. Link farms are networks of pages linking to each other. People also bought links and spammed comments with links. Defences:

  • rel="nofollow", introduced jointly by Google, Yahoo and MSN in 2005, so that user-generated links can be marked as non-endorsing.
  • Link-spam classifiers that use graph features (unusual reciprocal-link density, sudden link spikes, links from known spam neighbourhoods).
  • Down-weighting links from the same owner.
  • Trust propagation.

Today PageRank-like authority is one feature among hundreds. Most search engineers would say that user-behaviour and content-quality signals now carry at least as much weight. The idea of treating the web's link structure as a reputation system remains foundational.

7. Learning to rank, neural re-ranking and measuring quality#

Why learn the ranking function? Brin and Page described tuning their type-weights and proximity weights as "something of a black art", helped by a feedback tool where trusted users rated results. With hundreds of signals, hand-tuning is impossible. Learning to rank (LTR) trains a model that takes a (query, document) feature vector and outputs a score, optimised so that sorting by the score matches human judgements of relevance. The broader ML lifecycle (feature stores, training pipelines, serving) is in ML System Design and Feature Stores.

Features, in four families.

FamilyExamples
Query–document text matchBM25F overall and per field, matched-term fraction, exact phrase match, minimum covering window, title starts with the query, anchor-text match count
Document staticPageRank and host authority, content quality score, spam score, page length, URL depth, HTTPS, mobile-friendliness, page speed, freshness (age, last change)
QueryLength, intent class (navigational, informational, transactional), freshness intent, language, location intent, query frequency
BehaviouralHistorical click-through rate of this document for this query, long-click rate (the user stayed), short-click rate (the user came back fast, "pogo-sticking"), query reformulation after viewing

Labels: humans and clicks.

  • Human raters grade (query, document) pairs on a scale (for example, 0 = irrelevant to 4 = perfect), following detailed written guidelines. Google publishes its Search Quality Rater Guidelines. Ratings are accurate but expensive, so millions of judgements cover only a sliver of queries.
  • Clicks are plentiful but biased. Users click higher positions more regardless of relevance (position bias). They can only click what was shown (presentation bias). And a click may be a mistake. Click models correct for this. One is the cascade model (Craswell, Zoeter, Taylor and Ramsey, WSDM 2008), which assumes users scan down the list and click the first attractive result. Unbiased learning to rank re-weights clicks by the inverse of the estimated probability that the position was examined (Joachims, Swaminathan and Schnabel, WSDM 2017). The examination probabilities are estimated with small randomised swaps of adjacent results.

Three formulations.

  • Pointwise. Predict each document's relevance grade independently (regression or classification). This is simple, but it ignores that only the order matters.
  • Pairwise. Learn which of two documents should rank higher. RankNet (Burges and others, ICML 2005) used a neural network with a pairwise logistic loss.
  • Listwise. Optimise a list metric such as NDCG directly. LambdaRank scaled RankNet's pairwise gradients by how much swapping the pair would change NDCG. LambdaMART applied those "lambda" gradients to gradient-boosted decision trees (Burges, "From RankNet to LambdaRank to LambdaMART: An Overview", Microsoft Research technical report, 2010). An ensemble built on LambdaMART was among the winners of the 2010 Yahoo! Learning to Rank Challenge. Boosted-tree LTR models (LightGBM and XGBoost both implement LambdaMART objectives) remain the workhorse second-pass ranker in many search systems. They are fast (microseconds per document), robust to feature scaling and easy to debug.

The metric: NDCG. For a ranked list with graded relevance rel_i at position i:

DCG@k  = sum for i = 1..k of (2^rel_i - 1) / log2(i + 1)
NDCG@k = DCG@k / IDCG@k        // IDCG = DCG of the ideal ordering

Worked example: grades at positions 1–3 are (3, 0, 2). DCG = (8 − 1)/1 + 0 + (4 − 1)/2 = 7 + 1.5 = 8.5. The ideal order is (3, 2, 0): IDCG = 7 + 3/1.585 + 0 = 8.89. So NDCG@3 = 8.5/8.89 = 0.956. Moving the grade-2 document to position 2 would give a perfect 1.0. The logarithmic discount encodes the fact that users pay far more attention to the top.

Neural re-ranking. Pre-trained transformers changed ranking around 2019.

  • A cross-encoder feeds the query and the document text together into a model like BERT and outputs a relevance score. Nogueira and Cho ("Passage Re-ranking with BERT", 2019) showed large gains on the MS MARCO passage-ranking benchmark this way.
  • Google announced in October 2019 that it was using BERT models in Search, saying they would help with about one in ten English-language queries in the US.
  • Cross-encoders are expensive: one transformer forward pass per (query, document) pair. They therefore run only on the top 20–100 candidates, on accelerators, and are often distilled into smaller models.
  • A bi-encoder (two-tower) embeds the query and documents separately. Document vectors are computed at index time, so it can be used for retrieval with approximate nearest-neighbour search. It is weaker than a cross-encoder at fine ordering.

The resulting cascade puts cheap models on many documents and expensive models on few:

StageDocuments scoredModelBudget
Leaf first passMillions (with pruning)BM25F + proximity + static score10–30 ms per leaf
Second passAbout 1,000Boosted trees, about 500 features5–15 ms
Neural re-rank20–100Distilled cross-encoder10–30 ms on accelerators
Final rules10–20Diversity, freshness, vertical blending1–5 ms

Online evaluation. Offline NDCG does not guarantee that users are happier. Changes are tested live:

  • A/B tests compare metrics such as click-through on the top result, "good abandonment" (the answer was in the snippet), time to first long click, reformulation rate and sessions per user. The machinery is in the case study Design an A/B Testing and Experimentation Platform.
  • Interleaving merges two rankers' results into one list (team-draft interleaving) and counts which ranker's results get clicked. It needs far less traffic than A/B tests to detect a preference (Chapelle, Joachims, Radlinski and Yue, "Large-scale validation and analysis of interleaved search evaluation", ACM TOIS 2012).

Training–serving skew. If a feature is computed one way in training (for example, from yesterday's batch) and another at serving (from the live index), the model learns the wrong thing. The standard fix is to log the exact feature values used at serving next to each impression and train on those logs.

8. Caching search results#

Why caching works so well here. Query streams are dominated by repetition. A small set of head queries is issued millions of times a day. The torso is queries repeated moderately often. A huge tail consists of queries seen once. Google has said that about 15% of the queries it sees each day have never been searched before. Academic analyses of search logs find that a large share of distinct queries are singletons. That puts an upper bound on a result cache's hit rate (singletons can never hit), typically somewhere around 50–70% of query volume depending on the log. Even 40% is a 40% cut in fan-out load, which is thousands of servers. General caching patterns are covered in Caching Strategies: Cache-Aside, Read-Through, Write-Through, Write-Behind.

What to cache, at which layer.

LayerWhatHit costNotes
Browser and CDN edgeAutocomplete responses; non-personalised result pages for a few seconds to minutes0–30 ms from the userOnly if results are not personalised; key includes locale
Root result cacheFinal ranked list with titles and snippets, per normalised query keyAbout 1 msThe big win; sharded by key
Root or aggregator candidate cacheTop 1,000 candidates before final re-rankingA few msLets page 2 and small personalisation tweaks reuse work
Leaf posting and intersection cacheDecoded posting blocks for hot terms; intersections of frequent pairsSaves leaf CPUHelps torso queries
Document server cacheRecent snippets and document textSaves storage readsHigh hit rate for popular pages

Designing the result cache: a classic interview version. A common version of this problem asks only for the cache that sits in front of a search engine's reverse-index and document services. The design:

  1. The query API cleans and normalises the query: remove markup, break the text into terms, fix typos, normalise capitalisation, and convert it to a canonical boolean form. The normalised string (plus locale, page and safe-search setting) is the cache key, so Store Passwords, store passwords and store passwords share one entry.
  2. Look up the key. On a hit, return the cached results and mark the entry as most recently used.
  3. On a miss, call the reverse-index service to find and rank matching documents, call the document service for titles and snippets, store the result, and return it. This is the cache-aside pattern.
  4. Bound memory with LRU eviction. A hash map from key to a node in a doubly linked list gives O(1) lookup. Moving a node to the head on access, and removing the tail on eviction, are also O(1).
class LruCache<V> {
  private map = new Map<string, V>();   // JS Map keeps insertion order
  constructor(private capacity: number) {}
  get(key: string): V | undefined {
    const v = this.map.get(key);
    if (v === undefined) return undefined;
    this.map.delete(key); this.map.set(key, v);      // move to most-recent
    return v;
  }
  set(key: string, value: V): void {
    if (this.map.has(key)) this.map.delete(key);
    else if (this.map.size >= this.capacity) {
      const oldest = this.map.keys().next().value!;  // least recently used
      this.map.delete(oldest);
    }
    this.map.set(key, value);
  }
}
// Cache-aside around the engine
async function search(raw: string, locale: string, page: number) {
  const key = `${locale}|${page}|${normalise(raw)}`;
  const hit = cache.get(key); if (hit) return hit;
  const ranked = await reverseIndex.search(parse(raw), page);
  const results = await docService.snippets(ranked, raw);
  cache.set(key, results); return results;
}

(The JavaScript Map keeps insertion order, which stands in for the linked list here. In C++ or Java you would combine a hash map with an explicit doubly linked list, or use LinkedHashMap in access-order mode.)

When to update cached results. Results go stale when page contents change, when a page is removed or added, or when its rank changes (new links, a new ranking model, a new index version). There is no cheap way to know which cached queries a changed page affects. The inverse mapping from document to queries would itself be enormous, and a new page can join the results of queries it never appeared in. Practical answers:

  • TTL. The simplest and most common approach. Every entry expires after a time-to-live chosen per query class: seconds to a minute for news-sensitive or trending queries, minutes to hours for stable informational queries.
  • Version keys. Include the base index version (or a per-tier version) in the key, so a new rollout naturally misses and refills.
  • Refresh in idle time. Instead of letting popular entries expire and causing a burst of misses, re-execute them in the background when serving capacity is idle, preferring the oldest and most popular. Cambazoglu and colleagues at Yahoo ("A refreshing perspective of search engine caching", WWW 2010) studied this with very large result caches. They found that refreshing entries with spare capacity kept caches both large and fresh.
  • Event-driven invalidation for hot topics. When the fresh tier sees a burst of new documents for an entity (for example, an earthquake), invalidate or shorten the TTL for the cache keys of queries mentioning it.

Scaling the cache across machines. There are three options:

  • Each root keeps its own cache. This is simple, but hit rates are low because the same query lands on different roots, and memory is duplicated.
  • Each root keeps a full copy. This is fast to read, but memory-hungry, and every update must reach every copy.
  • Shard the cache by key. Route each key to cache node hash(key) mod n, so each query has exactly one home and hit rates are as high as a single giant cache. Plain modulo reshuffles almost every key when n changes, so use consistent hashing (see Consistent Hashing). That way adding a node moves only about 1/n of the keys. This option is the usual choice.

Static plus dynamic caching. Research on search-engine caching (for example, Fagni, Perego, Silvestri and Orlando, ACM TOIS 2006, and Baeza-Yates and colleagues, SIGIR 2007) found that splitting the cache works better than one LRU:

  • a static part, filled offline with the historically most popular queries, never evicted between refreshes;
  • a dynamic LRU part for bursty recent queries.

Pure LRU lets a flood of one-off tail queries evict the stable head. Baeza-Yates and colleagues also showed that caching posting lists can produce higher hit rates than caching results, because many different queries share terms. That is why we cache at both layers.

Avoiding stampedes. When a hot entry expires during a news spike, thousands of identical requests can miss at once and all fan out. Request coalescing (one in-flight computation per key; the others wait for it), early refresh (refresh at 80% of the TTL) and serving slightly stale entries while refreshing prevent this. These are covered in Cache Failure Modes: Stampedes, Hot Keys and Penetration.

Do not cache incomplete answers. If any shard missed its deadline, the result is partial. Serve it, but do not cache it, or cache it with a very short TTL. Otherwise a momentary hiccup is frozen into the cache.

9. Freshness and incremental indexing#

What "fresh" means. There are three useful measures:

  • Index age: for each document, how long ago the indexed copy was fetched. Average it weighted by how often documents are shown in results.
  • Staleness: the fraction of shown results whose indexed copy differs from the live page.
  • Time to searchable: the delay from a page being published or changed to it appearing in results. This is the one users notice for news.

Freshness starts at the crawler. The index cannot be fresher than its copies. The crawler estimates each page's change rate (pages change roughly like a Poisson process, so the observed changes over past visits estimate the rate) and its importance, and schedules re-crawls accordingly. Cho and Garcia-Molina studied refresh policies in the early 2000s. They showed, perhaps surprisingly, that visiting pages strictly in proportion to their change rate can give worse average freshness than a more uniform policy, because pages that change constantly are stale again almost immediately whatever you do. Sitemaps, RSS feeds and push protocols (for example, IndexNow, used by Bing and some other engines) let sites announce changes instead of waiting to be polled. Scheduling is designed in the case study Design a Web Crawler. Here we focus on what happens after fetch.

Detecting a real change. Many re-fetches return the same content with a new timestamp, advertising block or session token. The pipeline computes a content hash over the main content (after removing boilerplate such as navigation, ads and dates) and a SimHash fingerprint. If neither changed, it only updates the fetch time and skips re-indexing. This avoids reprocessing a large fraction of fetches.

From batch rebuilds to incremental processing. Early Google rebuilt the index in large batches: crawl a large set of pages, run the MapReduce pipeline over everything, ship a new index. Even with fast batches, a page changed just after a cycle started waited for the next one. Peng and Dabek's Percolator (OSDI 2010) replaced this for web indexing:

  • It stores the repository in Bigtable and adds cross-row, cross-table transactions with snapshot isolation. Each read sees a consistent snapshot at a start timestamp from a central timestamp oracle. Locks and write records are kept in extra Bigtable columns, so no separate lock server is needed.
  • Observers are code registered on columns. When a column changes, the observer runs in its own transaction and may write other columns, triggering further observers. A changed page flows through a chain: parse the document, update the canonical cluster for its duplicates, update its link records, update the inverted-index data.
  • The abstract reports that Google's indexing system stores tens of petabytes and processes billions of updates per day on thousands of machines, and that switching to Percolator-based incremental indexing cut the average age of documents in search results by 50% while processing the same number of documents per day. Google announced the resulting indexing system as Caffeine in 2010.
  • The trade-off is cost. Transactions and per-document notifications use more resources per document than a well-tuned batch job, which amortises overhead across huge sorted files. You pay for freshness with machines.

The transaction matters because the steps touch many rows: the document, its duplicate cluster, the targets of its links. Without snapshot isolation, two pages in the same duplicate cluster processed at once could each decide that the other is the canonical copy. Then neither, or both, would be indexed.

Making the serving index accept updates. A document-partitioned, compressed, immutable index is hard to edit in place. The standard answer is the segment model from Deep Dive 1:

  • New and changed documents go to the fresh tier, whose leaves hold small in-memory segments that accept appends. Each update makes the document searchable after a short refresh interval. Elasticsearch, for example, refreshes every second by default. A changed document gets a new docID in the fresh tier, and its old docID in the base tier is added to the tombstone (deleted docs) set.
  • Periodically, fresh segments are merged into larger incremental-tier segments (hourly), and those eventually into the next base build (days). Merges drop tombstoned documents and reclaim space.
  • Real-time search systems show how far this can go. Twitter's Earlybird engine (Busch and others, ICDE 2012) indexed tweets in memory and made them searchable within about 10 seconds. It used a posting format designed for concurrent single-writer, multi-reader access without locks.

Ranking fresh documents fairly. A news article that is ten minutes old has no click history, few links and no PageRank. If ranking relied only on those signals, it would never appear. Fixes:

  • Freshness intent detection. Signs that a query wants recent results include a burst in that query's volume, a burst of new documents mentioning its terms, and words like "today", "live" or "latest". When the signs are strong, the ranker boosts recency features. Some descriptions of web ranking call this "query deserves freshness".
  • Prior from the source. A new page inherits a quality prior from its host and its section (for example, the host's average quality and authority) until its own signals accumulate.
  • Fast feedback. Click signals from the first minutes are fed back through a streaming pipeline into features for the fresh tier.

Deletes and removals must be fast. A page that returns 404 or 410, gains a noindex tag, or is the subject of a legal removal must disappear quickly. Its docID goes into the tombstone set, which is tiny compared with the index (millions of entries, a few megabytes as a sorted array or a compressed bitmap) and is pushed to every leaf within seconds. Leaves filter tombstoned docIDs during retrieval. Result-cache entries containing that docID are filtered on read, or the cache is flushed for urgent legal removals. The document is physically purged at the next merge.

Consistency across shards. There is no need for a globally consistent index snapshot. Different shards may be minutes apart in freshness, and replicas of a shard may briefly differ. A user re-running a query might see slightly different results, which is acceptable. Only deletes for legal reasons need a guaranteed bound ("removed everywhere within N minutes"), and they are tracked with acknowledgements from every leaf.

10. Spelling correction and autocomplete#

Spelling correction as a noisy channel. Treat the typed query w as a corrupted version of the intended query c. Choose the c that maximises:

P(c | w)  is proportional to  P(w | c) * P(c)
  P(c)     = how likely c is as a query   (language model from query logs and web text)
  P(w | c) = how likely you type w when you mean c   (error model: edits, keyboard, phonetics)

This framing goes back to Kernighan, Church and Gale's work on spelling correction at COLING 1990. Peter Norvig's short essay "How to Write a Spelling Corrector" (2007) shows a toy version in about 20 lines of Python.

A worked example. The user typed pasword. Candidates within edit distance 1 or 2 include password (one insertion), passwords (two edits) and sword (two deletions). Suppose the language model gives P(password) = 2 × 10⁻⁴, P(passwords) = 5 × 10⁻⁵ and P(sword) = 3 × 10⁻⁵. The error model gives P(pasword | password) = 0.02 (dropping one letter of a double letter is common), P(pasword | passwords) = 0.001 and P(pasword | sword) = 0.0001. The products are 4 × 10⁻⁶ for password, 5 × 10⁻⁸ for passwords and 3 × 10⁻⁹ for sword. password wins by a factor of 80 over the runner-up.

What makes it work at web scale.

  • The query log is the dictionary. It contains names, products, slang and new words that no dictionary has. Silviu Cucerzan and Eric Brill ("Spelling correction as an iterative process that exploits the collective knowledge of web users", EMNLP 2004) showed how to learn corrections from query logs alone. They corrected step by step towards more frequent queries.
  • Reformulation pairs. When many users type X, get poor results, and within seconds type Y and click, (X → Y) is strong evidence for a correction. Mining these pairs yields a large, self-updating error model.
  • Context. form the start is a real-word error, since form is a valid word. Only a model of word sequences (bigrams, or a neural language model) sees that from the start is far more likely. Per-token correction alone cannot fix this.
  • Fast candidate generation. Comparing against a billion-entry vocabulary is too slow. Precompute deletion neighbourhoods: for each vocabulary word, index all strings obtained by deleting up to two characters. Then look up the deletions of the typed word. This is the idea behind tools like SymSpell. Alternatively, use a character n-gram index or a trie walk bounded by edit distance (Levenshtein automata, as in Lucene's fuzzy queries).
  • Do not "fix" what is right. A brand-new product name or a rare surname may look like a typo. Signals that the original is fine include enough good results for it, rising query frequency and an exact-match title in the index. In that case, show "Did you mean" at most, or nothing.
  • Decide how bold to be. With high confidence (and much better results for the correction), auto-correct and show "Showing results for X, search instead for W". With medium confidence, show "Did you mean X?". With low confidence, do nothing. The thresholds are tuned with experiments on clicks and reformulations.

Autocomplete (query suggestions). The suggest service maps a prefix to the most likely full queries:

  • Data. It is built from the query log. Count each normalised query with time decay (for example, a half-life of a few days), so new interests rise quickly. Remove queries that are rare (privacy: a query typed by only a handful of users should never be suggested), offensive, or violate policy. Add trending queries from a streaming counter so breaking news appears within minutes.
  • Structure. A trie where every node stores the precomputed top-k completions (for example, k = 10) for its prefix. A lookup is a walk of length equal to the prefix plus one read of a small list, which takes microseconds. A finite-state transducer (FST, as used by Lucene's suggesters) stores the same information far more compactly by sharing suffixes as well as prefixes.
  • Size. Keeping the top 100 million queries at about 25 bytes each is 2.5 GB of strings. Top-k lists stored as references, at 10 entries per node over a few hundred million nodes, add tens of GB. That fits in the memory of a single server, so the suggest table is fully replicated for throughput instead of sharded.
  • Ranking. Score = popularity (decayed) × locale match × freshness boost, plus light personalisation (the user's own recent queries) merged on the client or at the server.
  • Latency. Requests are debounced on the client, the CDN caches popular prefixes (short prefixes are shared by everyone), and the service itself answers in about 1 ms. The total is well under 50 ms.

The full design, including trie updates, sampling the log and handling typos inside prefixes, is the case study Design Search Autocomplete (Typeahead).

11. Duplicates, spam and page quality#

Why duplicates matter. A large fraction of fetched pages are copies or near-copies of others: http and https versions, www and bare domains, tracking parameters, printer views, mirrors, syndicated news, scraped copies and template-heavy pages that differ only in a date. Indexing all of them wastes index space and serving CPU, splits link signals across copies, and fills results with the same thing ten times.

Exact duplicates are easy. Hash the cleaned main content (for example, 128 bits of SHA-256 or a fast 128-bit hash) and group by hash.

Near duplicates need similarity-preserving fingerprints:

  • MinHash (Andrei Broder, "On the resemblance and containment of documents", 1997). Represent a document as its set of shingles (overlapping word n-grams, for example 5-grams). The Jaccard similarity of two documents is |A ∩ B| / |A ∪ B|. Apply many random hash functions and keep the minimum hash value for each. The probability that two documents share a minimum equals their Jaccard similarity, so the fraction of matching minimums estimates it. Locality-sensitive hashing bands the signatures so that similar documents collide in some band and can be found without comparing all pairs. The underlying probabilistic ideas are in Probabilistic Data Structures for Big Data.
  • SimHash (Moses Charikar, STOC 2002). Produce one 64-bit fingerprint per document. Each feature (a word or shingle, weighted) is hashed to 64 bits. For each bit position, add the feature's weight if that bit is 1 and subtract it if 0. The fingerprint bit is 1 if the total is positive. Similar documents get fingerprints that differ in only a few bits. Manku, Jain and Das Sarma ("Detecting near-duplicates for web crawling", WWW 2007) reported that for a repository of 8 billion pages, 64-bit SimHash fingerprints with a Hamming distance threshold of 3 worked well in practice.
simhash(features):                 // features: list of (token, weight)
  v = [0] * 64
  for (tok, w) in features:
    h = hash64(tok)
    for i in 0..63:
      v[i] += w if bit(h, i) == 1 else -w
  fp = 0
  for i in 0..63:
    if v[i] > 0: fp |= (1 << i)
  return fp
near_dup(a, b) = popcount(a XOR b) <= 3

Finding all fingerprints within 3 bits, fast. Comparing a new fingerprint with 50 billion others is impossible. Use the pigeonhole trick. Split the 64 bits into 4 blocks of 16. If two fingerprints differ in at most 3 bits, at least one block is identical. Build tables keyed by each block (or by permuted combinations of blocks, for better selectivity) and look up only fingerprints that share a block exactly. Then check the full Hamming distance on that small set. Manku and colleagues describe this permuted-table design and its trade-offs between the number of tables and the lookup cost.

Choosing the canonical. For each duplicate cluster, pick one canonical URL using:

  • the site's rel=canonical hint,
  • redirects,
  • HTTPS over HTTP,
  • shorter and cleaner URLs,
  • higher PageRank,
  • and the original source over syndicated copies.

Merge the signals (inbound links and anchor text) of all members into the canonical, so that link authority is not split. Keep the other URLs as aliases, so that a search for a specific URL still finds it.

Spam and low quality. Search engines are attacked constantly, because ranking well is worth money. Common tactics and defences:

  • Keyword stuffing and hidden text. Defeated partly by BM25 saturation. Also detected by classifiers on term distributions, and by rendering the page to find text that is invisible to users.
  • Cloaking. Showing the crawler different content from users. Detected by fetching the page sometimes as a normal browser from ordinary IP addresses and comparing the results.
  • Link schemes. Farms, paid links and comment spam (Deep Dive 6).
  • Scraped and mass-produced content. Pages copied from others, auto-spun or generated in bulk (including with language models) to target many queries. Duplicate detection catches copies. Quality classifiers trained on rated examples catch thin content. Site-level signals catch domains that produce large volumes of it.
  • Doorway pages and parked domains. Detected by templates and by user signals (very short clicks).
  • Soft 404s. Pages that say "not found" but return HTTP 200. Detected by content classifiers, and treated as removed.

Spam and quality scores flow into the static score. They affect tiering (spam rarely deserves tier 1) and ranking. The most extreme spam is not indexed at all. Manual review and penalty systems exist alongside the classifiers, because adversaries adapt faster than models are retrained.

12. Assembling the results page and running it reliably#

Snippets. A good snippet shows why the result matches. The document servers hold the cleaned text of each document, sharded by docID and kept mostly in memory for popular documents. For each of the final ten results:

  1. Fetch the document's text (or a pre-split list of sentences and a compact positional map).
  2. Find candidate windows of about 150–300 characters that contain as many distinct query terms as possible, close together, preferring sentence boundaries and the main content over boilerplate.
  3. Prefer the page's meta description if it contains the query terms and reads well.
  4. Bold the matched terms (and their variants), and truncate cleanly.

Snippet generation is query-dependent, so it cannot be fully precomputed. Ten lookups in parallel with in-memory text take a few milliseconds. Research on fast snippet generation (for example, Turpin, Tsegay, Hawking and Williams, SIGIR 2007) focused on compact document representations so this step stays cheap. Engines also generate titles. They usually use the HTML title, but sometimes rewrite it from headings or anchor text when the title is missing, generic ("Home") or stuffed.

Verticals and blending. The results page is often more than ten links: news results, images, videos, maps for local queries, a knowledge panel, and ads. Each comes from its own system with its own index. The root calls them in parallel with the web search, each with a deadline. A blending model decides whether and where each vertical's block appears, based on query intent (for example, earthquake → a news block at the top) and on the predicted usefulness of each block. A vertical that misses its deadline is simply left out.

Rendering fast. Send the page header, styles and search box immediately (flushing the first bytes of HTML while the query is still running). Then stream the results. Keep the results page light, since it is loaded billions of times a day. Prefetch the top result's resources only when the probability of a click is high, because prefetching costs the result site's bandwidth too. Client-side considerations are in Client, Mobile and Frontend Considerations.

Graceful degradation under load. Overload is never all-or-nothing. In order of increasing severity, shed work:

  1. Skip the neural re-ranker (the boosted-tree ranking alone is still good).
  2. Drop optional verticals.
  3. Search tier 1 only.
  4. Lengthen cache TTLs and serve stale entries.
  5. Reduce the fan-out deadline and accept more partial results.
  6. Rate-limit abusive clients and scrapers at the front end.

Each step is a pre-built switch, tested regularly, not an emergency code change. Patterns for this are in Resilience Patterns: Timeouts, Retries and Circuit Breakers and Designing for High Availability.

Regions and failure domains. Run three or more serving regions, each with complete replicas of every tier, the result cache, the suggest service and the document servers. Global load balancing routes users to the nearest healthy region. Losing a region shifts its traffic to others, so each region needs spare capacity (with three regions, at least 50% headroom to absorb one region's loss). Within a region, spread each shard's replicas across racks and power domains. The indexing pipeline is a separate system. It can stop for hours while serving continues on the last good index, which is one of the strongest reliability properties of this architecture.

What to watch. Useful dashboards (see Observability: Logs, Metrics and Traces) include:

  • p50, p99 and p99.9 latency per tier;
  • the rate of partial results (shards missing deadlines);
  • per-shard latency outliers;
  • result-cache hit rate and TTL expiry spikes;
  • tier-1 fall-through rate;
  • index age and the delay from fetch to searchable;
  • the rates of spelling corrections and zero-result queries;
  • and quality metrics such as the click-through rate on the top result, abandonment and reformulation.

A sudden rise in zero-result queries often signals a broken analyser or a bad index push before anything else does.

Abuse and privacy. Scrapers and bots can be a significant share of traffic. Rate limiting by IP address and client signature, bot detection and challenges protect capacity (see Rate Limiting and Throttling). Query logs are highly sensitive personal data. Keep them only as long as needed, anonymise or aggregate them for training, enforce strict access control, and apply minimum-count thresholds before any query becomes a public suggestion.

Bottlenecks and Failure Modes#

Failure / hotspotImpactMitigation
One slow leaf out of 1,000 (GC pause, merge, noisy neighbour)Every query waits for it; p99 explodesHedged requests after the p95 time, deadlines with partial results, latency-based replica probation, micro-partitions
Shard replica group lost (rack or power failure)Some documents missing, or capacity dropSpread replicas across failure domains; aggregators skip missing shards and flag partial; spare replicas reloaded from the segment store
News spike for one query (thousands of QPS on a new topic)Cache miss storm, fresh-tier hotspotRequest coalescing, short TTL with stale-while-revalidate, extra fresh-tier replicas, pre-warming trending queries
Bad index push (broken analyser, corrupt segment, bad ranking model)Wrong or empty results everywhereCanary rollout per replica group, quality gates (zero-result rate, NDCG on a probe set), checksums, instant rollback to the previous version kept on disk
Common-term queries (the who, to be or not to be)Huge posting lists, slow leavesPhrase and bigram indexes for frequent pairs, block-max pruning, never drop stopwords entirely
Result cache node failureHit rate drops for its key range; fan-out load jumpsConsistent hashing with replicas, gradual refill, capacity headroom for cache loss
Fresh tier falls behind (indexing backlog)News results minutes to hours lateAutoscale pipeline workers, prioritise by freshness class, drop low-value updates first, alert on time to searchable
Link spam or content farms gaming rankingLow-quality results for valuable queriesSpam classifiers, TrustRank-style propagation, site-level quality, nofollow, manual actions, retrained models
Duplicate explosion (infinite URL spaces, session IDs)Index bloat, wasted crawl and servingURL normalisation rules, SimHash clustering, per-host caps, crawler trap detection
Training–serving skew in the rankerModel looks good offline, hurts onlineLog served features, train on logs, interleaving and A/B before ship, shadow scoring
Cross-region index copy lagRegions serve different index versionsPre-stage base builds everywhere before switching; separate low-latency stream for the fresh tier; version in cache keys
Scrapers and botsCapacity drained, skewed logsRate limiting, bot detection, challenges, exclude bot traffic from learning signals

What Interviewers Expect#

Mid-level. Explain the two halves clearly: an offline pipeline from crawled pages to an inverted index, and an online path from a query to ranked results. Describe what an inverted index is (term to posting list of docIDs) and why posting lists are sorted, and walk through answering a two-word query by intersecting lists. Know that results are ranked by text relevance (TF-IDF or BM25) combined with page importance (PageRank) and that the index is split into shards with replicas. Add a result cache in front with TTLs and an LRU policy, and explain the cache key. Mention spelling suggestions and autocomplete as separate services built from query logs. The smaller "site search" version (a SQL database, then full-text indexes, then Elasticsearch kept in sync by change data capture, then Redis or CDN caching) is a common mid-level answer and should be explained well.

Senior. Size the system with numbers: documents, postings, bytes per posting after compression, shard size, replicas from QPS, and the fan-out arithmetic. Justify document partitioning over term partitioning. Explain the serving tree with aggregators and deadlines, and how tail latency is handled with hedged requests and partial results. Describe BM25 (saturation, length normalisation, field weights) and PageRank (random surfer, damping, power iteration) in enough detail to compute a small example. Explain the ranking cascade from cheap first-pass scoring to a learned second-pass model. Cover posting-list compression (gaps, varint or block bit-packing, skips) and top-k pruning with WAND. Design freshness with tiers (base, incremental, real-time) and tombstones. Design the result cache with sharding, consistent hashing, static and dynamic parts, and invalidation by TTL and index version.

Staff and above. Reason about the system as a cost-quality-freshness trade-off: how docID ordering, tiering and early termination trade a little recall for large savings, and how to measure the cost of that (fall-through rate, quality on tail queries). Discuss index build and rollout as a release process with quality gates and rollback. Discuss incremental indexing with transactional processing (Percolator) versus batch, and its resource cost. Address learning to rank end to end: labels from raters and bias-corrected clicks, LambdaMART, neural re-rankers within latency budgets, interleaving, and training–serving skew. Cover adversarial robustness (spam, cloaking, link schemes, AI-generated content), privacy of query logs, multi-region operation, degradation ladders and how the system evolves towards hybrid lexical-plus-dense retrieval and generated answers without losing the inverted index's strengths.

Deep Dive: Sizing every tierShow
TierSizing logicResult
Front ends100,000 peak QPS; about 2,000 QPS per front-end server for TLS, routing and renderingAbout 50 servers per region plus headroom, so 100–150 across 3 regions
Root serversQuery parsing, speller call, cache lookup, final merge and re-rank; about 500 QPS per server100,000 ÷ 3 regions ÷ 500 ≈ 70 per region, plus about 30% headroom, so about 90 per region
Result cache100 million entries per region at about 4 KB (10 results with snippets and metadata)About 400 GB per region; 20–40 cache nodes with replication
SpellerCalled on every query that misses the cache, roughly 2–5 ms of CPUA few dozen servers per region, models in memory (a few GB each)
AggregatorsEach handles fan-out to about 33 leaves plus second-pass ranking of about 1,000 candidatesHundreds per region
Leaves (base tiers)1,000 shards × 9–12 replicas (Capacity Estimation), less with tieringAbout 9,000–12,000 per region with 256–512 GB RAM each
Fresh-tier leavesAbout 1 billion documents in memory across 100 shards, 9 replicas eachAbout 900 per region
Document servers100 TB of clean text, about 20% hot in RAM, the rest on SSDAbout 200–400 per region
Suggest service400,000–600,000 peak QPS, mostly absorbed by the CDN; about 50,000 QPS per server from memory10–20 per region behind the CDN
Indexing pipeline58,000 pages per second at about 50 ms of CPU eachAbout 3,000 cores, so about 100 servers, plus GPUs for embeddings
Index buildersRebuild 100 TB of index in about a day from forward recordsA few thousand cores of batch capacity during builds
Link analysis1 trillion edges, 40–50 iterationsHundreds of servers for a few hours every few days
Segment storeSeveral index versions × 100 TB, plus raw pages and forward dataSeveral petabytes on a distributed file system

Bandwidth inside a region. At 50,000 index-path QPS per region with about 300 shards touched on average (after tiering), that is 15 million leaf RPCs per second. At about 1.6 KB per response, that is about 24 GB/s (roughly 200 Gbit/s) of response traffic, spread across thousands of machines. That is fine for a modern data-centre fabric, but it is why candidate lists are kept small and features are packed.

RAM in total. 10,000 leaves × 384 GB ≈ 3.8 PB of RAM per region for the base index. This is the dominant hardware cost, and the reason compression ratios and tiering decisions translate directly into millions of dollars.

Deep Dive: Real-world systems comparedShow
SystemScale and eraIndex and servingWhat to learn from it
Google prototype (Brin and Page, 1998)24 million pages; 147.8 GB fetched, 53.5 GB compressed repository, 37.2 GB full inverted index64 barrels by wordID range; short (title and anchor) and full inverted barrels; disk over NFS; most queries took 1–10 sThe whole pipeline shape (URL server, crawlers, repository, indexer, sorter, lexicon, searcher), compact 2-byte hits, anchor text and PageRank as signals, early termination at 40,000 matches
Google cluster architecture (Barroso, Dean and Hölzle, IEEE Micro 2003)Billions of pages, thousands of commodity PCs per clusterIndex split into shards, each served by a pool of replicated machines; separate document servers for snippets; load balancing across replicated clustersCommodity hardware with software fault tolerance; throughput through replication; price-performance over peak single-machine speed
Google incremental indexing (Percolator and Caffeine, 2010)Tens of petabytes; billions of updates per dayTransactions and observers on Bigtable instead of batch MapReduceFreshness via incremental processing: 50% lower average document age, at higher cost per document
Apache Lucene, Elasticsearch, OpenSearch, SolrFrom one node to clusters of hundreds of nodes, billions of documentsImmutable segments with merges; document-partitioned shards with replicas; near-real-time refresh (1 s default in Elasticsearch); block-max WAND in LuceneThe open-source reference implementation of nearly every idea here; ideal for site and app search, not for a whole-web engine
Vespa (open-sourced by Yahoo in 2017)Large-scale serving for search and recommendationContent nodes hold documents and indexes; stateless containers fan out and merge; multi-phase ranking expressed in the schemaFirst-class multi-phase ranking with ML models next to the data, and real-time writes
Twitter Earlybird (ICDE 2012)Real-time tweet searchIn-memory, append-optimised posting lists with a single writer and lock-free readers; tweets searchable in about 10 secondsHow to build a real-time tier
Common CrawlAn open, regularly published crawl of billions of pagesRaw archives (WARC files) plus extracted text and metadata, published for anyone to processWhat the raw input looks like at web scale, and a dataset for building and testing indexing pipelines

Hedging. The internals of today's commercial engines are mostly not public. Statements about their current architecture beyond the published papers and official announcements should be treated as informed inference, not fact.

Deep Dive: A 45-minute interview planShow
MinutesWhat to do
0–5Clarify the scope: general web search or site search? Index size, QPS, latency, freshness, personalisation, verticals. Agree that the crawler is a given.
5–10Requirements and estimates: 50 billion documents, about 100 TB of index, 100,000 QPS at peak, p99 under 400 ms. Derive the shard count and the leaf count roughly.
10–20High-level design: the offline pipeline (parse, dedup, analyse, link graph, index build) and the online tree (root, cache, aggregators, leaves, document servers). Draw both and the index between them.
20–28Deep dive on the index: inverted index structure, compression and skips, document partitioning versus term partitioning, the serving tree, tail latency and hedging.
28–36Deep dive on ranking: BM25 with field weights, PageRank intuition and power iteration, the ranking cascade with learning to rank and a neural re-ranker, top-k pruning.
36–41Freshness and caching: tiers (base, incremental, real-time), tombstones, the result cache (key, TTL, LRU, sharding with consistent hashing, static plus dynamic).
41–45Spelling and autocomplete in one minute each; failure modes and degradation; what you would measure (NDCG, clicks, latency, index age).

Common traps:

  • spending 20 minutes on the crawler;
  • proposing term-partitioned shards without discussing the network cost;
  • treating PageRank as the ranking;
  • forgetting that every query hits every shard;
  • caching partial results;
  • ignoring deletes.
Deep Dive: Follow-up questions and strong answersShow

"Why not just use Elasticsearch?" For site or app search up to billions of documents, you should. For whole-web search, the core ideas are the same (Lucene's segments, BM25, block-max WAND), but the scale changes the design. The index is about 100 TB per copy, replicated many times. There are tens of thousands of leaves, and custom tiering and docID ordering are needed. Hand-tuned compression and memory layout pay for whole data centres, and the ranking stack is a multi-stage ML system. Engines at this scale build custom serving stacks.

"How do you handle a query like the who or to be or not to be?" Never discard stopwords entirely. Index frequent phrases or bigrams (or use positional intersection with skips) so the phrase can be matched directly. Rank by phrase match and by anchor text (the band's site has many links with anchor text "The Who").

"How would you add semantic search?" Compute dense embeddings for documents at index time and store them in per-shard approximate-nearest-neighbour indexes next to the inverted index. At query time, run lexical and dense retrieval in parallel, then fuse the candidates, for example with reciprocal rank fusion or a learned merger, before the learned ranker. Keep lexical retrieval for exact names, codes and rare terms.

"How do you know a ranking change is better?" Run it through offline NDCG on rated sets per query class, then interleaving for a quick, sensitive online signal, then an A/B test with guardrail metrics (latency, abandonment, revenue if ads are affected). Look at side-by-side rater comparisons for the queries that changed most.

"A page was deleted for legal reasons. How fast is it gone?" The docID goes into the tombstone set, which is replicated to every leaf within seconds to minutes. Leaves filter it during retrieval, and cached pages are filtered on read or purged. Track acknowledgements from every leaf to prove completion. The document is physically removed at the next merge.

"What happens if the indexing pipeline stops for a day?" Serving continues on the last good index. Results become a day staler, and news suffers most. The fresh tier should have its own simpler pipeline with priority, so it can keep going when the big batch path is stuck.

"Why sort docIDs by quality?" So that the best documents appear first in every posting list. Early termination and tiering then find good results after scanning only a prefix. That cuts leaf CPU, at a small risk of missing a lower-ranked document that would have scored highly on text.

"How do you personalise without killing the cache?" Cache the non-personalised candidate list (the top 1,000 for the query and locale) and apply cheap personalisation (re-ranking by the user's language, location or recent history) on top, at the root. The expensive fan-out is shared; only the final re-rank is per user.

"How do you shard the result cache, and what happens when you add a node?" Use consistent hashing on the normalised key. Adding a node moves about 1/n of the keys. They miss once and refill, so plan for the temporary extra fan-out load.

Deep Dive: When you are not Google, site and app search step by stepShow

Most real search problems are not the whole web. They are "search the events, products, posts or documents in our own database". The same ideas apply at a smaller scale, and the usual progression is a good interview answer in its own right.

Step 0: the slow query. A first version often does this:

SELECT * FROM events
WHERE name LIKE '%Taylor%' OR description LIKE '%Taylor%';

A leading wildcard means no B-tree index can help, so every query scans the table. At a million rows, this already takes hundreds of milliseconds and burns database CPU.

Step 1: ordinary indexes and query tuning.

  • Index the columns used for exact or prefix filtering, such as date, venue, category and the start of a name.
  • Use EXPLAIN to read the query plan, select only the columns you need instead of SELECT *, and add LIMIT.
  • Sometimes rewriting an OR across columns into a UNION of two indexed queries helps.

This fixes filters and sorting, but not "find the word Taylor anywhere in the text". Each index also costs storage and slows writes, so index only what queries use. See Database Indexing.

Step 2: full-text indexes inside the database. PostgreSQL has built-in full-text search: a tsvector column (the analysed tokens of the text) with a GIN index, which is an inverted index inside the database, queried with tsquery. MySQL has FULLTEXT indexes. Neither is built on Lucene, but both turn a word search into an index lookup:

ALTER TABLE events ADD COLUMN search tsvector
  GENERATED ALWAYS AS (to_tsvector('english', name || ' ' || coalesce(description, ''))) STORED;
CREATE INDEX events_search_idx ON events USING GIN (search);
SELECT id, name, ts_rank(search, q) AS rank
FROM events, plainto_tsquery('english', 'taylor swift') q
WHERE search @@ q ORDER BY rank DESC LIMIT 20;

This is often enough for millions of rows and modest QPS. The costs are more storage, slower writes, limited relevance tuning, weak typo tolerance, and search load competing with transactional load on the same database.

Step 3: a dedicated search engine. Move search to Elasticsearch or OpenSearch (or Solr, Typesense or Meilisearch). You get inverted indexes with BM25, analysers per language, fuzzy matching (edit-distance queries that find "Taylor Swift" from "Tayler Swift"), facets, highlighting and horizontal scaling. The database stays the source of truth, and the search index is a derived, rebuildable copy:

  • Keep it in sync with change data capture. Stream inserts, updates and deletes from the database's write-ahead log (for example, with Debezium into Kafka) to an indexer that writes to Elasticsearch, as described in Change Data Capture and the Outbox Pattern.
  • Expect seconds of lag. Design the user experience accordingly. For example, after creating an event, show it from the database rather than from search.
  • The costs are another cluster to run and pay for, and the work of keeping the two consistent: reconciliation jobs, and full re-index from the database when mappings change.

Step 4: cache repeated searches. Put Redis or Memcached in front of the search API:

  • Build the key from every parameter that changes the result, for example search:keyword=taylor swift&start=2026-01-01&end=2026-12-31&page=1.
  • Choose a TTL that matches how fast results change (minutes for event listings, longer for stable catalogues).
  • Invalidation is the hard part, because you cannot easily tell which cached searches a new or changed item affects. That is even harder with fuzzy matching, where a new "Taylor" event should appear for "Tayler". Use TTLs plus tag-based invalidation: tag each cached entry with, for example, the categories or performers it involves, and purge by tag when those change.

Step 5: engine-level and edge caching. Elasticsearch has a node query cache (it caches the results of filter clauses at the shard level) and a shard request cache (it caches whole responses for a shard, especially useful for aggregation-heavy queries such as facets). These help repeated queries automatically. For results that are not personalised, a CDN (for example, CloudFront or Fastly) can cache search API responses close to users for a short TTL, removing round trips entirely. Do not do this for personalised results. Edge caches also need a purge path when underlying data changes, for example when a new event is announced.

This ladder (database scan → indexes → database full-text → search engine with CDC → result cache → engine and edge caches) is the "small world" version of the web search design. The web engine simply replaces each step with a custom, sharded, tiered component.

Deep Dive: Adding generated answers on top of searchShow

Modern engines increasingly show a generated summary above the links, written by a large language model from the retrieved pages. Architecturally, this is retrieval-augmented generation with the web index as the retriever. The patterns are in Designing LLM and AI-Powered Systems.

  • Retrieval is unchanged and still decisive. The model can only summarise what the index returns. Ranking quality, freshness and spam defence matter even more, because a spam page in the context window can become a confident wrong answer.
  • Passage-level retrieval. Answers need passages, not whole pages. Index documents as passages (for example, 100–300 tokens each) with their own embeddings, or extract passages from the top documents at query time on the document servers.
  • Latency and cost. Generating 200 tokens on a large model takes hundreds of milliseconds to seconds, and costs far more than the whole classic query. Engines therefore generate only for query classes where an answer helps (complex informational queries, not navigational ones). They stream the answer while the links render, and they cache generated answers for popular queries with short TTLs.
  • Attribution and safety. Cite the source pages inline. Check that each claim is supported by a retrieved passage, and suppress generation for sensitive topics (medical, financial, legal) or low-confidence retrieval.
  • Evaluation. Ratings must judge factual accuracy and attribution as well as relevance, which is much more expensive than judging ranked links.

The classic inverted-index engine does not go away. It remains the cheapest, most precise and most controllable way to find candidate documents among hundreds of billions. Generation is a new final stage on top.

Key Takeaways#

  • A web search engine is two systems meeting at the index: an offline pipeline (parse, canonicalise, deduplicate, analyse, link analysis, index build) and an online serving tree (root, cache, aggregators, leaves, document servers).
  • The inverted index maps terms to sorted, compressed posting lists. It is built with external sorting (barrels, MapReduce or SPIMI segments) and stored as gaps encoded with block bit-packing, PForDelta or Elias-Fano, with skips and block-max scores.
  • Document partitioning wins at web scale. Every shard answers every query locally and returns a tiny top-k list. The price is fan-out, so tail latency is the central serving problem. Handle it with replicas, hedged requests, deadlines and partial results.
  • Ranking is a cascade: BM25F, proximity and a static score (PageRank, quality, spam) at the leaves, with WAND-style pruning; then learning to rank (LambdaMART over hundreds of features) on about 1,000 candidates; then a neural re-ranker on the top few dozen.
  • BM25 saturates term frequency and normalises by length, so keyword stuffing does not pay. PageRank is the stationary distribution of a random surfer with damping 0.85, computed by power iteration over the link graph. It is one signal among many, not the ranking.
  • Freshness comes from tiers (base, incremental, real-time), tombstones for instant deletes, and incremental processing. Percolator-based indexing cut the average document age in Google's results by 50%, at a higher cost per document.
  • Caching is the cheapest capacity win. Use a result cache keyed by the normalised query with TTLs, LRU eviction, consistent-hash sharding and static plus dynamic parts; posting-list caches on leaves; and CDN caching for non-personalised responses. Never cache partial results.
  • Spelling correction is a noisy-channel model learned from query logs and reformulations. Autocomplete is a precomputed prefix-to-top-k table (a trie or FST) served from memory and the edge.
  • Measure quality with NDCG on rated sets, bias-corrected clicks, interleaving and A/B tests. Log served features to avoid training–serving skew.
  • For site or app search, follow the smaller ladder: indexes, then database full-text search, then Elasticsearch synced by CDC, then Redis and edge caching. It uses the same ideas at a size one team can run.