SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
  • Design Ride Sharing (Uber/Lyft)
  • Design a Payment System
  • Design Ticket / Hotel Booking
  • Design a Search Engine
  • Design Google Maps
  • Design a Collaborative Editor (Google Docs)
  • Design a Metrics and Monitoring System
  • Design a Distributed Message Queue (Kafka-like)
  • Design an E-commerce System (Amazon)
  • Design a Content Recommendation System (YouTube/Netflix)
System Design/Case Studies/Hard
Interview case study

Design a Search Engine

Crawl, index and rank billions of pages, and answer a query in milliseconds.

⏱ 38 min readHard case studyAdvanced26 cross-questionsHas visualizer
Prompt60-sec answer45-min plan1 Clarify2 Estimate3 API + Data4 Design5 Deep dives6 Scale7 Wrap upCross-questionsVariationsScoringMistakesCheat-sheet

StartThe prompt and what is really being tested

The interviewer says

“Design a web search engine, like Google. Someone types a few words, and we show the ten best pages in a fraction of a second.”

It is short on purpose. Your first job is to make it specific.

What they checkWhy it matters
Splitting offline from onlineBuilding the index (slow, huge, batch) and answering a query (fast, small, live) are two different systems. Strong candidates draw the line first and say what crosses it.
Sharding an indexThe index is far too big for one machine. Document partitioning versus term partitioning, and the cost of asking every shard, is the heart of the question.
Tail latencyA query that waits for 1,000 shards is as slow as the slowest one. This is the follow-up that separates senior candidates from the rest.
Ranking in stagesYou cannot run an expensive model on billions of pages. Cheap retrieval first, expensive reranking on a few hundred candidates second.
Freshness, quality and honestyNews must appear in minutes, spam must be demoted, and every shortcut has a cost. The interviewer wants the costs said out loud.

TL;DRThe whole design in 60 seconds

A search engine is two systems joined by an index. Offline, a pipeline crawls pages, cleans them, scores them and builds an inverted index cut into about 1,000 shards, each held by many replicas. Online, a query is understood, sent to every shard, and the best few hundred hits are merged, reranked and shown with snippets.

  • Scale (illustrative): 50 billion pages, 100,000 queries a second at peak, an answer in about 200 ms, 99% of the time.
  • Index: document-partitioned. Each shard holds about 50 million documents and the full word lists for them. Every query goes to every shard.
  • Serving: a tree of aggregators fans the query out, each shard returns its local top 20, and the root merges them. Then a second-stage ranker reorders the top few hundred.
  • Tail latency: with 1,000 shards, a 1% chance of one slow call becomes a near certainty that a query hits one. Fix it with backup requests, a deadline that returns partial results, and caching.
  • Ranking: text match (BM25), link importance (PageRank), freshness and quality, in two stages: cheap retrieval, then a learned reranker.
  • Freshness: immutable segments, a small real-time tier for news, and rolling index swaps with no downtime.
  • Not here: crawling is in "Design a Web Crawler" and typeahead is in "Design Search Autocomplete". This case study is about indexing, sharded serving and ranking.
💡How to use this page
Read the 60-second answer first. Then work through steps 1 to 7 in order, and try each step yourself before reading the model answer. Finish with the cross-questions: say your answer out loud, then open the model one.

PlanA 45-minute plan

4
3
4
8
16
7
3
Minutes per step (total 45). A guide, not a rule: move time to the part the interviewer cares about.
StepMinutesWhat to get done
1. Clarify4Web scale or one site, how fresh, how fast, what the results page looks like, what is out of scope.
2. Estimate3Corpus size, index size, shard count, queries a second, and the fan-out cost of asking every shard.
3. API and data4One search call, the shard RPC, and the forward index, inverted index and per-page signals.
4. High-level design8Offline pipeline, online serving tree, and where the index is stored and swapped.
5. Deep dives16Index partitioning, tail latency, ranking, freshness, and quality and spam.
6. Scale and failures7Shard loss, bad index builds, hot queries, cost, and multi-region.
7. Wrap up3Recap, trade-offs, what you would build first and what you would leave for later.

Step 1Clarify requirementsabout 4 min

🤔
Pause. Try it yourself first
You have 60 seconds. Write five questions that change the design. Hint: think about the size of the corpus, how fresh results must be, what a result contains, how many queries, and what you are NOT building.

Questions to ask, and why

AskWhy you ask itTypical answerHow it changes the design
Is this web-scale search over billions of pages, or search inside one website?One site fits on a few machines and a single Elasticsearch cluster. The web does not.Web scale: about 50 billion pages.The index must be sharded across thousands of machines. This is the whole problem.
What does a result page show?Ten links with a title and a snippet needs the text of the page at query time, not just the index.Ten results, each with a title, a link and a snippet of text around the matching words.We need a document store for snippets, separate from the index.
How many queries a second, and how fast must the answer be?The query rate decides the number of replicas. The latency target decides how we handle slow shards.About 100,000 queries a second at peak. Under 200 ms typically, 99% under 500 ms.Fan-out to every shard at that rate is huge, so we need replicas, caching and tail-latency controls.
How fresh must results be?A new news story in 5 minutes needs a streaming path. A new blog post in a week does not.Most pages within days. News and trending topics within minutes.Two index tiers: a large main index rebuilt in batches, and a small real-time tier for fresh content.
How good must ranking be, and who judges it?Ranking is the product. It decides whether to run an expensive model, and how.Very good. Relevance is measured by human raters and click data.Two-stage ranking, and an evaluation and A/B testing setup.
Do we need to handle many languages?Languages change tokenizing, stemming and which shards can answer.Yes, but start with one language and design for more.A language field per document, and per-language analysis in the index and the query.
Is personalization in scope?Personalization needs user data and a different cache strategy, since results are no longer shared.No. Use location and language only.Result caching stays simple: the same query gives the same page for everyone nearby.
What about spam, adult content and legal removals?These are part of the product, and they shape the index and the ranker.Yes: demote spam, support safe search, and honour removal requests.Quality and spam scores per page, a removal list applied at serving time.
Do we build the crawler here?Crawling is a large problem of its own.No. Assume a crawler delivers pages. We build indexing, serving and ranking.We start from a stream of fetched pages and link data. See Design a Web Crawler.
What availability do we need, and is a slightly incomplete answer acceptable?If partial results are allowed, a slow or dead shard does not have to fail the whole query.99.99% available. A good answer from 99% of the index beats no answer.Per-shard deadlines and partial results are allowed, but must be measured.

