FullStack AI Hub
Studio
System Design · 03. Data & Storage
11 min
10 steps
Intermediate

Search Engines

Build sub-50ms full-text search with tokenization, inverted indexes, BM25 ranking, and sharded scatter-gather.

System Design03. Data & StorageLesson 10 of 11
11 minIntermediate10 steps

Search Engines

Build sub-50ms full-text search with tokenization, inverted indexes, BM25 ranking, and sharded scatter-gather.

SEARCH P95
2,200 ms
SQL CPU LOAD
95% pegged
RANKING
Arbitrary
TYPO SUPPORT
None
O(N) LIKE scan"wireless..."Search API74%LIKE "%...%"Primary SQL (5M rows)95%full text scan!
search query
ranked hits (BM25)
CDC index sync
SQL LIKE scan / fan-out
shard timeout
In This LessonStep 1 of 10
What You Will Master
  • ✓Explain why SQL `LIKE "%term%"` cannot use B-Trees and how an Inverted Index turns scans into instant posting-list lookups
  • ✓Trace tokenization, stemming, and BM25 scoring (TF, IDF, and field-length normalization) to rank relevant results first
  • ✓Scale search indexes horizontally via Query-Then-Fetch scatter-gather across shards
  • ✓Keep search clusters fresh via CDC streams, near-real-time (NRT) segment refreshes, and prefix autocomplete tries

Architectural Trade-Off Comparison Matrix

PatternBest ForKey Trade-Off
Inverted Index (Elasticsearch / OpenSearch)Full-text keyword search, fuzzy typo matching, faceted e-commerce filters, and relevance rankingEventual consistency (~1s refresh lag) and not suitable as your primary ACID source of truth
BM25 Relevance ScoringRanking matches by rare-term importance (IDF), saturating term frequency (TF), and short-title boostsPure lexical matching misses semantic synonyms unless paired with synonym dictionaries or vector embeddings
Query-Then-Fetch Scatter-GatherSearching multi-terabyte sharded indexes by fetching only top-K `(doc_id, score)` pairs firstDeep pagination (`OFFSET 50,000`) forces every shard to sort 50k items—use `search_after` cursors instead
CDC → Search Sync PipelineKeeping search automatically synchronized with your primary SQL database without dual-write driftAdds ~1–2 second near-real-time indexing delay before brand-new listings appear in search

Step-by-Step Architectural Breakdown (10 Steps)

Full architectural walkthrough transcript and state transitions for Search Engines.

STEP 01 · PROBLEMJump to step →

Why SQL `LIKE "%wireless%"` melts your primary database

Users type `"wireless headphones"` in your search bar. Running `SELECT * FROM products WHERE description LIKE "%wireless%"` on 5 million rows **cannot use a B-Tree index** because of the leading `%` wildcard.

Every single search triggers a **full table scan**, offers **zero typo tolerance**, and has **no relevance ranking**—pushing search p95 past **2,200 ms** while starving checkout queries on the same database!

watch:Leading-wildcard SQL `LIKE "%word%"` forces O(N) string scans across every row and cannot rank relevance, handle typos, or stem plurals.

Leading Wildcard ScanNo Relevance RankingPrimary DB Starvation
STEP 02 · TECHNIQUEJump to step →

Step 1 of Search: Text Analysis (Tokenize → Lowercase → Stem)

Before indexing a product title like `"The Best Running Shoes!"`, a Search Engine runs an **Analyzer Pipeline**: **(1) Tokenize** into words, **(2) Lowercase**, **(3) Strip stop-words** (`"the"`), and **(4) Stem** (`"running" → "run"`, `"shoes" → "shoe"`).

At query time, the user’s query `"RUN shoe"` passes through the **exact same analyzer**, guaranteeing clean linguistic matches regardless of capitalization or pluralization.

idea:Index-time and query-time analysis MUST match—otherwise `"Shoes"` stored as `"shoe"` won’t match an unanalyzed query for `"Shoes"`.

TokenizationStop WordsStemming & Synonyms
STEP 03 · SOLUTIONJump to step →

The Inverted Index: flip Document→Words into Word→Documents

Like the index at the back of a textbook, an **Inverted Index** maps every unique **Term** directly to a sorted **Posting List** of matching Document IDs: `"wireless" → [12, 48, 91, 405]` and `"headphone" → [48, 91, 710]`.

Answering `"wireless AND headphone"` simply intersects two sorted integer arrays in RAM (`[48, 91]`) using skip-lists/SIMD—plunging search latency from **2,200 ms down to 11 ms**!

idea:Posting lists are stored as delta-encoded sorted integers compressed with bit-packing, allowing engines to intersect millions of Doc IDs in microseconds.

Inverted IndexPosting ListsSorted List Intersection
STEP 04 · TECHNIQUEJump to step →

Ranking the best results first: BM25 Scoring

Matching 14,000 products isn’t enough—shoppers only click the **top 5**. Modern search engines (Lucene / Elasticsearch) rank matches with **BM25**, combining three intuitive signals:

**(1) IDF (Rarity)**: matching rare `"noise-cancelling"` beats common `"black"`. **(2) Saturating TF**: repeating a word 50 times in spam gives diminishing returns. **(3) Length Norm**: a match in a 5-word title beats one buried in a 1,000-word paragraph.

idea:BM25 improves on classic TF-IDF by saturating term frequency (blocking keyword stuffing) and normalizing for short titles vs verbose descriptions.

BM25 ScoringTF SaturationIDF & Length Normalization
STEP 05 · SOLUTIONJump to step →

Scaling to Billions of Docs: Sharded Query-Then-Fetch

When your index grows to **500 million documents (2 TB)**, it no longer fits on one machine. Split the index into **Shards 0, 1, and 2** across separate search nodes.

A Coordinator runs **Query-Then-Fetch**: **(1) Query phase** scatters the query to all 3 shards and collects *only* the top-20 `(doc_id, score)` pairs from each (60 tiny pairs). **(2) Fetch phase** merges the global Top 20 and fetches full JSON bodies *only* for those 20 winners.

idea:Query-Then-Fetch avoids shipping huge JSON documents over the network for losing candidates—and enables horizontal scale across dozens of search shards.

Query-Then-FetchSearch ShardsGlobal Top-K Merge
STEP 06 · TRADE-OFFJump to step →

The deep-pagination trap: why `OFFSET 50,000` kills search

A scraper requests **Page 2,500** (`FROM 50,000 SIZE 20`) across 3 shards. To know which 20 docs sit at rank 50,000 globally, **every shard must sort and send 50,020 results** to the coordinator (`150,060` items sorted per single request!).

Fix it by capping `OFFSET` at 10,000 and switching infinite scroll / exports to **`search_after` cursor pagination** (passing the last document’s `(score, doc_id)` tie-breaker)—keeping cost O(20) even on page 10,000.

watch:Never expose unbounded `OFFSET` on a sharded search cluster—one bot crawling page 5,000 can OOM your coordinator nodes in seconds.

Deep Pagination Costsearch_after CursorsBounded Result Window
STEP 07 · TECHNIQUEJump to step →

Keeping Search Fresh: CDC Sync & Near-Real-Time (NRT) Segments

Never treat Elasticsearch as your primary database, and never dual-write from your API (`write SQL` + `write Search`), or transient errors will drift them out of sync permanently.

Instead, stream SQL WAL commits via **CDC → Kafka → Search Indexer**. Inside Lucene, new docs buffer in RAM and flush into immutable **segments** every **1 second** (`refresh_interval = 1s`)—giving fast **Near-Real-Time (NRT)** searchability.

idea:Search indexes are derived views! Because CDC + Kafka feeds them, you can rebuild a brand-new index with updated analyzers zero-downtime via Index Aliases.

Near-Real-Time (NRT)Immutable Lucene SegmentsZero-Downtime Reindex Alias
STEP 08 · TECHNIQUEJump to step →

Instant Typeahead & Typo Tolerance: Edge N-Grams & FSTs

Users expect instant suggestions after typing just 3 letters (`"wir" → "wireless headphones"`), even with typos (`"wireles"`).

Precompute **Edge N-Grams** (`w, wi, wir, wire…`) or an in-memory **Completion FST (Trie)** for <8 ms prefix lookups, and bound Levenshtein **Edit Distance (`fuzziness: 1–2`)** so minor typos match smoothly without exploding candidate sets.

idea:Debounce keystrokes on the client (150 ms) and cache top 1-to-3 letter prefixes in Redis/CDN—those few prefixes represent 60%+ of all autocomplete traffic!

Prefix Trie / FSTEdge N-GramsFuzzy Edit Distance
STEP 09 · TECHNIQUEJump to step →

Modern Hybrid Search: BM25 Keywords + Vector Embeddings

BM25 nails exact SKUs (`"RTX-4090"`) and keywords, but struggles with intent queries like *"cozy winter gift for coffee lover"* where exact words don’t appear in the product title.

**Hybrid Search** runs **BM25 (Inverted Index)** and **ANN Vector Search (HNSW)** in parallel, then merges both ranked lists via **Reciprocal Rank Fusion (RRF)**—getting both exact SKU precision and semantic understanding!

idea:Never replace BM25 completely with vectors—exact part numbers and brand names still perform far better lexically. Reciprocal Rank Fusion combines the best of both.

Hybrid SearchHNSW Vector IndexReciprocal Rank Fusion (RRF)
STEP 10 · RECAPJump to step →

Recap: production full-text search architecture

Full-text search is a specialized **derived read index** powered by **Text Analysis**, **Inverted Posting Lists**, and **BM25 (+ Vector RRF)** ranking.

Keep Primary SQL as your source of truth, feed Search asynchronously via **CDC → Kafka → `_bulk` NRT refreshes**, scale horizontally via **Query-Then-Fetch shards**, and always use **`search_after` cursors** instead of deep offsets.

idea:Interview cheat code: always keep Search decoupled from Primary SQL via CDC—never dual-write from the app and never run `LIKE "%term%"` on production SQL.

Inverted IndexBM25 + RRFQuery-Then-FetchCDC NRT Sync

Related Production Deep-Dives & Simulators

Included In Free Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.