← Data structures

Inverted index

Text, space and time

A map from each word to the sorted list of document ids that contain it, the reverse of a document-to-words mapping. It exists because "find every document with these words" becomes intersecting a few short lists instead of reading every document.

What it costs

OperationCostNote
Single-term lookupO(1) + list lengthHash or B-tree the term, then read its posting list from disk or memory.
AND of two termsO(|A| + |B|)Merge two sorted lists; skip pointers make it closer to the shorter list.
Ranked top-kO(matches × log k)Score each candidate (TF-IDF or BM25) and keep a heap of the k best.
Add a documentO(terms in doc)Append the doc id to each term’s list. Engines batch this into immutable segments and merge them.
Delete a documentO(1) markA deleted bitmap marks the id; the list entry is dropped at the next segment merge.

Memory: One posting (document id, often with positions) per term occurrence. 1 billion video titles of 8 words each is 8 billion postings; delta-encoded at about 1 byte each, roughly 8 GB plus a term dictionary of a few hundred megabytes, which is a tenth of the raw text.

Term → sorted posting list; a query merges lists

Each term points to the ascending list of documents containing it. "system AND interview" walks the two lists together and keeps ids present in both, then scores the survivors.

How it works

  1. Tokenise each document: lowercase, split on spaces and punctuation, drop stop words like "the", and stem so "running" and "runs" both become "run". The result is a list of terms.
  2. For every term, append the document id to that term’s posting list, which is a list of document ids kept in ascending order. A posting may also carry the term frequency (how many times it appears) and positions (where) for phrase queries.
  3. Store the term dictionary (term → where its list lives) as a sorted structure so prefix and range queries work, and store posting lists delta-encoded: 1041, 1043, 1050 becomes 1041, +2, +7, which compresses well because ids are sorted.
  4. To answer "system AND design", fetch both lists and walk them together like a merge sort, emitting ids present in both. Skip pointers every few hundred entries let the walk jump ahead in the longer list.
  5. To rank, score each surviving document: a term that is rare across the corpus (high inverse document frequency) and frequent in this document (high term frequency) scores highest. Keep the top k in a heap.
  6. Writes go to a new small segment (an immutable mini-index) rather than editing lists in place; a background merge combines segments, and deletes are a bitmap applied at read time until the merge drops them.

Why it is shaped this way

  • Sorted posting lists are what make AND and OR a linear merge rather than a nested loop, and what make delta encoding possible.
  • Immutable segments mean writes never lock readers; the price is that a document is searchable only after its segment is committed, typically a second later.

Worked example

Searching video titles on the streaming platform

  • 100M videos, titles average 8 words, 2M distinct terms after stemming. Postings: 800M. Delta-encoded at about 1.2 bytes each ≈ 1 GB. Dictionary: 2M terms × ~40 bytes ≈ 80 MB. The whole index fits in RAM on one node; shard by video id when you add descriptions and subtitles.
  • Query "system design interview": "system" has 400K postings, "design" 900K, "interview" 150K. Intersect smallest-first: walk interview (150K) against system with skip pointers, leaving maybe 20K; walk those against design, leaving 6K. About 300K list reads, well under 10 ms.
  • Rank the 6K: BM25 score per document, heap of the top 20. "interview" is the rarest term so documents with it in the title score highest.
  • A new upload "System design interview tips" arrives: tokens [system, design, interview, tip]; append id 100,000,001 to four lists in the current segment. Searchable after the next segment flush, about 1 s.
  • A video is removed: set its bit in the deleted bitmap. Queries skip it immediately; the postings vanish at the next merge.

When it is the wrong choice

  • Exact key lookups or range scans on one column: a B-tree does that with less machinery and strong consistency.
  • Data that must be searchable the instant it is written: segments commit with a delay of about a second, so a search index is a derived copy, never the source of truth.
  • Numeric aggregation over many rows (sums, averages): a column store is built for that; an inverted index only finds rows.

Interviewer follow-ups

Answer out loud before you open each one.

Why are posting lists kept sorted?

Sorted lists let two terms be intersected or unioned in one linear merge, like the merge step of merge sort, instead of checking every pair. Sorting also makes delta encoding possible, because consecutive ids differ by small numbers that compress to a byte or two.

How does a new document become searchable, and why is there a delay?

The engine appends its postings to a small in-memory segment and periodically writes that segment as an immutable file; a query searches every committed segment. The delay is the flush interval, typically one second. Editing lists in place would need locks on the hot read path.

What is the posting list for a word like "the"?

Almost every document, so it is huge and useless for narrowing results. Engines drop such stop words at tokenisation, or keep them only for phrase queries, where positions matter.

How do you keep the search index in sync with the database?

Treat it as a derived view: publish each row change as an event (change data capture or an outbox) and have an indexer consume them. Make the indexer idempotent on document id so replays are harmless, and keep a way to rebuild the whole index from the database.

Where it shows up

Building blocks
Full-text and fuzzy search · Suggest as the user types · Analytics without hurting production · Index the columns you filter on
Problems
Video Streaming Platform (YouTube / Netflix) · News Feed (Twitter / X timeline)