Write the scope on the board

Functional (must do)
  • •Given a text query, return the ten most relevant pages, with title, URL and snippet
  • •Support further pages of results, and common query features (phrases, language, region)
  • •Include new and changed pages within a bounded delay (minutes for news, days for the rest)
  • •Demote spam and low-quality pages, and support safe search and legal removals
  • •Correct simple spelling mistakes and rewrite queries (a small first version)
Non-functional (how well)
  • •Latency: about 200 ms typical, under 500 ms at p99
  • •Scale: 50 billion pages, 100,000 queries a second at peak
  • •Availability: 99.99%, and a graceful partial answer is better than an error
  • •Freshness: minutes for news, days for most pages
  • •Relevance: measured with raters, click data and A/B tests
Out of scope (say it)
  • •Crawling and fetching pages (covered in Design a Web Crawler)
  • •Typeahead suggestions (covered in Design Search Autocomplete)
  • •Personalised results, ads, maps and other special result blocks
  • •Semantic (vector) search, kept as a later second retrieval path
🎤
Say it out loud
“Let me confirm the scope. We build web search over about 50 billion pages: an indexing pipeline, a sharded serving system, and ranking. Ten results per page with titles and snippets, around 100,000 queries a second at peak, a typical answer in 200 milliseconds and the slow end under 500. Most pages can be days old, news must appear in minutes. A good answer from most of the index is better than no answer, so partial results are allowed. I am leaving out crawling, typeahead, personalization and ads. Does that sound right?”

Step 2Estimate the scaleabout 3 min

🤔
Pause. Try it yourself first
On paper: how big is the index, how many shards does it need, and what does it cost to ask every shard for every query? Which number is the scary one?

Assumptions (say them first)

AssumptionValue
Pages in the index50 billion
Raw page size (HTML), as crawled100 KB
Extracted text per page10 KB
Index size compared with extracted text20% (after compression)
Shard size100 GB of index, about 50 million documents
Replicas per shard10 (for throughput and availability)
Queries at peak100,000 per second
Share of queries answered from the result cache40%
CPU time per shard call (local top 20)3 ms
Cores per machine32 (so about 10,000 shard calls a second at full load)
Pages that change and are re-indexed each day1% (500 million)

The arithmetic, line by line

WhatMathsResult
Raw crawled data50B × 100 KB5 PB
Extracted text50B × 10 KB500 TB
Index size (one copy)500 TB × 20%100 TB
Shards100 TB ÷ 100 GB1,000 shards, about 50M documents each
Machines for the index1,000 shards × 10 replicas10,000 machines, about 1 PB of index in total
Queries that reach the shards100,000 × (1 − 40%)60,000 per second
Shard calls per second (fan-out to all shards)60,000 × 1,00060 million per second (100 million with no cache)
Load per machine60M ÷ 10,000 machines = 6,000 calls/s; capacity 32 ÷ 3 ms ≈ 10,700 calls/sabout 56% busy at peak (94% with no cache)
Pages re-indexed per day50B × 1%; ÷ 86,400 s500 million a day, about 5,800 per second
Text to process per day500M × 10 KB5 TB of new text a day
Link graph for PageRank50B pages × 50 links each2.5 trillion links, about 40 TB at 16 bytes a link
Full rebuild of the index, at 10 GB/s500 TB of text ÷ 10 GB/s50,000 s, about 14 hours
What the numbers tell us about the design
  • •The fan-out is the cost: every query touches all 1,000 shards, so 60,000 queries a second becomes 60 million shard calls a second. The replicas exist for throughput, not just safety.
  • •Ten replicas at about 56% busy is about right. With no result cache the same fleet would be 94% busy, so the cache is not an optimisation, it is capacity.
  • •At 1,000 shards, a query is only as fast as its slowest shard. The tail, not the average, decides the user experience.
  • •5 TB of new text a day is a streaming and batch problem, not a database write problem. Segments are built offline and swapped in.
  • •A full rebuild takes about 14 hours, so freshness cannot depend on rebuilding. We need incremental segments and a small real-time tier.
  • •The link graph is 2.5 trillion edges, which only fits in a distributed batch job. PageRank runs offline, a few iterations a day, and its output is just one number per page.
🎤
Say it out loud
“Let me do the maths. 50 billion pages at 10 kilobytes of text is 500 terabytes. The index is about 20 percent of that, 100 terabytes, so with 100-gigabyte shards that is 1,000 shards, and with 10 replicas each, about 10,000 machines. At 100,000 queries a second, with a 40 percent cache hit rate, 60,000 queries reach the shards, and each goes to all 1,000 of them: 60 million shard calls a second. That is why replicas matter, and why the slowest shard sets our latency.”

Step 3Define the API and the data modelabout 4 min

🤔
Pause. Try it yourself first
Write the one call a user makes, then the call between the root and a shard. What does a shard return? What does the index look like on disk, and what else do you need per page besides the words?

Endpoints

MethodPathRequestResponseNotes
GET/search?q=&lang=&region=&page=none200 { results: [{ url, title, snippet, score }], partial, tookMs, spell }page is limited (for example, 10 pages) since deep pages are costly. partial=true when some shards did not answer in time.
POST/internal/shard/query{ terms[], filters, topK: 20, deadlineMs }{ hits: [{ docId, score }], docsScanned }Root or mid-level aggregator to a leaf. Returns only IDs and scores, not text, so replies are small.
POST/internal/docs/snippets{ docIds[], terms[] }{ items: [{ docId, url, title, snippet }] }Called only for the final ten. Reads the document store, not the index.
POST/internal/index/segments{ shardId, segmentId, manifest }204The indexer publishes a built segment. Replicas download and load it, then switch.

Data model

StoreKey and valueNotes
Inverted indexterm → postings: sorted docIds, term frequency, positionsPer shard, in immutable segments, compressed (delta + variable-length). The main data structure.
Forward index / document storedocId → { url, title, extracted text, language, fetchedAt }Used for snippets and reranking features. Sharded by docId. About 500 TB.
Per-page signalsdocId → { pageRank, quality, spam, freshness, language }Computed offline. Small numbers per page, loaded into memory on each shard.
URL to docId maphash(url) → docIdUsed by the indexer for updates, dedup and removals.
Link graphdocId → outgoing docIds (and anchor text)Input for PageRank and anchor-text signals. About 40 TB.
Result cachehash(normalised query, lang, region) → top resultsShort TTL. Absorbs the head of the query distribution.
Postings for one term inside one shard (sketch)
"nearby"  ->  docIds:    [12, 40, 41, 97, 410, ...]      (sorted, stored as gaps: 12, 28, 1, 56, 313 ...)
              term freq: [ 3,  1,  2,  1,   5, ...]
              positions: [[4,19,77], [8], [2,30], [60], [1,5,9,22,40], ...]   (for phrase queries)
              skip list: every 128 docIds, so an AND can jump ahead
📝Which store, and why
The inverted index lives on each shard's local SSD and the hot parts in memory, in immutable segment files, because the index is read far more than it is written and rebuilt in batches. The document store and link graph live in distributed object or key-value storage and are read in bulk by batch jobs. Per-page signals are small, so each shard keeps them in memory. There is no general-purpose database in the query path.
🎤
Say it out loud
“There is one public call, a search with a query, language and page, which returns ten results and a flag if the answer was partial. Inside, the root calls each shard with the terms and a top-K and gets back only document IDs and scores, so replies are tiny. Only for the final ten we fetch titles and snippets from a separate document store. The data is an inverted index per shard in immutable segments, a document store, a small set of per-page signals such as PageRank and spam score, and a link graph used offline.”

Step 4Draw the high-level designabout 8 min

🤔
Pause. Try it yourself first
Draw two halves: the slow offline pipeline that makes the index, and the fast online path that answers a query. Where do they meet? Where does one query fan out, and where do the answers come back together?
Search engine: high-level design
Offline: build the index
🕷️Crawlerfetched pages (separate system)
↓
🧹Parse and deduptext, links, near-duplicates
↓
🧮Link graph and PageRankbatch, iterative
↓
🏗️Indexerbuilds segments per shard
Index storage
📦Segment storeimmutable files
📚Document storetext for snippets
⚡Real-time tierfresh news, small
👤Usertypes a query
→↓HTTPS
🧠Query understandingtokenize, spell, rewrite
→↓
🗃️Result cachehead queries
→↓miss
🌳Root aggregatorfan-out and merge
Index shards (1,000), 10 replicas each
🔎Leaf: shard 1 ... 1,000local top 20 by a cheap score
🔎Replica groupsbackup requests go here
After the merge
🎯Rerankerlearned model on top 300
✂️Snippet builderreads document store
Offline, pages become index segments. Online, a query fans out to every shard, comes back merged, is reranked and gets snippets.
ComponentWhat it does
Parse and dedupExtracts text, links and anchor text from each fetched page, drops exact and near-duplicates (with MinHash or SimHash), and assigns a stable document ID.
Link graph and PageRankA batch job over the link graph computes an importance score per page. It runs offline, a few times a day, and writes one number per page.
IndexerBuilds immutable index segments for each shard from the cleaned pages. Publishes a manifest. Replicas download and switch to the new segments.
Real-time tierA small index fed by a stream, holding pages from the last hours. Queried alongside the main index so news appears in minutes.
Query understandingTokenizes, lowercases, corrects spelling, expands synonyms, and detects language. Output is a structured query.
Result cacheStores the finished top results for popular queries for a short time. The cheapest query is one we do not run.
Root and mid-level aggregatorsFan the query out in a tree, collect each shard's top 20, merge them into a global top list, and enforce deadlines.
Leaf shards and replicasEach holds 50M documents' inverted index and signals. Scores locally with a cheap formula and returns IDs and scores. Replicas share the load.
Reranker and snippet builderRerank the top few hundred with an expensive model and many features. Fetch text for the final ten and cut the snippet.
Write path (follow one request)
  1. The crawler delivers fetched pages. A parse step extracts text, title, language, links and anchor text, and computes a content fingerprint.
  2. Dedup drops exact copies and near-duplicates, and assigns each page a stable docId (so a changed page keeps its ID).
  3. A batch job builds the link graph and runs PageRank. It also computes quality and spam scores. Each page gets a small set of numbers.
  4. The indexer groups pages by shard (docId modulo shard count, or a hash), builds a new immutable segment with postings and signals, and uploads it.
  5. Replicas of each shard download the segment, check its checksum, load it, and add it to their list of live segments. A background merge combines small segments.
  6. Pages with news-like changes also go through a stream into the small real-time tier, so they are searchable within minutes, long before the next batch.
Read path (follow one request)
  1. The user sends a query. The front end checks a rate limit and sends it to query understanding, which produces tokens, a language and a corrected form.
  2. The result cache is checked on the normalised query. A hit returns the stored page at once (about 40% of queries in our assumptions).
  3. On a miss, the root aggregator sends the query to the mid-level aggregators, which send it to one replica of every shard, with a deadline attached.
  4. Each shard walks the postings of the query terms, intersects them, scores each match with a cheap formula (text match plus its stored signals) and returns its local top 20.
  5. Aggregators merge the lists as answers arrive. If a shard is slow, a backup request goes to another replica. At the deadline, the root stops waiting and marks the answer partial.
  6. The reranker scores the best 300 or so candidates with the expensive model. The snippet builder fetches text for the final ten and highlights the match.
  7. The page is returned, and stored in the result cache with a short TTL.
