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 Published 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

Back-of-envelope estimate for a large web search engine (assumed figures)
QuantityAssumptionResult
Documents5 billion pages in the main indexthe base for every other line
Textabout 20 KB of extracted text per pageabout 100 TB of text
Index sizecompressed inverted index around 30% of the text (assumed)about 30 TB, before replicas
Shards1,000 shards5 million documents and about 30 GB of index each, which fits in memory on one server
Queries1 billion a dayabout 11,600 a second on average, about 23,000 at peak
Back-of-envelope estimate for a large web search engine (assumed figures). Scroll sideways on a small screen.

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 }] }
A single public endpoint; the internal shard call returns only document IDs and scores.

4. Sketch the data model

Index structures per shard
StructureContentsWhy
Term dictionaryEvery term in the shard, with a pointer to its posting list and its document frequencyFind a term's list fast; document frequency feeds scoring
Posting listsFor each term, sorted document IDs, term frequencies and (optionally) positionsSorted IDs compress well (store gaps) and allow fast intersection; positions enable phrase queries
Document storePer document: URL, title, length, language, quality signals, stored text for snippetsScoring inputs and result rendering
Link and quality dataPrecomputed per document scores such as link-based authorityQuery-independent ranking signal
Index structures per shard. Scroll sideways on a small screen.

5. Build the index

  1. ParseExtract text, title, headings and anchor text from links pointing to the page; drop boilerplate; detect language.
  2. NormalizeTokenize, lowercase, fold accents, and optionally stem ("running" to "run"). Index both raw and stemmed forms if you want exact matches to score higher.
  3. InvertFor a batch of documents, emit (term, docId, frequency, positions) and sort by term. Each batch becomes an immutable index segment.
  4. 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]
AND query over sorted posting lists, driven by the rarest term, with galloping search. Checked against set intersection.

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

Where each ranking signal is applied
StageRuns onSignals
Match and cheap scoreEvery matching document in each shardBM25 (term frequency, rarity of the term, document length), title and anchor-text matches, static quality score
Shard top-kA few hundred per shardKeep the best by cheap score; return features for them
Learned rankerThe merged top few hundredA model trained on human relevance ratings and click behavior, using many features: proximity of query terms, freshness, language match, page quality
Final adjustmentsThe top resultsRemove duplicates, limit results per site, mix in fresh news results when the query is about an event
Where each ranking signal is applied. Scroll sideways on a small screen.

8. The architecture

  1. Offline
    • Crawled document store
    • Parse and normalize
    • Segment builder and merger
  2. Fresh path
    • Real-time indexer
    • Fresh index (minutes old)
  3. Index serving
    • Shard servers (1,000 shards x replicas)
    • Static quality scores
  4. Query path
    • Load balancer
    • Front-ends and query rewriting
    • Result cache
  5. Ranking
    • Merger (top-k)
    • Learned ranker
    • Snippet service
Indexing pipeline and query serving. Crawled documents land in a document store. An indexing pipeline parses and normalizes them, builds immutable index segments in batches, merges them, and publishes them to shard servers. A separate real-time indexer builds a small fresh index from recently crawled pages every few minutes. Queries arrive at front-end servers behind a load balancer, which check a query result cache, rewrite the query, and fan out to one replica of every main-index shard and the fresh index. A merger combines the shard results, a ranking service re-scores the top set, and a snippet service builds the result text.

9. What breaks, and trade-offs to discuss

Failure modes worth naming
FailureEffectMitigation
One shard replica is slowEvery 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 buildRelevance drops or results disappearValidate segments against test queries before publishing; keep the previous version for rollback
Breaking newsMain index is hours oldFresh index rebuilt every few minutes, merged at query time
Query spike on one topicRepeated identical queriesResult cache keyed by normalized query, with a short TTL for news-like queries
Failure modes worth naming. Scroll sideways on a small screen.
  • 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

Defending document partitioning
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.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP