SysDesignAtlas

Search & Inverted Indexes

How full-text search works internally, why your database can't do it, relevance ranking, and keeping the index in sync with the source of truth.

HLDMedium11 min readsearchelasticsearchinverted-index
Confidence

#Why not just use LIKE

sql
SELECT * FROM posts WHERE body LIKE '%distributed systems%';

This reads every row in the table. No index can help, because the pattern starts with a wildcard — there's no prefix to look up. At 100M rows it's unusable.

And even if it were fast, it would be wrong for search. No ranking, so you can't put the best result first. No stemming — reducing words to their root — so "running" won't match "run". No typo tolerance, no sense of which of several words matters most, no phrase handling.

Search is a genuinely different problem requiring a different data structure.

#The inverted index

A normal index maps document → contents. An inverted index maps term → documents containing it.

   Doc 1: "the quick brown fox"
   Doc 2: "the quick red fox jumps"
   Doc 3: "brown bears sleep"

   INVERTED INDEX (postings lists)
     brown  → [1, 3]
     fox    → [1, 2]
     jumps  → [2]
     quick  → [1, 2]
     red    → [2]
     sleep  → [3]
     ...

   Query "quick fox" → intersect [1,2] ∩ [1,2] = docs 1, 2

Each term's list of document IDs is called its postings list, and each list is kept sorted by document ID. A query becomes a set intersection over those lists: walk "quick" and "fox" side by side and keep the IDs that appear in both. That's extremely fast, and the work depends on how long those two lists are — not on how many documents exist in total, which is what a scan pays for.

Postings also store two extra things per document:

  • Positions — where in the document each term appears. These support phrase queries: "quick fox" as an exact phrase only matches if "fox" sits at the position right after "quick".
  • Frequencies — how many times the term appears in that document, which ranking uses (see below).

#The analysis pipeline

Text is transformed before indexing, and the same transformation is applied to queries. Mismatches here are the source of most "why doesn't this match?" bugs.

   "The Runners' Feet Were Running!"
        │
   1. Character filters   strip HTML, normalize unicode
        │
   2. Tokenize            [The, Runners, Feet, Were, Running]
        │
   3. Lowercase           [the, runners, feet, were, running]
        │
   4. Stop words          [runners, feet, running]      (optional)
        │
   5. Stemming/lemma      [runner, foot, run]
        │
        ▼
   indexed terms

Stemming chops to a crude root (running → run) — fast, imperfect (universal → univers). Lemmatization uses a dictionary for real base forms (feet → foot, better → good) — accurate, slower.

Stop word removal — dropping very common words like "the", "to", "be" — is now often skipped, for two reasons. It breaks phrase queries: "to be or not to be" is made entirely of stop words, so it becomes an empty query. And it isn't needed any more, because modern ranking (IDF, below) already gives common words almost no weight.

Synonyms and n-grams can be layered in. An n-gram is a short run of characters cut from a word — sys, yst, ste from "system" — and indexing those lets a query match part of a word or survive a typo. Edge n-grams are the ones cut from the start of the word — indexing sys, syst, syste, system — so a user who has typed only "syst" already finds "system". That's how prefix autocomplete is often served.

#Relevance ranking

Matching gives you a candidate set — every document that contains the query terms. Ranking decides the order. And ranking is the product: users only look at the first few results, so a search that finds the right document but puts it on page 3 has failed.

TF-IDF — the classic intuition:

  • Term Frequency — a term appearing often in a document suggests the document is about it.
  • Inverse Document Frequency — a term appearing in few documents is more discriminating. Matching "the" tells you nothing; matching "raft" tells you a lot.

BM25 is the modern default (it's what Elasticsearch and Lucene use). It refines TF-IDF in two important ways:

  • Term frequency saturates. The 50th occurrence of a word adds almost nothing over the 10th. Without this, a page that repeats "cheap flights" 500 times (keyword stuffing) would outrank a genuinely useful page.
  • It normalizes for document length. A long document mentions most words more often simply because it has more words. BM25 adjusts for that, so a short, focused document isn't beaten by a long rambling one that happens to mention the term more times.

Beyond text relevance, production search blends in signals that often matter more to users than whether the words match (lexical matching): recency, popularity/engagement, personalization, geographic distance, and business rules. Scoring every document with all of those would be too slow, so a typical architecture works in two stages. First it retrieves a few hundred candidates cheaply with BM25. Then it re-orders just those few hundred with an expensive model. This pattern is called retrieve then rerank, and it's worth naming in an interview.

Vector / semantic search matches meaning rather than words. Each piece of text is turned into a list of numbers (an embedding), positioned so that texts with similar meanings land near each other. A query is turned into numbers the same way, and the search finds the closest documents. So "how do I fix a flat tire" matches a document about "repairing a puncture" even though they share no words.

Modern systems combine both. Hybrid search runs BM25 and vector retrieval in parallel and merges the two ranked lists into one, because keyword search still wins on exact identifiers, names, and rare terms — a vector search for error code E1042 may happily return E1043.

#Architecture

Search engines shard the index and replicate each shard:

   query ──► coordinator
               │  scatter to every shard (query touches all)
               ├──► shard 1 (replicas) → top 10 local
               ├──► shard 2 (replicas) → top 10 local
               └──► shard 3 (replicas) → top 10 local
               │
               ▼  gather, merge, globally rank, return top 10

Two consequences worth stating:

  • Search is inherently scatter-gather: every query goes out to every shard, and the answer can't be returned until the last shard replies. So the query is as slow as the slowest shard. With 20 shards, the odds that one of them is having a slow moment are much higher than with 2 — this is tail amplification. That means adding shards isn't free: more shards hold more data, but each query waits on more of them.
  • Deep pagination is brutal. Page 100 at 10 results a page means every shard must send its top 1,000 results to the coordinator, which merges them all just to show 10. Prefer search_after/cursor pagination over offsets — instead of "skip 990 results", the client says "give me the 10 after the last one I saw", so each shard only sends 10. And cap how deep users can page.

Documents are written into segments — self-contained chunks of index that, once written, are never modified, only merged together later. Because nothing changes in place, readers never need locks and caching is trivial. The cost is that an update is really "mark the old one deleted, insert a new one", and the space isn't reclaimed until a merge runs.

Near-real-time, not real-time: a newly indexed document isn't searchable straight away. It becomes visible only after the next refresh, when the engine turns recently buffered documents into a searchable segment (typically every ~1 s in Elasticsearch). You could force a refresh after every write, but each refresh creates a tiny segment, and thousands of tiny segments per second destroy throughput. So search is eventually consistent by design — and saying so in an interview shows you understand how the engine actually works.

#Keeping the index in sync

The search index is a derived store; the database is the source of truth. Getting data from one to the other is where real designs go wrong.

Dual write (avoid). The application writes to both the DB and the index. If the second write fails, they diverge permanently, and there's no self-healing.

Outbox / CDC (correct). The application writes only to the database. A separate process (a relay) then reads the changes and updates the index asynchronously. It finds the changes either in the database's own transaction log (the WAL — every committed change, in order) or in an outbox table the application writes "this post changed" rows into, in the same transaction as the real change.

   app → DB (source of truth)
           │ WAL / outbox
           ▼
       CDC relay → transform → bulk index → search cluster

This gives you three things:

  • The index always catches up. Every committed change is in the log, so the index ends up matching the database even if the relay falls behind for a while.
  • It survives index downtime. If the search cluster is down, changes simply queue up and are applied when it returns.
  • You can rebuild from scratch by replaying the changes. You will need to, whenever the mapping changes — the mapping is the index's schema: which fields exist, their types, and which analyzer each uses.

Bulk, don't trickle. Indexing one document per request is an order of magnitude more expensive than batching. Buffer for a second or a thousand documents and submit in bulk.

Reindexing strategy. Analyzers and mappings can't always be changed on an existing index — if you switch the stemmer, every already-indexed term is wrong. The standard pattern: build a new index alongside the old one and fill it. The application never queries an index by its real name; it queries an alias (a pointer name like posts). When the new index is ready, atomically flip the alias from posts_v1 to posts_v2. Zero downtime, and rollback is just flipping it back.

#When you don't need a search engine

Worth volunteering, because adding Elasticsearch is a large operational commitment:

  • Prefix/autocomplete only → a trie, or a Postgres index on LOWER(name) text_pattern_ops, or Redis sorted sets. See Search Autocomplete.
  • Small corpus (< ~1M docs), simple queries → Postgres full-text search (tsvector + GIN index) is genuinely good and removes an entire system from your architecture.
  • Exact matching / filtering → that's just a database query with an index.
  • Fuzzy name matching only → trigram indexes (pg_trgm).

The instinct to reach for the smallest sufficient tool — and to say "Postgres FTS handles this until we're past a few million documents or need real relevance tuning" — reads as maturity rather than ignorance.

#Check yourself

What does an inverted index map, and how does it answer a two-word query?Show answer
Each term maps to a sorted list of the documents containing it. A query intersects those lists — "quick fox" is quick's list ∩ fox's list.
Why must the same analysis pipeline run on documents and queries?Show answer
Lowercasing, stemming and tokenising must match on both sides or terms won't line up — the source of most "why doesn't this match?" bugs.
What does BM25 improve over TF-IDF?Show answer
Term frequency saturates, so the 50th occurrence adds almost nothing (beating keyword stuffing), and scores are normalised by document length so long documents don't win just by repeating terms.
What is "retrieve then rerank"?Show answer
Fetch a few hundred candidates cheaply with BM25 (or vectors), then re-order them with an expensive model that blends in recency, popularity and personalisation.
Why combine keyword and vector search (hybrid search)?Show answer
Vectors match meaning — "fix a flat tire" finds "repairing a puncture" — but keyword search still wins on exact identifiers, names and rare terms. Run both and fuse the rankings.
Why is deep pagination painful in a sharded search engine?Show answer
Page 100 at 10 a page makes every shard return 1,000 results for merging. Use search_after/cursor pagination and cap the depth.
Why should you never dual-write to the database and the search index?Show answer
If the second write fails they diverge permanently with no self-healing. Write to the database and let CDC or an outbox relay update the index, which also lets you rebuild it by replay.
How do you change an index mapping with zero downtime?Show answer
Build a new index alongside the old, fill it, then atomically flip an alias (posts_v1 → posts_v2). Rollback is flipping it back.

#What to carry forward

  • Full-text search needs an inverted index; LIKE with a leading wildcard scans everything and can't rank.
  • Analysis (tokenise, lowercase, stem) must match between indexing and queries.
  • BM25 is the ranking default; production adds retrieve-then-rerank and hybrid vector search.
  • Search is scatter-gather and near-real-time — refreshes make new documents visible after about a second.
  • Keep the index derived from the database via CDC, reindex behind an alias, and don't add a search engine Postgres can cover.
00:00
/ 11m