🎤
Say it out loud
“Two halves. Offline, fetched pages are parsed, deduplicated, scored with PageRank and quality signals, and the indexer builds immutable segments for each of about 1,000 shards. A small real-time tier covers fresh news. Online, a query is understood, checked against a result cache, and then a tree of aggregators sends it to one replica of every shard. Each shard returns its local top 20, the root merges them, a learned reranker orders the top few hundred, and a snippet builder reads the document store for the final ten. Deadlines and backup requests keep one slow shard from slowing everyone.”

Step 5Deep dive into the hard partsabout 16 min

🧠The pattern for every deep dive
Problem → options → pick one → say why → say what it costs. Interviewers score the reasoning more than the choice.
5.1

How to split the index across machines

The problem: The index is 100 TB, far too big for one machine, and 100,000 queries a second is far too much for one copy. We must decide what each machine holds, and how many machines every query has to touch.

OptionHow it worksGoodBad
Document partitioningEach shard holds a subset of documents, with all terms for those documents. A query goes to every shard.Each shard can answer alone. Adding documents touches one shard. Balanced by construction. A failed shard loses a slice, not a word.Every query touches every shard (60 million calls a second). The slowest shard decides the latency.
Term partitioningEach shard holds the full postings for some terms. A query goes only to the shards that own its terms.Fewer shards per query. Less total work for rare words.A common word has a huge posting list that must be sent across the network to be intersected. Hot terms create hot shards. Adding a document touches many shards.
Document partitioning with tiersPut high-quality, frequently clicked pages in a small, fast first tier. Query the big second tier only if the first does not give enough good answers.Most queries are answered by a small slice of the index. Saves a lot of machines.Complex. A page in the wrong tier is hidden. Needs a rule for when to go to the next tier.
Hybrid: document-partitioned groupsGroup shards into clusters, each a complete index of a slice of the web. A query goes to every shard inside one cluster, and clusters are copies for load.Natural way to organise replicas and rolling swaps.Same fan-out inside a cluster. Needs routing and capacity planning per cluster.
Pick
Document partitioning, with replicas as whole copies of each shard, and a small high-quality tier in front

The key advantage is that a shard is self-contained: it can find, score and return its best 20 without talking to anyone. Term partitioning looks cheaper because fewer machines are touched, but the cost moves to the network: the posting list for a common word is tens of millions of entries, and intersecting two of them across machines means shipping megabytes per query.

The price of document partitioning is the fan-out, and we pay it with replicas and a result cache. Ten replicas per shard handle the throughput, and the tail-latency tools in the next deep dive handle the slowest shard. A first tier of the best pages lets most queries stop early.

Document partitioningTerm partitioning
Shards per queryAll 1,000Only the shards that own the query terms
Data sent for one query20 hits from each shard (about 320 KB in all)Long posting lists, megabytes for common words
Adding one documentOne shardEvery shard that owns one of its terms
Hot spotsRare (a hot document is just one document)Common: one popular word is one hot shard
A shard failsLose a slice of the pages (about 0.1%)Lose all pages that contain those words
📝The size of the fan-out reply
Each shard returns 20 hits of about 16 bytes (ID and score). That is 320 bytes a shard and about 320 KB per query across 1,000 shards. At 60,000 queries a second that is about 19 GB/s into the aggregators, so a tree of mid-level aggregators is needed, and not one root.
🎤
Say it out loud
“I would partition by document. Each shard holds a slice of the pages with all their words, so it can find and score its best 20 on its own. The alternative, term partitioning, touches fewer machines per query but has to ship huge posting lists for common words across the network, and creates hot shards. The price of my choice is that every query touches all 1,000 shards, which is 60 million shard calls a second. I pay that with ten replicas per shard, a result cache, and a small first tier of the best pages that answers most queries early.”
5.2

Tail latency: the answer is as slow as the slowest shard

The problem: A query waits for all 1,000 shards. Even if each shard is slow only 1% of the time (a garbage collection pause, a merge, a bad disk), almost every query will meet at least one slow shard.

OptionHow it worksGoodBad
Wait for everyoneThe root waits for every shard to reply.Complete answers. Simplest.The slowest shard sets the latency. With 1,000 shards and 1% slow calls, 1 - 0.99^1000 is more than 99.99% of queries.
Backup (hedged) requestsIf a shard has not replied after a short time (about the 95th percentile of a healthy call), send the same request to another replica and use whichever answers first.A query is slow only if both tries are slow, about 1% × 1% = 0.01% per shard. Cheap: about 5% extra calls if you hedge at p95.More load. Only helps when slowness is independent between replicas. Requests must be safe to repeat.
Deadline and partial resultsStop waiting at a fixed time and answer with the shards that replied. Mark the answer partial.A hard upper bound on latency. Often invisible, since the top results rarely come from the one slow shard.A small share of the index is missing in that answer. Must be measured, and queried for rare pages carefully.
Cut the work and the varianceEarly termination (stop after enough candidates), caches for posting lists and results, smaller and evenly sized shards, rate limits between GC pauses, and removing noisy neighbours.Fewer slow calls in the first place.Ongoing engineering. Never reaches zero.
Pick
Backup requests at about p95, plus a deadline for partial results, on top of caching and less variance

The maths is what makes this hard. If one call is slow with probability p, a query over N shards is slow with probability 1 - (1 - p)^N. For p = 1% and N = 1,000, that is 1 - 0.99^1000 = 1 - 0.00004 = 99.996%. For p = 0.1% it is still 63%. Nothing about the average latency shows this. It lives entirely in the tail.

