Core Concept

Search and Inverted Index Fundamentals

Search engines turn text into terms, store which documents contain each term in sorted postings lists, and rank matches with BM25. Immutable segments, document sharding, scatter-gather, and a two-stage ranker are the pieces every search design reuses.


1. What It Is

Users type a few words and expect the best documents back in well under a second. A database scan with LIKE '%word%' reads every row and cannot rank, so search engines flip the data around. An inverted index records, for every term, which documents contain it, so a query touches only the lists for its own terms.

What:

A search index built by analyzing text into terms and storing, for each term, a postings list of document ids in ascending order, usually with term frequency and positions. A scoring function, most often BM25, orders the matches.

Primary purpose:

Find and rank the few relevant documents among millions or billions without scanning the corpus, at interactive latency.

Usually used for:

Web and product search, log and event search, typeahead suggestions, and the keyword leg of hybrid retrieval next to vector search.

2. Core Mental Model

Picture the index at the back of a textbook. A search engine builds that index for every field of every document, then answers a query by looking up each query term and combining the lists.

πŸ”€ Analyze

Text becomes terms through tokenizing, lowercasing, optional stop word removal, and stemming. The same chain must run at index time and at query time, or the terms never match.

πŸ“‡ Invert

Store term to documents instead of document to words. Postings are sorted by doc id, so AND, OR, and phrase queries become linear merges of sorted lists.

πŸ† Score, then re-rank

BM25 scores candidates cheaply across the whole index. A heavier model re-ranks only the top few hundred or thousand, which keeps latency and cost bounded.

In the room

Say that the search index is a derived read model and the database stays the system of record. Then name the pipeline in order: analyze, merge postings, score with BM25, re-rank the top K. Close with how you shard (by document), how you stay fresh (immutable segments plus a refresh interval), and what you accept (fan-out tail latency and results that are a few seconds stale).

3. Why It Matters in HLD

Search is the read path where a plain index lookup is not enough, because users expect ranked answers over free text. Three lenses:

Needed When:

Users search free text over millions or billions of documents, relevance order matters, and the latency budget is 50 to 200 ms. Typeahead, product search, log search, and RAG retrieval all qualify.

Avoids:

Full scans and LIKE queries on the primary database, ranking by recency alone, and search load interfering with transactional traffic.

Optimizes For:

Read latency and relevance. The price is index work at write time, extra storage (the Log Aggregation problem illustrates a full text index of about 1.5x to 2x the raw log volume), and results that lag by a refresh interval.

4. Architecture & Data Flow

Walk the system as interview steps. Step 1 (analyze): run documents and queries through the same analyzer chain. Step 2 (index): write postings (doc id, term frequency, positions) into an in-memory buffer, and turn it into a new immutable segment on every refresh. Step 3 (retrieve): look up each query term and merge the sorted postings lists, rarest term first. Step 4 (score): rank candidates with BM25 using corpus-wide term statistics. Step 5 (scatter-gather): repeat per shard, merge the local top K at a coordinator, and pass roughly the top 1,000 to a re-ranker. Step 6 (fetch): load titles and snippets for only the final 10.

Loading...

In the room

Draw a four-document corpus like this one on the whiteboard, because it answers the probes before they are asked. Expect these next: why AND is a linear merge, how a phrase query uses positions, what happens when a document is updated, why p99 is much worse than p50 once you fan out, and why you did not shard by term.

5. Key Characteristics

Four things set search behavior: the analyzer chain, the postings structure, the cost of merging lists, and the scoring formula. Start with the analyzer, because a mismatch between index time and query time silently loses results:

StepWhat it doesExampleWatch out for
1. TokenizeSplits text into tokens at whitespace, punctuation, or language rulesThe Foxes are Running becomes The, Foxes, are, RunningChinese and Japanese are written without spaces between words, and Korean words carry many attached endings, so these languages need a dictionary based or n-gram tokenizer
2. LowercaseFolds case, and often accents, so Fox matches foxThe, Foxes, are, Running becomes the, foxes, are, runningFolding is lossy, so exact-case search needs a second field
3. Stop wordsDrops very common words such as the, a, and isthe, foxes, are, running becomes foxes, runningBreaks phrases such as "to be or not to be", so many engines keep stop words and let IDF down-weight them
4. StemCuts words to a root using suffix rulesfoxes, running becomes fox, runRules are crude. The Porter stemmer maps both universe and university to univers, and it turns lazy into lazi, which is not a word. Lemmatization uses a dictionary and is slower but more precise
  • Postings content: each posting stores a doc id, a term frequency for scoring, and optionally positions for phrase and proximity queries. Positions make the index larger, so engines let you keep them only for the fields that need phrases. Doc ids are stored as gaps and compressed, so the ids 1, 5, 15, 22 become the gaps 1, 4, 10, 7, which is why the Search Engine problem quotes a 5x to 10x smaller index.
  • AND, OR, and phrase queries are merges of sorted lists. AND is a two-pointer intersection that costs O(m + n) for lists of m and n entries, so start from the rarest term (smallest df) and probe the longer lists against it. OR is a union. A phrase query runs AND first and then checks positions, as the diagram shows.
  • Skip pointers let an intersection jump ahead in a long list. A common rule is one pointer about every sqrt(n) postings for a list of n entries, so a rare term with 3 postings probing a common term with 1,000,000 postings needs at most about 1,000 skip hops plus short walks of up to 1,000 postings each, a few thousand steps instead of a million. Block-Max WAND applies the same idea to scored OR queries by skipping blocks whose best possible score cannot beat the current top K.

Scoring: TF-IDF versus BM25

TF-IDF scores tf x ln(N / df). Rare terms weigh more through IDF, but the score grows linearly with term frequency, so a page that repeats a word 100 times scores 10 times a page that says it 10 times, which rewards keyword stuffing. BM25 fixes this with saturation and length normalization:

score(D, Q) = sum over each query term t of
              IDF(t) x tf x (k1 + 1) / ( tf + k1 x (1 - b + b x |D| / avgdl) )

IDF(t) = ln( 1 + (N - df + 0.5) / (df + 0.5) )

tf    occurrences of t in document D      |D|    length of D in terms
df    documents that contain t            avgdl  average document length
N     documents in the corpus             k1 = 1.2 and b = 0.75 are the usual defaults

The parameter k1 sets saturation, because the tf factor approaches k1 + 1 = 2.2 and never exceeds it, so each extra occurrence helps less. The parameter b sets length normalization, where b = 0 ignores document length and b = 1 normalizes fully, so a longer document needs more occurrences to score the same. This IDF is the Lucene form with the +1 inside the log, which keeps it non-negative. The classic form written in the Search Engine problem omits the +1 and goes negative for a term that appears in more than half of the documents. The formula above is the textbook one with the constant (k1 + 1) in the numerator. Lucene 8 and later, and therefore Elasticsearch 7 and later, drop that constant, which divides every score here by 2.2 without changing the order, so the score an engine reports is smaller than the numbers below while the ranking agrees.

Worked example on the diagram corpus

Take the query brown dog over the four documents in the diagram, with N = 4, lengths 3, 5, 3, 3, and so avgdl = 14 / 4 = 3.5.

IDF(brown) = ln(1 + (4 - 3 + 0.5) / (3 + 0.5)) = ln(1.4286) = 0.3567     (df = 3)
IDF(dog)   = ln(1 + (4 - 2 + 0.5) / (2 + 0.5)) = ln(2.0)    = 0.6931     (df = 2)

length term for |D| = 3:  1.2 x (0.25 + 0.75 x 3 / 3.5) = 1.2 x 0.89286 = 1.0714
length term for |D| = 5:  1.2 x (0.25 + 0.75 x 5 / 3.5) = 1.2 x 1.32143 = 1.5857
tf factor = tf x 2.2 / (tf + length term)

D4 (length 3): brown 1 x 2.2 / (1 + 1.0714) = 1.0621, dog 1.0621
               score = (0.3567 + 0.6931) x 1.0621 = 1.115
D2 (length 5): brown 2 x 2.2 / (2 + 1.5857) = 1.2271, dog 1 x 2.2 / (1 + 1.5857) = 0.8508
               score = 0.3567 x 1.2271 + 0.6931 x 0.8508 = 0.4377 + 0.5897 = 1.027
D1 (length 3): brown only, score = 0.3567 x 1.0621 = 0.379
DocLengthbrown factordog factorScoreWhy
D4 old brown dog31.062 (tf 1)1.062 (tf 1)1.115Short document that contains both terms
D2 brown dog chase brown fox51.227 (tf 2)0.851 (tf 1)1.027brown twice, but longer than average, so every factor is discounted
D1 quick brown fox31.062 (tf 1)none0.379Misses dog, the term with the larger IDF

D2 mentions brown twice and still loses to D4, for two separate reasons. First, saturation: inside D2 the second occurrence lifts the brown factor from 0.851 (what a single occurrence earns at length 5, as the dog factor shows) to 1.227, which is 44 percent more (1.227 / 0.851 = 1.442) where TF-IDF would have doubled it. Second, length: D2 is longer than average, and its length term of 1.586 against 1.071 discounts every factor, so D2's brown factor ends up only 15.5 percent above D4's 1.062 (1.227 / 1.062 = 1.155) and its dog factor falls below D4's. With k1 = 1.2 no term can contribute more than IDF x 2.2, so brown tops out at 0.357 x 2.2 = 0.785 however often it repeats.

6. Strategic Tradeoffs

A search index buys read speed with write and operational cost, so state both sides:

BenefitCost
Fast ranked retrieval (postings are precomputed, so a query reads only the lists for its own terms instead of scanning documents)Write amplification and storage (every document is analyzed and indexed on ingest, positions add size, and merges rewrite data)
Lock-free reads and compact files (immutable segments compress well, cache well, and need no in-place edits)Deletes and updates are tombstones (space returns only at merge, and many small segments slow every query)
Near real time visibility (a refresh makes buffered writes searchable within about a second)No read-your-writes (a document is invisible until the next refresh, and short intervals create more segments and merge work)
Two-stage ranking (a cheap BM25 pass bounds the work an expensive model must do)Recall ceiling (the re-ranker can only reorder what stage 1 returned, so a missed candidate is gone for good)

Document partitioned versus term partitioned

The sharding choice is the one the interviewer will press on, so know both layouts and the verdict:

DimensionDocument partitioned (local index)Term partitioned (global index)
Where a postings list livesEvery shard holds a complete index over its own slice of the documentsEach term's whole postings list lives on one shard
Query fan-outEvery shard is queried, so fan-out equals the shard countOnly the shards that own the query terms, so a short query touches few shards
Multi-term ANDEach shard intersects locally and only its top K hits cross the networkLong postings lists must be shipped between shards before they can be intersected
Indexing one documentOne shard, one write pathTouches every shard that owns one of its terms
Hot termsA popular term is spread across all shards, so load stays evenA popular term lands on one shard and creates a hot spot
Losing a shardA slice of the documents disappears and other results still returnEvery query that needs a term on that shard fails or loses that term

Document partitioning wins because writes stay on one shard, load is even, a failed shard degrades recall gently, and only top K hits cross the network. Its cost is that every query pays the full fan-out, which Section 7 turns into a tail latency problem. Term partitioning looks attractive because a short query contacts few shards, but it ships long postings lists between nodes and concentrates popular terms on single shards. That is why the Search Engine problem treats document sharding as the industry standard. Replicas then add availability and read throughput, because a query uses one copy of each shard.

7. Failure / Bottleneck Awareness

Fan-out, merge pressure, hot terms, and drift between the index and the source of truth are the usual failures, so we volunteer the mitigations:

🐌 Scatter-gather tail latency

Problem: A query finishes only when its slowest shard answers. If each shard is slow on 1 percent of requests, the chance that at least one of n shards is slow is 1 minus 0.99 to the power n, which is 1 percent for 1 shard, about 9.6 percent for 10 shards, and about 63 percent for 100 shards (0.99 to the power 100 is about 0.366, so 1 minus 0.366 is 0.634). The tail you see is the tail of the slowest shard.

