System design interview: design a search engine
A search engine turns a pile of crawled documents into an index that can answer a query in a fraction of a second, then orders the matches so the most useful ones come first. The interview centers on the inverted index (how it is built and split across machines), on serving a query by fanning out to every shard and merging their best results, and on ranking in stages so expensive scoring only touches a short list.
By Evin JohnPublished 7 min read
1. Clarify the requirements
"Design Google search" can swallow the whole hour. Agree that crawling is a given (the web crawler walk-through covers it) and that typeahead suggestions are separate (see search autocomplete). What remains is indexing, serving and ranking.
- Functional: accept a text query, return the ten best results with title, URL and snippet; support phrases and simple filters (language, site, date); paginate.
- Non-functional: results in well under a second end to end; new or updated pages searchable within hours, breaking news within minutes; the index survives machine failures; relevance is good enough to measure and improve.
- Out of scope unless asked: ads, images and video search, knowledge panels, personalization, spam detection beyond a mention.
2. Estimate the scale
| Quantity | Assumption | Result |
|---|---|---|
| Documents | 5 billion pages in the main index | the base for every other line |
| Text | about 20 KB of extracted text per page | about 100 TB of text |
| Index size | compressed inverted index around 30% of the text (assumed) | about 30 TB, before replicas |
| Shards | 1,000 shards | 5 million documents and about 30 GB of index each, which fits in memory on one server |
| Queries | 1 billion a day | about 11,600 a second on average, about 23,000 at peak |
With every query touching every shard, 23,000 queries a second means each shard server receives that full rate too. You scale throughput by adding replicas of each shard, and you scale index size by adding shards. Keeping those two axes separate is the key capacity point.
3. Define the API
GET /v1/search?q=solar+panel+efficiency&lang=en&page=1
-> 200 { results: [{ url, title, snippet, docId }], total: "about 2,400,000", tookMs }
internal: POST /shard/{n}/query { terms[], filters, k: 200 } -> { hits: [{ docId, score, features }] }4. Sketch the data model
| Structure | Contents | Why |
|---|---|---|
| Term dictionary | Every term in the shard, with a pointer to its posting list and its document frequency | Find a term's list fast; document frequency feeds scoring |
| Posting lists | For each term, sorted document IDs, term frequencies and (optionally) positions | Sorted IDs compress well (store gaps) and allow fast intersection; positions enable phrase queries |
| Document store | Per document: URL, title, length, language, quality signals, stored text for snippets | Scoring inputs and result rendering |
| Link and quality data | Precomputed per document scores such as link-based authority | Query-independent ranking signal |
5. Build the index
- ParseExtract text, title, headings and anchor text from links pointing to the page; drop boilerplate; detect language.
- NormalizeTokenize, lowercase, fold accents, and optionally stem ("running" to "run"). Index both raw and stemmed forms if you want exact matches to score higher.
- InvertFor a batch of documents, emit (term, docId, frequency, positions) and sort by term. Each batch becomes an immutable index segment.
- Merge and publishMerge small segments into larger ones in the background; ship finished segments to shard servers, which swap them in without downtime.
Immutable segments are the trick that makes updates manageable. A changed page is added to a new segment and its old copy is marked deleted; merges later drop the deleted entries. Search engine libraries such as Lucene work this way.
6. Serve a query
A query arrives at a front-end, which checks a result cache, rewrites the query (spelling correction, synonyms), and sends it to one replica of every shard. Each shard finds matching documents, scores them cheaply and returns its best few hundred. The front-end merges these lists, runs the expensive ranker on the merged top set, fetches snippets and returns ten results.
from bisect import bisect_left
def gallop(postings, target, lo):
"""First index >= lo whose doc id is >= target, probing 1, 2, 4, 8... ahead."""
step, hi = 1, lo
while hi < len(postings) and postings[hi] < target:
lo, hi, step = hi + 1, hi + step, step * 2
return bisect_left(postings, target, lo, min(hi + 1, len(postings)))
def intersect(lists):
"""Doc ids present in every sorted posting list (an AND query)."""
if not lists:
return []
lists = sorted(lists, key=len) # drive from the rarest term
result = []
pos = [0] * len(lists)
for doc in lists[0]:
for i in range(1, len(lists)):
pos[i] = gallop(lists[i], doc, pos[i])
if pos[i] == len(lists[i]):
return result
if lists[i][pos[i]] != doc:
break
else:
result.append(doc)
return result
intersect([[2, 7, 9, 40], [1, 2, 3, 9, 10, 40, 41], [9, 40, 99]]) # [9, 40]Starting from the shortest list matters: a query for "the solar inverter" walks the few thousand "inverter" documents and skips through the huge "the" list, instead of the other way round. Real engines also stop early once enough high-scoring documents are found, using per-list score bounds (techniques such as WAND).
7. Rank in stages
| Stage | Runs on | Signals |
|---|---|---|
| Match and cheap score | Every matching document in each shard | BM25 (term frequency, rarity of the term, document length), title and anchor-text matches, static quality score |
| Shard top-k | A few hundred per shard | Keep the best by cheap score; return features for them |
| Learned ranker | The merged top few hundred | A model trained on human relevance ratings and click behavior, using many features: proximity of query terms, freshness, language match, page quality |
| Final adjustments | The top results | Remove duplicates, limit results per site, mix in fresh news results when the query is about an event |
8. The architecture
- Offline
- Crawled document store
- Parse and normalize
- Segment builder and merger
- Fresh path
- Real-time indexer
- Fresh index (minutes old)
- Index serving
- Shard servers (1,000 shards x replicas)
- Static quality scores
- Query path
- Load balancer
- Front-ends and query rewriting
- Result cache
- Ranking
- Merger (top-k)
- Learned ranker
- Snippet service
9. What breaks, and trade-offs to discuss
| Failure | Effect | Mitigation |
|---|---|---|
| One shard replica is slow | Every query waits for the slowest shard (tail latency) | Send a hedged request to a second replica after a short delay; answer without a shard that misses the deadline |
| Bad index build | Relevance drops or results disappear | Validate segments against test queries before publishing; keep the previous version for rollback |
| Breaking news | Main index is hours old | Fresh index rebuilt every few minutes, merged at query time |
| Query spike on one topic | Repeated identical queries | Result cache keyed by normalized query, with a short TTL for news-like queries |
- Partition by document or by term. Document partitioning sends each query to every shard but keeps each shard self-contained and balanced. Term partitioning sends a query to fewer machines, but popular terms create hot shards and multi-term queries need cross-machine joins. Most large systems partition by document.
- Freshness or efficiency. Rebuilding segments often keeps the index current but costs compute; a separate fresh tier gets most of the benefit.
- Complete or fast answers. Returning results without a slow shard loses a few matches but protects latency for everyone.
- Cache hit rate or freshness. Long cache lifetimes save compute but show stale results for fast-moving queries.
Smaller versions of the same machinery show up elsewhere. An email product keeps a separate index per mailbox (see design an email service), and a news aggregator indexes only recent articles. The ranking stages mirror those of a recommendation system, with a query in place of a user.
10. How to talk through it in the interview
Fictional example
- Interviewer
- Every query hits all thousand shards? That sounds wasteful.
- Candidate
- It is more machines per query, but each shard does a small, predictable amount of work on an in-memory index, and the shards are balanced because documents are spread evenly. With term partitioning, a query for a common word would land on one hot machine, and multi-word queries would need to move posting lists between machines.
- Interviewer
- What about the slowest of the thousand?
- Candidate
- That is the real cost, so I would hedge: if a shard has not answered in, say, the 95th percentile time, send the same request to another replica and take whichever returns first.
- Draw the posting list and say "sorted document IDs, compressed as gaps".
- Name both scaling axes: shards for size, replicas for query rate.
- Explain ranking as a funnel, cheap to expensive, with a number at each stage.
Practicing this design with Natively
Search engines invite deep follow-ups on data structures, so rehearse explaining posting lists and fan-out without notes. During a practice call, Natively keeps a running transcript on your Mac or Windows computer and can propose points for the latest question, for instance tail latency across shards. If you sketch the index layout, a screenshot lets you ask it to describe what the drawing shows and what it is missing. The kept transcript makes it easy to compare your explanation of ranking stages from one session to the next.
Questions people ask
How do you design a search engine in a system design interview?
Treat crawling as given. Build an inverted index offline in immutable segments, split it across shards by document, and replicate each shard. At query time, fan out to one replica of every shard, let each return its best few hundred matches by a cheap score, merge them, and rank the top set with a learned model.
What is an inverted index?
It maps each term to a posting list: the sorted IDs of documents containing it, often with term counts and positions. A query looks up its terms and intersects or merges their lists, which is far faster than scanning documents. Sorted IDs are stored as gaps so the lists compress well.
Should a search index be partitioned by document or by term?
Most large systems partition by document. Each shard holds complete posting lists for its slice of documents, load stays balanced and shards work independently, at the cost of sending every query to every shard. Term partitioning creates hot shards for common words and needs cross-machine work for multi-term queries.
How does a search engine stay fresh?
It keeps a small index of recently crawled pages that is rebuilt every few minutes, alongside the large main index that is rebuilt and merged less often. Queries search both and merge results, and result caches use short lifetimes for news-like queries.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