A backup request turns the failure into two independent bad events: the query is slow only if the first try and the backup are both slow, about p × p. For p = 1% that is 0.01% per shard, and over 1,000 shards 1 - (1 - 0.0001)^1000 is about 9.5%. Better, not solved. So we add a deadline as the last safety net: stop waiting, return what we have and flag the answer partial. Together they bring almost every query inside the budget.

Slow calls per shard (p)1 - (1 - p)^1,000: some shard is slowWith a backup: 1 - (1 - p²)^1,000
0.1%63.2%0.1%
1%99.996%9.5%
5%about 100%91.8%
💡Hedge after the healthy p95, not the p99
If you send the backup too early you double the load. If you send it too late it does not help. A healthy shard answers in about 8 to 14 ms, so a backup after about 20 ms adds roughly 1% extra calls for a 1% slow rate. The deadline should be smaller than the latency budget minus the time the other stages need.
⚠️A deadline can hide a bad shard
If a shard is always slow and always skipped, its pages silently disappear from results. Track the share of partial answers per shard, and take a shard that is persistently late out of rotation and rebuild it.
🎤
Say it out loud
“A query waits for all 1,000 shards, so it is as slow as the slowest. If each shard is slow just 1% of the time, the chance that at least one of 1,000 is slow is 1 minus 0.99 to the 1,000, which is 99.996%. So I would add backup requests: after about the healthy 95th percentile, send the same call to another replica and take the first answer. A query is then slow only if both tries are slow, about one in ten thousand per shard. Then a deadline as a safety net, so a stuck shard gives a slightly partial answer instead of a slow one. And I would track partial answers per shard, so a shard that is always late gets fixed.”
5.3

Ranking: cheap retrieval first, expensive reranking second

The problem: Billions of pages match a loose query. We cannot run a heavy model on all of them, and relevance is the product: ten wrong links is a failed search.

OptionHow it worksGoodBad
Text match only (BM25 or TF-IDF)Score each page by how often and how rarely the query words appear in it, with length normalisation.Fast and cheap. Works inside the shard on the postings alone.Easy to spam. Ignores importance, freshness and intent. Many pages match equally well.
Text match + link analysis (PageRank)Add a static importance score per page, from how many important pages link to it.A strong, query-independent quality signal, computed offline, free at query time.Can be gamed by link farms. Slow to react to new pages. Says nothing about this query.
Two-stage rankingStage 1, on each shard: a cheap score (text match + static signals) picks the local top 20. Stage 2, at the root: a learned model with hundreds of features reranks the merged top few hundred.The expensive model runs on about 300 pages, not billions. The model can change without rebuilding the index.Stage 1 can drop a page that stage 2 would love. Two systems to tune and evaluate.
Heavy model on all matchesScore every page that matches with the learned model.Best possible ranking.Impossible at 100,000 queries a second over billions of pages.
Pick
Two stages: a cheap shard-local score for retrieval, and a learned reranker on the merged top few hundred

The first stage must be so cheap that it can score every match on a shard, so it uses only the postings and a few stored numbers: a text score such as BM25 (which rewards a rare query word appearing often in a short field, and weights title and anchor text more than body text), plus the static page signals (PageRank, quality, spam, freshness). Its only job is to make sure the best pages are in the top 20 of their shard.

The second stage sees only about 300 candidates, so it can afford a learned model with many features: term proximity, the query's language and region, click history for this query, how fresh the page is, and more. Because it runs after the index, a new model can be tested and rolled out without rebuilding anything.

SignalWhat it measuresComputed
BM25 on body, title, anchor textHow well the words match, rare words count more, fields are weightedAt query time, from postings
Proximity and phrase matchAre the words close together, in order?At query time, from positions
PageRankHow important the page is, from the link graphOffline, a few times a day
Quality and spam scoreIs it useful, original and safe?Offline, with a model
FreshnessHow recent is it, and does this query want recent pages?Offline and at query time
Click and satisfaction dataDid people click and stay on this result for this query?Aggregated offline, used by the reranker
📝PageRank in one paragraph
Imagine a person who clicks links at random, and now and then (with probability 0.15) jumps to a random page. PageRank is the share of time they spend on each page. A page gets a high score if many pages with high scores link to it. It is computed by repeating one step: each page splits its current score among the pages it links to, then every page adds up what it receives, with the damping factor of 0.85 on the received part. After about 30 rounds it settles. On 2.5 trillion links each round is a batch job, with each round taking minutes on a large cluster, so it runs offline and the result is one number per page.
💡Evaluate before you ship a ranking change
Human raters score result pages (NDCG is a common measure of how good the top of a list is). Then an A/B test on a small share of live traffic looks at clicks, time to first click and returns to the results page. A change only goes out if it wins on both.
🎤
Say it out loud
“I would rank in two stages. Each shard scores its matches with something cheap, text relevance such as BM25 with extra weight for title and anchor text, plus stored signals like PageRank, quality and spam score, and returns its local top 20. The root merges to about 300 candidates and a learned reranker with many more features orders them. The expensive model sees 300 pages, not billions, and I can change it without rebuilding the index. PageRank is computed offline as the random-surfer score on the link graph, one number per page. I would judge changes with human raters and an A/B test.”
5.4

Freshness: updating a huge index without rebuilding it

The problem: A full rebuild takes about 14 hours, but a breaking news story must be searchable in minutes. Pages also change and disappear, and replicas must keep serving while the index changes under them.

OptionHow it worksGoodBad
Rebuild everything on a scheduleRebuild the whole index every day or week and swap it in.Simple. Clean, well-compressed index.Days of staleness. A huge amount of repeated work for the 99% that did not change.
Update the index in placeAdd and change postings directly in the live index.Fresh at once.Needs locks or complex structures, hurts read speed and caching, and is hard to recover after a crash.
Immutable segments plus mergesNew and changed pages go into small, new, read-only segments. Queries search all live segments. A background job merges small ones into big ones, and deleted pages are marked in a bitmap.Reads are never blocked. New data is searchable as soon as its segment loads. Crash-safe: a segment is complete or absent.Queries search several segments. Merging costs disk and CPU. Deletes are logical until a merge.
A separate real-time tierA small, fast index fed by a stream holds only the last few hours of changes. Queries ask both tiers and merge.Minutes of freshness for the content that needs it, without touching the big index.Two indexes to operate, and results from both tiers need compatible scoring.
Pick
Immutable segments with background merges, plus a small real-time tier for news, and rolling swaps

This is the same idea as an LSM tree, applied to an index: never change a file, only add new ones, and clean up later. A shard has a few large old segments and many small new ones. A query searches them all and merges. A deleted page is marked in a per-segment bitmap and filtered out of results, and its space is reclaimed when the segment is next merged.

For new batches, the indexer builds segments off to the side. Each replica downloads, checks and loads them, and then switches its list of live segments in one step. Replicas are updated a few at a time, so the shard always has healthy copies serving. The real-time tier covers the gap: pages from a news feed or a recrawl of a trending page go straight into it, and fall out of it once the main index has caught up.

EventWhat happensVisible after
Breaking news pageStream to the real-time tierA few minutes
Ordinary page changedNext batch builds a new small segmentHours to a day
Page removed (legal or spam)Added to a removal list checked at serving, bit cleared in the segmentMinutes (filtered); space freed at the next merge
Ranking signals updated (new PageRank)Signals file replaced, loaded into memoryHours
New index versionReplicas load it a few at a time, then switchRolled out over hours with no downtime
⚠️Never swap every replica at once
A bad index build (a broken tokenizer, a missing field) must hit a few replicas first, be noticed by quality checks, and be rolled back. Treat an index version like a deployment: canary it (see Canary Releases and Blue-Green Deployments), compare result quality, then continue.
🎤
Say it out loud
“A full rebuild takes about 14 hours, so freshness cannot depend on it. I would never change an index file. New and changed pages go into small immutable segments, queries search all live segments, deletes are marked in a bitmap, and a background job merges small segments into big ones, the same idea as an LSM tree. A small real-time tier fed by a stream makes news searchable in minutes. New segments are loaded by a few replicas at a time and checked before the rest, so a bad build is caught early and never takes the whole shard down.”
5.5

Quality, spam and keeping the index clean

The problem: The web is full of copies, thin pages and people trying to rank higher than they deserve. If we index everything equally, results fill with duplicates and spam, and ranking signals such as links get gamed.

OptionHow it worksGoodBad
Index everything, rank laterKeep every fetched page and rely on ranking to push the bad ones down.Simple, never throws away something useful.Wastes storage and shard capacity on duplicates and junk. Spam still reaches the top-K of a shard and can crowd out good pages.
Dedup before indexingDrop exact copies (hash of the text) and near-duplicates (MinHash or SimHash fingerprints), and keep one canonical page.A smaller index and cleaner results. Cheap to do in the batch pipeline.A wrong near-duplicate match hides a real page. Needs a canonical-page rule.
Quality and spam modelsScore each page offline for quality and spam (thin content, keyword stuffing, hidden text, link-farm patterns) and store the score as a signal.Demotes or excludes the worst. Reused by the ranker.An arms race. Needs training data and review. False positives hurt honest sites.
Link-spam resistanceDiscount links from suspected farms, ignore marked links (nofollow), and compute trust from known good seed pages.Protects the strongest signal, PageRank.More graph computation. Honest links can be discounted by mistake.
Pick
Dedup before indexing, quality and spam scores as ranking signals, and link discounting, with removals applied at serving time

Doing it in the batch pipeline is cheap and shrinks everything downstream: fewer pages to index means fewer shards and cheaper replicas. Exact duplicates are found by hashing the cleaned text. Near-duplicates (the same article with a different header) are found by comparing small fingerprints: MinHash estimates how much two sets of word groups overlap, and pages above a threshold are grouped, with one chosen as the canonical page.

Spam and quality are stored as numbers per page, so the shard score and the reranker can use them. Legal removals and safe-search flags are checked at serving time against a small, fast list, because they must apply in minutes, long before the next index build.

🎤
Say it out loud
“I would clean the web before indexing it. Exact copies are dropped by hashing the text, near-duplicates are grouped with MinHash or SimHash fingerprints and one canonical page is kept. A model scores quality and spam per page and the score is a ranking signal, and the link graph discounts suspected link farms so PageRank is harder to game. Legal removals and safe search are applied at serving time, from a small fast list, so they take effect in minutes instead of waiting for an index build. It is an arms race, so I would also measure the spam rate in results and review samples.”
VisualizerScatter-gather search: why the slowest shard sets the latencyStart with 1,000 shards and 1% slow calls: almost every query misses the 200 ms budget. Then turn on a backup request, then a deadline, and watch the tail, the partial answers and the extra load.
How often is one shard call slow?
Backup request to a second replica
Per-shard deadline, then partial results
Time to answer, for 200 queries in a fixed run. The shard stage plus 60 ms for the rest (understand the query, result cache, rerank, snippets). Green bars fit the 200 ms budget, red bars do not.
0
under 100 ms
0
100-150 ms
0
150-200 ms
0
200-300 ms
5
300-500 ms
195
500+ ms
Over 200 ms
100.0%
200 of 200 queries
Typical (p50)
860 ms
half are faster
Slow end (p99)
860 ms
1 in 100 is slower
Partial answers
0.000%
every shard answered
Extra shard calls
0.000%
backup requests
100.0% of queries blew the 200 ms budget. Each shard is slow only 1.00% of the time, but the answer waits for all 1000. The chance that at least one is slow is 1 - (1 - 0.01)^1000 = 99.996%. Turn on a backup request or a deadline.
The arithmetic behind it
A query is slow if any of its 1,000 shards is slow. With 1.00% slow calls:
1 - (1 - 0.01)^1000 = 1 - 4.3 x 10^-5 = 99.996%
In this run, 100.0% of the 200 queries met at least one slow first try (the formula predicts 99.996%).

A simplified model with made-up numbers and no random values: each call's time comes from a fixed formula. A healthy shard takes 8 to 14 ms. A slow one (a garbage collection, a merge, a bad disk) takes 150 to 800 ms. The backup goes to a second replica with its own fixed times. The deadline applies to the shard stage only; a query that hits it returns the shards that answered and reports the rest as missing.

Step 6Scale, bottlenecks and failuresabout 7 min

🤔
Pause. Try it yourself first
What breaks first if queries double, or if one shard group gets a bad index? What do users see if 10 shards are down? What gets expensive first?

What breaks first, and the fix

BottleneckFix
Fan-out cost (60M shard calls a second)More replicas, a result cache, a first tier of the best pages that answers many queries early, and posting-list caches. Smaller replies from each shard.
Tail latency from one slow shardBackup requests at about p95, a deadline with partial results, and fewer causes of slowness (GC tuning, throttled merges, spreading maintenance).
Aggregator fan-in (about 19 GB/s)A tree of mid-level aggregators, so no one machine receives 1,000 replies, and shard replies stay as small as IDs and scores.
Hot, popular queriesResult cache with a short TTL, and request coalescing so many identical queries trigger only one search.
Expensive reranker at peakRerank fewer candidates under load, use a smaller model, and degrade to the first-stage order when overloaded.
Index growth and costTiering (best pages in a small fast tier, the long tail on cheaper storage), compression, dropping duplicates and junk before indexing.
Snippet generationFetch document text only for the final ten, cache snippets for popular results, and store text compressed and in sorted blocks.

What if a part fails?

FailureHow the design copes
One replica of a shard diesOther replicas serve. The load balancer stops sending calls to it, and a new replica downloads the segments.
All replicas of a shard are downReturn a partial answer missing about 0.1% of the index, flagged partial, and page an engineer. Rebuild from the segment store.
A bad index version is rolled outRoll out to a few replicas first, compare quality and error metrics, and roll back to the previous segments. Keep the last two versions.
A query of death crashes shardsRun each query with limits (time, memory, postings scanned), quarantine the query pattern, and isolate crashes so retries do not take down every replica.
The result cache is lostCapacity drops for a while (the fleet would run at about 94% busy). Shed load with rate limits and warm the cache from popular queries.
A region goes downRoute to another region, which holds a complete index copy. Capacity planning must allow for losing a region, and results may be slightly staler.
What to monitor
  • •Latency by stage (understanding, shard fan-out, merge, rerank, snippets), at p50, p95 and p99
  • •Share of partial answers overall and per shard, and shards that are persistently late
  • •Backup request rate, and how often the backup wins
  • •Result cache hit rate, and the load per replica
  • •Index freshness: age of the newest page in the main and real-time tiers
  • •Relevance: click-through, time to first click, query reformulation rate, and rater scores on a fixed query set
Security and abuse
  • •Rate limit queries per client and detect scraping and bots (see Design a Rate Limiter).
  • •Honour robots rules and legal removal requests, and apply them at serving time.
  • •Sanitise snippets and titles before showing them, since they come from untrusted pages.
  • •Protect the index and document store: access control, encryption, and signed segments so a tampered file is rejected.
  • •Watch for ranking attacks: link farms, cloaking (showing the crawler different content), and fake click patterns.

Step 7Wrap upabout 3 min

Offline, pages are parsed, deduplicated, scored with PageRank and quality signals and built into immutable segments for about 1,000 document-partitioned shards, each with 10 replicas, plus a small real-time tier for news. Online, a query is understood, checked against a result cache, fanned out through aggregators to one replica of every shard, merged, reranked by a learned model and given snippets. Backup requests and deadlines protect the tail, and rolling swaps keep the index fresh without downtime.

Trade-offs you made

DecisionWhat we gainWhat it costs
Document partitioningSelf-contained shards, easy updates and balanced load.Every query touches every shard: 60 million shard calls a second.
Backup requests and deadlinesA bounded tail, with almost every query inside the budget.About 1 to 5% extra load, and a small share of partial answers.
Two-stage rankingA strong model runs on 300 pages instead of billions, and can change without a rebuild.Stage 1 may drop a page that stage 2 would have liked.
Immutable segments and a real-time tierCrash-safe updates, no read locks, and minutes of freshness for news.Queries search several segments, and merges cost disk and CPU.
A result cacheAbout 40% fewer shard calls and a faster typical answer.Stale results for a short time, and a capacity hole if the cache is lost.
Dedup and quality scoring up frontA smaller index, cleaner results and a harder-to-game ranker.False positives can hide real pages, and spam is an arms race.
If we had more time, we would…
  • •Add a vector (semantic) retrieval path next to the keyword path, and merge the candidates before reranking.
  • •Personalization and location-aware ranking, with careful caching and privacy.
  • •Better query understanding: spell correction, synonyms, entities and intent.
  • •Learned sparse or dense index tiers to cut cost, and smarter shard routing for rare queries.
  • •A shadow-traffic harness to test a new index or ranker on live queries without showing results.
🎤
Say it out loud
“To recap: pages are cleaned, deduplicated and scored offline and built into immutable segments for about a thousand document-partitioned shards with ten replicas each, plus a small real-time tier for news. A query goes through understanding and a result cache, then fans out through aggregators to every shard, each returns its local top 20, and a learned reranker orders the top few hundred. I protect the tail with backup requests and a deadline, and I keep the index fresh with segments and rolling swaps. The costs are the fan-out, a few percent extra load, and some partial answers. Next I would add semantic retrieval and personalization.”

Q&ACross-questions (26)

💡How to practise
Cover the answer. Say yours out loud in 30 to 60 seconds. Then open the model answer, the follow-up, and the weak answer to see what to avoid. Use Open all at the top for a quick read.
Warm-upProbingCurveballWarm-up = basics. Probing = tests depth. Curveball = changes the problem.