Mitigation: Hedge by sending the same request to a second replica after about 30 ms (the Search Engine problem value) and keeping the first answer. Only requests slower than the delay are duplicated, so the extra load is small, about 5 percent in that problem. Choose replicas by observed latency and queue depth, set a deadline, and return partial results from, say, 95 of 100 shards only when the product accepts lower recall. Keep shards few and large (10 to 50 GB in the Elasticsearch problem) because every shard adds fan-out, and cache popular queries at the coordinator.

🧱 Segment explosion and merge storms

Problem: Refreshing every second under a heavy bulk load creates thousands of tiny segments. Every query must search each one, and background merges compete with indexing and queries for disk I/O.

Mitigation: Batch bulk writes, raise the refresh interval to about 30 seconds during backfills as the Elasticsearch problem does, throttle merges, and force-merge indices that are read-only. If a merge corrupts a shard, restore from a replica and replay the indexing events, which is the incident the Search Engine problem walks through.

πŸ”₯ Hot terms and deep pagination

Problem: A viral query makes the same long postings lists the hottest data on every shard. Separately, asking for page 1,000 forces every shard to return its top from + size hits, and the coordinator must sort all of them.

Mitigation: Cache exact-query results and keep hot postings in memory. Cap the result window (10,000 hits by default in Elasticsearch) and page through deep results with search_after and a stable sort instead of offsets.

🧭 Index drift and incomparable scores

Problem: Three silent failures. The query analyzer differs from the index analyzer, so terms never match. The index diverges from the source of truth after missed or replayed events, or a deleted document stays searchable until the next refresh. Each shard computes IDF from its own documents, so scores from small or skewed shards are not comparable.

