Search engine
What we are building
Section titled “What we are building”A search engine takes a few words and returns the pages that best answer them, in a fraction of a second, out of billions. It is two systems joined by one data structure. One system gathers pages and builds the index, slowly and offline. The other answers queries from the index, quickly and all day. The index is where they meet.
Functional requirements. Fetch pages from the web and keep them fresh. Build an index of their words. Given a query of one or more words, return the 10 best pages. Snippets, spelling correction, images, personalisation and advertising are left out.
Non-functional requirements. These are targets chosen for this lesson. A query answers in under 500 ms at the 99th percentile. The crawler never overloads a site. A page is searchable within about a month of being fetched, and news within minutes is a stretch goal that the last section costs. The service stays up when a machine fails.
Scale. 5 billion pages of about 100 KB, each fetched again every 30 days, and 10,000 queries per second at the peak.
Mental model. A book has an index at the back: for each word, the pages where it occurs. A search engine is that index for the web, cut into pieces so that it fits on many machines, with a front desk that asks every piece and merges the answers. Everything else, the crawler that feeds it and the ranking that orders it, is about keeping that index complete, fresh and fast to read.
Estimate before you design
Section titled “Estimate before you design”The method is the one from storage and retention: every figure is a round number you can check by hand. The assumptions are the first rows.
| Quantity | Working | Result |
|---|---|---|
| Pages | assumed | 5 billion |
| Raw size of the pages | 5 billion × 100 KB | 500 TB |
| Seconds in the refresh period | 30 × 86,400 | 2,592,000 |
| Pages to fetch per second | 5 billion ÷ 2,592,000 | about 1,900 |
| Download rate | 1,929 × 100 KB | about 190 MB/s, 1.5 Gbit/s |
| Index per page | assumed | about 10 KB |
| Size of the index | 5 billion × 10 KB | 50 TB |
| Index per machine | assumed | 500 GB |
| Machines for one copy of the index (shards) | 50 TB ÷ 500 GB | 100 |
| Queries per second answered by a machine | 16 slots ÷ 0.020 s | 800 |
| Copies of the index for 10,000 queries per second | 10,000 ÷ 800 = 12.5, rounded up | 13 copies, 1,300 machines |
| Same, if a cache answers 40% of the queries | 6,000 ÷ 800 = 7.5, rounded up | 8 copies, 800 machines |
The 100 KB, the 10 KB, the 500 GB, the 20 ms and the 40% are assumptions. Three conclusions hold for any reasonable values. The index does not fit on one machine, so the engine is sharded from the start. Throughput does not come from the shards but from copies of them, because each query needs all of them. And the crawler is a modest stream of 190 MB/s that has to be shared among many sites without hurting any one of them.
The API and the data
Section titled “The API and the data”GET /search?q=red+fox&page=1200 OK {"results": [{"url": "https://…", "title": "…", "snippet": "…"}, … 10 results]}Behind that one request there are three stores. The crawler keeps the frontier, the queue of URLs still to fetch, and a table of what it knows about each URL (when it was fetched, a fingerprint of the content). The index builder turns each page into an inverted index, described below. And ranking uses per-page signals such as how many other pages link to it, computed offline and stored with the index.
Five stages, each forced by a number
Section titled “Five stages, each forced by a number”The lab shows the path of a query only, because that is what the load reaches. Every figure is model output from illustrative inputs; the model notes under the lab say what it leaves out.
A service that finds web pages from the words a person types. Queries are answered from an inverted index, not by scanning pages. Step through five stages, each adding the one thing the previous stage’s numbers called for (copies, shards, a results cache, index tiers), and raise the load to see what breaks. The lab shows the path of a query; crawling and building the index are in the lesson.
Start simple: one server holds the index
Design load of this stage: 500 req/s
- What we add
- One server holds the whole inverted index, 50 million pages. For each word of a query it reads the list of pages that contain the word, combines the lists and ranks the best matches. Crawling and indexing run elsewhere and hand it new index files.
- Why: the number that forced it
- 50 million pages at about 10 KB of index each make 500 GB, which fits on the server’s SSD. A query keeps one of its 16 slots for about 20 ms, so the server answers 16 ÷ 0.02 = 800 queries per second. At 500 queries per second it is at 62.5%.
- What it costs
- Cheap and simple: one machine to run, one index to build. The price is a single point of failure, and a server that spends the same CPU and disk on answering queries and on loading new index files.
- What breaks next
- At twice the load, 1,000 queries per second, demand is 125% of its 800: a fifth of the queries fail. A second server is needed, and soon a third.
Each dot stands for many requests. The numbers show the real rate.
No bottleneck: every component has headroom.
Figures at this load
- Busiest component
- Search server (index and ranking)Busy63% of its capacity
- p95, whole request
- 60 ms
- p99, whole request
- 92 ms
- Requests served
- 100%500 req/s
- Requests failed
- 0%0 req/s
- Bottleneck
- none
| Component | State | Utilisation | Offered (req/s) | Served (req/s) | Rejected (req/s) | p50 | p95 | p99 |
|---|---|---|---|---|---|---|---|---|
| Searchers | Healthy | <1% | 500 | 500 | 0 | 0 ms | 0 ms | 0 ms |
| Search server (index and ranking) | Busy | 63% | 500 | 500 | 0 | 14 ms | 60 ms | 92 ms |
- Traffic
- 500 req/s
- Successful
- 500 req/s
- Error rate
- 0%
- Mean latency
- 20 ms
All stages at a glance
Each cell is the engine’s steady state for that stage at that load: the busiest component, how much of its capacity it uses, and the share of requests that fail.
| Stage | Design load | Design load | 2× the design load | 4× the design load |
|---|---|---|---|---|
| 1. Start simple: one server holds the index | 500 req/s | 500 req/sSearch server (index and ranking): 63%none fail | 1K req/sSearch server (index and ranking): 125%20% fail | 2K req/sSearch server (index and ranking): 250%60% fail |
| 2. Add copies of the whole index | 2K req/s | 2K req/sSearch replicas (4 full copies): 63%none fail | 4K req/sSearch replicas (4 full copies): 125%20% fail | 8K req/sSearch replicas (4 full copies): 250%60% fail |
| 3. Split the index into shards | 4K req/s | 4K req/sIndex shards (8 copies of 100 shards): 63%none fail | 8K req/sIndex shards (8 copies of 100 shards): 125%20% fail | 16K req/sIndex shards (8 copies of 100 shards): 250%60% fail |
| 4. Cache the results of repeated queries | 6.4K req/s | 6.4K req/sIndex shards (8 copies of 100 shards): 60%none fail | 13K req/sIndex shards (8 copies of 100 shards): 120%10% fail | 26K req/sIndex shards (8 copies of 100 shards): 240%35% fail |
| 5. Split the index into tiers | 10K req/s | 10K req/sTop tier (14 copies of 10 shards): 54%none fail | 20K req/sTop tier (14 copies of 10 shards): 107%4% fail | 40K req/sTop tier (14 copies of 10 shards): 214%36% fail |
Illustrative values, not benchmarks of any real product.
Model notes
Assumptions
- Requests arrive at random, as a Poisson process, at a constant average rate.
- Each node is one queue, served first-come first-served by several identical slots (instances × concurrency).
- Service times are random with the stated mean; by default they are exponentially distributed.
- Each node is analysed separately, with the traffic it receives treated as Poisson.
- Every number is illustrative model output, not the benchmark of a real search engine: 20 ms to answer a query on a shard of 50 million pages, 16 queries at once per machine, 10 KB of index per page, 500 GB of index per machine, 40% of queries answered by a results cache, 30% of queries needing the bottom tier.
- The corpus is 50 million pages in the first two stages and 5 billion from the third, the size the lesson’s estimates use.
Simplifications
- Above capacity there is no steady state. The model switches to a fluid approximation: the node serves at capacity, its queue grows until it reaches its limit, and further requests are rejected.
- Percentiles assume an exponential tail. A service-time variability other than exponential changes the mean wait but not the shape of the tail.
- A node frees its slot as soon as it has done its own work, before waiting on the services it calls. Real thread-per-request servers hold the slot, so a slow dependency exhausts them faster than this model shows.
- A request calls its dependencies one after another. Parallel fan-out is not modelled.
- When a caller times out and gives up, the callee still finishes the work, so abandoned requests keep consuming capacity.
- Retries add load. Their backoff and jitter decide when that load arrives, which only the per-request simulation shows.
- Retry feedback is solved from the healthy starting point, so it finds one stable outcome. Systems that stay stuck in overload after the cause is gone are not shown.
- A throughput limit (for example maximum writes per second) is modelled as slower service, not as a separate rate limiter.
- A caller’s timeout counts the mean time its dependencies take, not their full distribution.
- Latency percentiles for a whole request are estimated, over every request, including those that are rejected and fail quickly. The mean is exact, and the percentiles come from a gamma distribution that has that mean and the variance of the time spent in each component.
- The lab models the path of a query only. Crawling, building the index and keeping it fresh are in the lesson, and the load they put on the machines is not modelled.
- A query to the shards is one call to one complete copy of the index, which takes 20 ms. A real broker asks 100 machines in parallel and waits for the slowest, so the real tail of the latency is much longer than the lab’s p95 and p99; the lesson works it out.
- Each stage is shown in a steady state: the load is held and the engine says where queues build. A burst, a cold cache warming up and a failed shard are not modelled.
- The cache hit ratio is fixed at 40% and the share of queries that need the bottom tier at 30%. Real values depend on the queries people ask and on how pages are split into tiers, and they change over time.
Parameter values are illustrative. They are not benchmarks of any real product.
Stage 1, one server. One server holds the index of 50 million pages, 500 GB, and a query keeps one of its 16 slots for about 20 ms, so it answers 800 queries per second. At 500 queries per second it is at 62.5%. At twice the load, 1,000, demand is 125% of its capacity and a fifth of the queries fail.
Stage 2, copies of the whole index. A load balancer spreads the queries over 4 servers with a copy each: 3,200 queries per second, so 2,000 is 62.5%. At twice the load, 4,000, the copies are at 125%. The stage cannot go further for a different reason: the corpus is about to grow from 50 million to 5 billion pages, and 50 TB of index does not fit on any machine.
Stage 3, shards. The index is cut into 100 shards of 50 million pages, one per machine, and a broker sends each query to one copy of each shard and merges the answers. The lab keeps 8 complete copies, 800 machines, and they answer 8 × 800 = 6,400 queries per second, so the design load of 4,000 is 62.5%. At 8,000 the shards are at 125%. Compare the machines with stage 2: 800 instead of 4, for a corpus 100 times larger and no faster.
Stage 4, a results cache. A cache that answers 40% of the queries leaves 60% for the shards. At 8,000 queries per second they receive 4,800: 75%. At the stage’s design load of 6,400 they see 3,840, which is 60%. At twice that, 12,800, they receive 7,680, are at 120% and one query in ten fails.
Stage 5, tiers. The best 10% of pages, 500 million in 10 shards, form a top tier that every query visits; the other 4.5 billion pages, 90 shards, form a bottom tier that only the 30% of queries with too few results at the top visit. A query now visits 10 + 0.3 × 90 = 37 shards on average instead of 100. At the design load of 10,000 queries per second, 6,000 reach the tiers, the top tier (14 copies) is at 53.6% and the bottom tier (5 copies) at 45%, with 590 machines against 800. At twice the load the top tier is the first to run out, at 107%, and the bottom tier is at 90%.
The crawler: fetching without harm
Section titled “The crawler: fetching without harm”The crawler’s loop is short: take a URL from the frontier, fetch the page, extract its links, add the new ones to the frontier, hand the page to the index builder. Three things make it hard.
Politeness. A site must not be hit by thousands of requests at once. The crawler keeps a queue for each host and waits a delay, here assumed to be 1 second, between two requests to the same host, and it reads each site’s robots.txt, the file in which a site says which paths a crawler may not fetch. The arithmetic follows from the estimate: 1,929 fetches per second at one request per second per host means at least 1,929 different hosts being fetched at any moment. It also limits large sites. A host with 1 million pages needs 1,000,000 seconds, 11.6 days, to be fetched once at that rate, and a host cannot be refreshed monthly if it has more than 2,592,000 pages. So the crawler gives each host a budget and decides which of its pages to refresh first.
Duplicates. The same page appears under many URLs, and many pages are almost identical. The crawler normalises URLs (lower-case host, remove fragments) and compares a fingerprint of the content. For near-duplicates a technique such as the simhash fingerprints of Manku and others finds pages that differ in a few words. Without this, the index spends its disks storing the same text again and the results show the same page ten times.
Traps. A calendar with a “next month” link generates an endless supply of URLs. The defences are depth limits, the per-host budget, and skipping URLs whose content fingerprint has been seen many times.
Scheduling decides freshness. A news home page might be fetched every few minutes and a page that has not changed in a year every few months, so the 30 days is an average and not a rule.
The inverted index: answering without reading pages
Section titled “The inverted index: answering without reading pages”Scanning 5 billion pages for each query is impossible: even at 1 GB/s, 500 TB takes 500,000 seconds. The index reverses the question. For each word, it stores the sorted list of the documents that contain it, called a posting list. Take three tiny documents.
| Document | Text |
|---|---|
| 1 | red fox jumps |
| 2 | red dog |
| 3 | fox and dog |
The index is the table of words to lists: red → 1, 2; fox → 1, 3; dog → 2, 3; jumps → 1; and → 3. The query “red fox” reads two lists and keeps the documents in both: 1, 2 meets 1, 3 and gives 1. Because both lists are sorted, the intersection walks them side by side once, a cost proportional to their lengths and not to the size of the corpus. The book chapter builds the same structure step by step.
Sizes explain why queries are fast enough. A shard has 50 million documents. A word that appears in 10% of them has 5 million postings. Stored as the gaps between consecutive document numbers, which average 10 and so fit in one byte each with a variable-length encoding, that list is about 5 MB. A query reads a few lists of that order, which is why the model’s 20 ms per query on one shard is plausible and not a guess about hardware.
Indexes are built offline. The builder writes segments, files that are never modified, and merges small ones into larger ones in the background; deleting a page marks it in a list instead of changing the segment. A new segment is shipped to every copy of its shard. This is why a fresh page takes minutes or hours to appear, and why news needs a separate small index that is rebuilt often.
Ranking in stages
Section titled “Ranking in stages”Finding the pages that contain the words is the easy part; ordering them is the hard part. The score of a page mixes how well the words match (their frequency in the page against their frequency overall), signals about the page such as the links that point to it (the idea behind PageRank in the Brin and Page paper), and freshness. Computing everything for every match is too expensive, so ranking is a funnel.
- Retrieval and a cheap score, inside each shard. The shard intersects the lists and scores the matches with a fast formula, and returns its best 10.
- Merge, in the broker. 100 shards × 10 results = 1,000 candidates. The best 10 of the whole corpus are always among the best 10 of their own shard, provided every shard scores on the same scale. That needs statistics about the whole corpus (how rare a word is) to be shared with the shards, and not computed from each shard’s own pages.
- Re-ranking, on a few hundred candidates. An expensive model, with many signals, rescores the top 100. At an assumed 0.1 ms per page that is 10 ms of one core per query. At 6,000 queries per second that is 60 core-seconds every second, 60 cores, 4 machines of 16 cores. Applying the same model to all the matches in a shard, 5 million pages at 0.1 ms, would take 500 seconds per query per shard.
The funnel buys speed and costs recall: a page that the cheap score puts at rank 11 in its shard is never seen by the expensive model, however good it would have scored.
Sharding the index, and what copies are for
Section titled “Sharding the index, and what copies are for”There are two ways to cut an index. In a document-partitioned index each shard holds the complete index of its own subset of pages, as in the lab. Any query must go to all the shards, since any shard may hold a match. In a term-partitioned index each shard holds the lists of some words, so a query goes only to the shards that hold its words, but long lists must travel across the network to be intersected, and the shards that hold common words are far busier than the others. The book’s chapter on distributed indexing notes that most large search engines prefer a document-partitioned index. The lab uses it.
That choice has a consequence that stage 3 shows in numbers. Every query visits every shard, so adding shards does not add capacity: a copy of the 100 shards answers 800 queries per second whether the corpus is 50 million pages or 5 billion. Shards give size; copies give throughput. This is the difference between partitioning and replication, seen in one design. The cost of that fan-out is in the next section.
What happens if one shard is slow
Section titled “What happens if one shard is slow”A query is as slow as the slowest of the 100 shards it waits for. Suppose each shard answers within 100 ms for 99 queries in 100 and is slower for the other one. A query meets at least one slow shard with probability 1 − 0.99^100 = 63%. The rare slowness of one machine (a disk busy with a merge, a pause for memory cleaning) becomes the usual experience of a query. This is the central example of The Tail at Scale, and the lab does not show it: its latencies come from one call, and the model notes say so.
The remedy in that paper is the hedged request. The broker sends the query to one copy of the shard; if no answer has arrived after a delay, set to the 95th percentile of the latency, it sends the same query to another copy and uses the first answer. If the two copies are slow independently, each with probability 1 in 100, a shard is slow for 1 query in 10,000, and a query meets a slow shard 1 − 0.9999^100 = 1.0% of the time instead of 63%. The cost is about 5% more requests, those sent after the delay. It works because there are copies; the stage that added them for throughput is also what makes the remedy possible.
When a shard has no copy that answers, the broker has two honest choices. It can fail the query, or it can answer from the other 99 shards, so that 1% of the corpus is missing and the user may not notice. Search nearly always chooses the second, with a deadline: answer with what has arrived by 200 ms.
What happens if the results cache is lost
Section titled “What happens if the results cache is lost”At the design load of stage 4, 6,400 queries per second, the shards see 3,840 with the cache. If the cache is empty after a restart, all 6,400 arrive, and the 8 copies of the shards are at exactly 100% of their 6,400: no headroom, the queues grow, and the tail from the previous section gets longer. Losing the cache is survivable here only because the stage was sized so that the shards alone can just carry its design load; at 12,800 queries per second the same loss would put them at twice their limit. The question to ask of any cache is what the origin does without it (the cache failure lesson does the same sum). A cache that restarts is also cold, so it is better to refill it gradually than to send it the full load at once.
What happens if the index is old
Section titled “What happens if the index is old”The index is a photograph of the web at the time it was built. A page that changed an hour ago is searched under its old words until its new segment is shipped, and a page that was deleted can still be returned. The results cache adds its own delay: entries last a few minutes. For most queries that is acceptable. For news it is not, and the usual answer is a second, small index of recent pages that is rebuilt in minutes and consulted next to the large one. That adds a shard group to every query, which is a cost in machines and in latency.
Trade-offs
Section titled “Trade-offs”| Decision | What you gain | What you pay | When to choose otherwise |
|---|---|---|---|
| Document-partitioned index | Any shard is complete for its pages; a lost shard loses a slice, not a word | Every query visits every shard, so a slow shard slows the query | Few, very large words with small lists: a term-partitioned index sends a query to fewer machines |
| Copies of the shards for throughput | More queries per second, and a second copy to ask when one is slow | Machines: each copy is 100 machines | Low traffic and a large corpus: one copy, and a longer queue |
| Results cache | 40% of the queries never reach the shards (800 machines instead of 1,300) | Results a few minutes old; a cold start is dangerous | Queries that rarely repeat, or results that must be current |
| Index tiers | 590 machines instead of 800 in the lab; 37 shards visited on average instead of 100 | A page in the bottom tier can be found late or missed; deciding who is in the top tier is its own problem | A corpus where every page is equally likely to be the answer |
| Re-ranking a few hundred candidates | The expensive model runs on 100 pages, not millions | A good page ranked 11th in its shard is never seen | A small corpus, where the expensive model can score everything |
Defend your design
Section titled “Defend your design”An interviewer asks you to design a search engine. The weak answers say “a big database with a full-text index”. A good answer gives the crawl and index numbers, builds an inverted index, splits it by document and says that this gives size and not speed, and names the price of fan-out. Write your answer first.
Interview question
Writing and reviewing an answer needs JavaScript.
The interviewer asks
Design a web search engine: it gathers pages from the web, builds an index and answers a query in well under a second. Walk through the pieces and the numbers.
Assume 5 billion pages of about 100 KB, each fetched again every 30 days, 10,000 queries per second at the peak, and machines that hold 500 GB of index and answer 800 queries per second for a shard of 50 million pages.
Write your answer first. The strong answer unlocks once you have written a real attempt.
0 of 100 characters written to unlock the strong answer
- 5 billion pages fetched every 30 days is about 1,900 pages per second, 190 MB/s. The index is about 50 TB, so 100 shards of 500 GB, and a machine answers 800 queries per second.
- A crawler keeps a queue per host, waits between requests to a host, obeys robots.txt, removes duplicates and limits traps. At one request per second per host, 1,929 fetches per second needs at least 1,929 hosts at a time.
- An inverted index lists, for each word, the sorted documents that contain it; a query with several words intersects the lists. It is built in segments that are never modified.
- Ranking is a funnel: a cheap score in each shard, a merge of 1,000 candidates, then an expensive model on 100. The expensive model on 100 pages is 10 ms per query; on 5 million it would be 500 seconds.
- Shards give size and copies give throughput: 8 copies of 100 shards answer 6,400 queries per second, and the lab’s 800 machines are 590 once the index is in two tiers and 40% of the queries are answered by a cache.
- Fan-out makes a query as slow as its slowest shard: 63% of queries meet a slow shard when one in 100 is slow. A hedged request to a second copy brings that to 1.0% for about 5% more requests.
Next: Object storage, which keeps data for years by copying or encoding it across disks.
Your progress
Built by GhaziAlibi.
© ShardCraft. All rights reserved.