Sharding and serving

The part interviewers start with. Say the numbers, and say what the fan-out costs.

Tail latency and failures

The senior-level follow-ups: what is slow, what is broken, and how you know.

Ranking and relevance

Where the product lives. Know what each signal is for, and how you would prove a change is better.

Freshness, cost and curveballs

Operating the thing: updates, spam, money, regions, and what you would cut.

What ifIf the interviewer changes the problem

A change in requirements is a test of whether you understand why your design looks the way it does.

New requirementWhat changes in the design
The corpus is one company's documents (10 million), not the webA single Elasticsearch or OpenSearch cluster with a few shards is enough. Drop the aggregator tree, tiers and hedging. Spend the effort on relevance and permissions.
Results must respect per-user access rules (enterprise search)Store an access list per document and filter at query time, or shard by tenant. Result caching becomes per user or per group, and ranking cannot leak titles of hidden documents.
Freshness must be seconds, for all pagesThe real-time tier becomes the main path: a streaming indexer writing small segments continuously, with more frequent merges and higher cost per page. Fewer pages can qualify.
Add semantic (vector) searchA second approximate nearest-neighbour index and fan-out, with candidates merged before the reranker. Needs an embedding pipeline and more memory.
Ten times the query rateMore replicas and a bigger cache, plus more aggressive early termination and a smaller first tier. Fan-out grows linearly, so the number of shards needs a second look.
Add personalizationThe same query no longer gives the same page, so the result cache key must include a user segment, or personalise in the reranker only. Needs privacy controls and a feature store.
Add image searchA separate index with image features and embeddings, text from surrounding page, and thumbnails in object storage. Same serving pattern, different retrieval.
Strict latency of 50 ms at p99Fewer, bigger shards and a tiered index with in-memory first tier, a smaller reranker, no second fan-out, and tighter hedging. Quality is traded for speed.

ScoreHow answers are judged

AreaWeakGoodGreat
RequirementsStarts drawing boxes, or says 'use Elasticsearch'.Asks scale, freshness, latency and scope, and states them.Separates indexing from serving, sets a latency budget and a partial-results policy, and names what is out of scope.
EstimationSkips it, or only sizes storage.Index size and shard count.Computes shard calls a second (the fan-out), per-machine load, and uses the cache hit rate to justify the replica count.
Index designA database table with a text column.An inverted index split across shards.Document partitioning with reasons against term partitioning, immutable segments, compressed postings and tiers.
Tail latencyNot mentioned.Mentions timeouts and replicas.Does the 1 − (1 − p)^N maths, uses backup requests and a deadline with partial results, and measures partial answers per shard.
RankingSort by keyword count.TF-IDF or BM25 plus PageRank.Two-stage retrieval and rerank, offline evaluation, A/B tests, and a safe rollout path.
OperationsSays add more servers.Mentions replicas and monitoring.Rolling index swaps with canaries and rollback, queries of death, region loss, cost levers, and a phased plan.

AvoidCommon mistakes on this question

MistakeDo this instead
Answering with a single database and a LIKE querySay the inverted index is the answer, then split it into shards and replicas.
Ignoring the fan-out costCompute shard calls a second. 60,000 queries times 1,000 shards is 60 million, and it explains replicas, caching and tiers.
Only discussing average latencyDo the 1 − (1 − p)^N maths and add backup requests and a deadline.
Running the heavy ranking model on every matchCheap local scoring first, then a learned reranker on the top few hundred.
Rebuilding the whole index to be freshImmutable segments, background merges and a small real-time tier.
Treating crawling and typeahead as part of this problemState the boundary, link to those designs, and focus on indexing, serving and ranking.
Swapping the index on every replica at onceRoll out a few replicas at a time with quality checks and a one-step rollback.
Never saying what a choice costsFor each choice name what you gain and pay: fan-out, extra load, partial answers, staleness.

Revise60-second revision sheet

  • ✔Two systems: offline index building, online query serving, joined by immutable index segments.
  • ✔Scale (illustrative): 50B pages, 500 TB text, 100 TB index, 1,000 shards of 100 GB, 10 replicas, 100k queries a second.
  • ✔Fan-out: document partitioning means every query touches all shards: 60,000 × 1,000 = 60M shard calls a second.
  • ✔Serving: understand, result cache, aggregator tree, each shard returns local top 20 (IDs and scores), merge, rerank about 300, snippets for 10.
  • ✔Tail: P(some shard slow) = 1 − (1 − p)^N. At p = 1%, N = 1,000: 99.996%.
  • ✔Fixes: backup request at about p95 (slow only if both slow, p²), a deadline with partial results, caching, less variance.
  • ✔Ranking: BM25 + PageRank + quality and freshness in stage 1; a learned reranker in stage 2; judge with raters and A/B tests.
  • ✔Freshness: immutable segments, merges, deletes by bitmap, a small real-time tier, rolling swaps with canaries.
  • ✔Quality: dedup (MinHash or SimHash), spam and quality scores, link discounting, removals checked at serving time.
  • ✔Cost levers: result cache, tiers, early termination, compression, dropping junk before indexing.

Read these topics next

Inverted Index→

The core data structure: postings, intersection, compression and segments.

Full-Text Search Engines→

How engines like Elasticsearch analyse text and rank results on one cluster.

Design a Web Crawler→

Where the pages come from: the frontier, politeness and freshness.

Design Search Autocomplete→

The suggestions shown while the user is still typing.

Sharding→

Splitting data across machines, and what it costs to ask every shard.

MinHash→

Finding near-duplicate pages with small fingerprints.

MapReduce→

The batch model behind PageRank and index building.

Caching Strategies→

The result cache and posting-list caches that make the fleet affordable.

← Previous
Design Ticket / Hotel Booking
Next →
Design Google Maps