Mitigation: Version the analyzer with the index and test a round trip. Feed the index from a change log with idempotent, version-gated upserts (see Idempotency & Exactly-Once Effects) and rebuild by replay. Precompute global IDF offline as the Search Engine problem does, or run a statistics pre-phase, which Elasticsearch offers as the dfs_query_then_fetch search type at the price of an extra round trip to every shard (the default query_then_fetch scores with each shard's local statistics). Re-check permissions against the source of truth at fetch time when stale visibility is unacceptable.

Classic mistakes

Proposing LIKE '%word%' on the main database, choosing term partitioning because only the relevant shards are hit, treating the search index as the system of record, forgetting that a refresh delays visibility, comparing raw BM25 scores across shards with different statistics, and running a cross-encoder over the whole corpus instead of the top few hundred candidates.

8. Common HLD Usage

Seven problems on this site lean on these fundamentals, and each one stresses a different piece:

ProblemHow it uses search fundamentalsNumbers worth quoting
Search EngineA document-sharded inverted index with BM25 retrieval and an ML re-ranker. Global IDF keeps shard scores comparable, and hedged requests tame the tail.100 shards per tier, top 1,000 to the re-ranker, hedge after about 30 ms
Typeahead AutocompleteA prefix lookup that skips the inverted index. A trie caches the top suggestions at every node, and immutable snapshots keep serving lock-free.Under 50 ms p99, top 10 per node, hourly rebuild plus a 5 minute trending overlay
Log Aggregation & SearchChooses between a full inverted index on message text (Elasticsearch) and a labels-only index that scans compressed chunks (Loki).Full text index of about 1.5x to 2x the log volume as an illustrative assumption
Elasticsearch Search ClusterOperates the engine itself: Lucene segments, refresh versus translog durability, shard sizing, routing, and query-then-fetch scatter-gather.About 40 GB per primary, 1,250 primaries for 50 TB, 1 s refresh and 30 s for backfills
Search Ranking (Learning to Rank)Stage 2 of the funnel. Hybrid BM25 and ANN retrieval builds a candidate pool, then LambdaMART and a cross-encoder narrow it to the final page.10K candidates, 500 for the cross-encoder, Recall@10K for stage 1 and NDCG@10 for stage 2
Vector Database & Semantic SearchThe dense leg of hybrid search. Elasticsearch supplies the sparse BM25 leg and Reciprocal Rank Fusion merges the two ranked lists.RRF with k = 60, about 20 ms added by running both legs
Web CrawlerThe upstream feed. Crawled pages land in object storage and a page-crawled event tells the indexer to update postings at least once.SimHash with Hamming distance 3 or less keeps near duplicates out of the index

9. Decision Signals

Pick the retrieval structure from the shape of the query, then pick the scale and freshness knobs. This table is the answer to why this design:

SituationReach forWhy
Free text, keywords, ranked resultsInverted index with BM25Postings merge cheaply, and BM25 handles frequency and length
Identifiers, SKUs, error codes, namesLexical match on an exact or keyword fieldEmbeddings blur exact tokens, while an inverted index matches them exactly
Paraphrases and natural language questionsDense vectors with ANNMeaning matches without shared words, at the cost of approximate recall
Exact tokens and meaning both matterHybrid, fused with Reciprocal Rank FusionRank-based fusion needs no score normalization, and k = 60 is the common default
Suggestions on every keystroke under 50 msTrie with top K per node, or edge n-gramsO(prefix length) lookup with no subtree scan
Known labels, huge volume, cost mattersLabels-only index that scans chunksSkips indexing every word and trades away speed on broad text queries
Relevance plateaus with BM25 aloneRe-ranker on the top K candidatesSpends the heavy model on 1,000 documents instead of billions
The index fits on one nodeOne shard with replicasNo fan-out, so add shards only when size or QPS demands it
Transactions or read-your-writes requiredKeep the system of record in a databaseA search index is eventually consistent by design
🎯 Reach for a search engine when:
  • Users search free text and expect ranked results rather than filtered rows.
  • Scanning is out of the question because the corpus is large or the latency budget is under 200 ms.
  • The product needs phrases, highlighting, facets, or typo tolerance, which come with the engine.
  • Candidates exceed one model budget, so a cheap stage 1 must feed a heavier stage 2.
⏭️ Skip it when:
  • Lookups are by key, equality, or range, where a B-tree from Indexing and Query Optimization is simpler and exact.
  • The data is small and the database built-in full text search is good enough.
  • You need transactions or immediate read-your-writes, which a refresh-based index cannot give.

In the room

Say the rule out loud: lexical for exact tokens, vectors for meaning, hybrid when both matter, and a re-ranker only after stage 1 recall has been measured. Then give the sharding verdict in one sentence, which is document partitioned with replicas, because writes stay local and only the tail latency grows.

11. Deep Dive (Optional)

Segments, refresh, and why deletes are tombstones

Loading...

Lucene-style engines never edit a segment after writing it. A write goes into an in-memory buffer and is appended to a translog. A refresh writes the buffer out as a new small segment and opens it for search, so visibility lags by the refresh interval, which defaults to 1 second in Elasticsearch. The translog is what lets an acknowledged write survive a crash, so durability and visibility are separate events, as the Elasticsearch Search Cluster problem explains.

Immutability is what makes postings compressible, memory-mappable, and safe to read without locks. It also explains tombstones. Removing one doc id from a compressed, gap-encoded postings list would mean rewriting the whole list, so the engine flips a bit in the segment live-docs bitmap and filters those hits at query time. An update is a delete plus an insert. A background merge picks segments of similar size, copies only the live documents into one bigger segment, and then drops the old ones, which is when deleted space is finally reclaimed. Merging also bounds the segment count, because every query must visit every segment. The cost is write amplification, since the same document is rewritten each time its segment is merged.

Query then fetch, replicas, and the two-stage funnel

Loading...

In the query phase the coordinator asks one replica of each shard for its local top K as doc id and score pairs only, then merges the sorted lists with a priority queue. Picking 1,000 results from 100 lists costs about 1,000 x log2(100) = 6,644 comparisons, which the Search Engine problem rounds to 7,000. In the fetch phase it asks only the owning shards for titles and snippets of the final 10, which keeps large payloads off the wire for the other 990 candidates. Replicas raise capacity and availability but do not shorten one query, while more shards shorten per-shard work and raise fan-out. The capacity math multiplies the two, so 20K QPS across 1,250 shards is 25 million shard queries per second in the worst case, which is why routing and avoiding oversharding matter.

Stage 1 must be cheap and recall oriented (BM25, Block-Max WAND pruning, or hybrid BM25 plus ANN) because it runs over the whole corpus. Stage 2 is precision oriented and can use features and models that would be impossible at corpus scale, such as LambdaMART over 200 or more features and optionally a cross-encoder on a few hundred candidates. The arithmetic forces the funnel, because even after narrowing to 500 candidates, 100K QPS means 50 million model evaluations per second. Measure stage 1 with Recall@K and stage 2 with NDCG@10, and keep a BM25 fallback for when the re-ranker is down. The Search Engine problem uses a 1,000 candidate funnel, and Search Ranking (Learning to Rank) uses a 10K pool narrowed to 500, but the shape is the same.

Prefix and typeahead structures

StructureHow a prefix lookup worksFit
Trie with top K per nodeWalk one node per character and return the cached top K listHighest QPS and tightest latency, but costs memory and needs rebuilds to absorb new frequencies
Sorted term dictionary with an FST indexA prefix is a contiguous range of a sorted dictionary, so find the range and union its postingsBuilt into the engine, but a one or two letter prefix expands to a huge number of terms
Edge n-grams in the inverted indexIndex sys, syst, syste, system as terms so a prefix is an ordinary term lookupReuses the search stack and ranking, but the index grows with every n-gram length
Reversed terms or n-gramsA leading wildcard cannot use a sorted dictionary, so index reversed terms or grams to match the end of a wordCostly, so bound such queries by time range and result limits

Lucene keeps its sorted term dictionary on disk in blocks of terms that share a prefix, and holds a finite state transducer (FST) in memory as the index into those blocks. The FST maps a term prefix to the block that holds every term starting with it and shares common prefixes and suffixes, so it stays compact and a prefix lookup jumps straight to the right range of terms. The decision rule is about the budget. If suggestions must return in under 50 ms at hundreds of thousands of requests per second, build a dedicated trie with the top K precomputed at each node, as Typeahead Autocomplete does. If the corpus is modest and you already run a search engine, edge n-grams on a suggest field are the cheaper operational choice.

Lexical, vector, and hybrid search

AspectLexical (inverted index)Vector (ANN)
Matches onExact analyzed termsCloseness of embeddings in vector space
Strong atSKUs, error codes, names, rare words, and explainable scoresParaphrase, vocabulary mismatch, and question answering
Weak atSynonyms and paraphrase unless you add themExact tokens and identifiers, and hard to explain
CostCheap CPU and disk, no model to runAn embedding model plus an ANN index that is memory heavy
Result qualityExact within the analyzed termsApproximate, with recall below 100 percent by design

Hybrid retrieval runs both retrievers in parallel and fuses the two ranked lists. BM25 scores are unbounded while cosine similarity lives in a narrow range, so adding raw scores is fragile. Reciprocal Rank Fusion uses ranks only, with k = 60 as the common default.

RRF score(d) = sum over retrievers of 1 / (k + rank of d in that retriever), with k = 60

doc A: rank 2 in BM25, rank 1 in the dense list    1/62 + 1/61 = 0.0161 + 0.0164 = 0.0325
doc B: rank 1 in BM25, absent from the dense list  1/61 = 0.0164

Doc A wins because both retrievers like it, even though doc B tops the BM25 list. Hybrid costs about 20 ms of extra latency in the Vector Database & Semantic Search problem and means keeping two indexes in sync with the source of truth. Use it when queries mix identifiers and concepts, and skip it when one side clearly covers the workload. The dense side is explained in Vector Embeddings & ANN Search.

πŸ’¬Review

Help Us Improve

How helpful was this walkthrough?

Click a star to rate. We actively use this feedback to refine and update our system design content.

Placeholder
Optional but highly appreciated!

Discussion

Share your thoughts, ask questions, or help others.

Loading comments...