Systemsfor Aravinda
0 / 78 core
Week 3 · Storage

Search indexes

2 hours · core path

Read first: Indexes: B-trees and LSM trees

In one sitting

An inverted index maps a term to the documents that contain it, and it is a derived copy of the primary store. Indexing is asynchronous, so a document you just saved is not searchable yet. Ranking can start from term frequency and inverse document frequency, and a product needs signals that score does not have.

A primary key lookup answers “row 42.” Search answers “which rows contain the word shoes, and which of those should I show first?” Those are different structures. The second one is built from the first, and it is always a step behind.

The index you already know from Indexes: B-trees and LSM trees finds a key or a range of keys in sorted order. An inverted index finds documents by the terms inside them. You still need the first structure. The row lives there. Search is a view of that row, not a replacement for it. Choosing a database is where the document is the source of truth. This page is the copy that lets a query box work.

Core concepts

Terms and postings

An inverted index maps a term to a postings list: the document ids that contain the term, and sometimes the positions inside each document. The forward direction, document to text, is how you stored the row. The inverted direction is how a query runs without reading every row.

Take three documents.

  • Document 1: red shoes
  • Document 2: blue shoes
  • Document 3: red hat

The postings are small enough to redraw:

  • red points at documents 1 and 3
  • shoes points at documents 1 and 2
  • blue points at document 2
  • hat points at document 3

A query for red AND shoes intersects the lists for red and shoes. Both lists are sorted by document id, so you walk them together. Start at the heads. Document 1 is in both, so emit 1 and advance both. Next is 3 against 2. Advance the smaller head. Next is 3 against the end of shoes. Shoes is exhausted, so you stop. The only hit is document 1. The walk is proportional to the sum of the lengths, not the product. A query that ANDs a rare term with a common one should use the short list to decide where to probe. That is the mechanical reason rare terms matter, and it shows up again in ranking.

OR is a union of the same sorted lists. Red OR hat is documents 1 and 3, union hat which is already in that set, so 1 and 3. You still walk. You do not scan the corpus.

Positions turn a bag of words into a phrase. In document 1, red is at position 0 and shoes is at position 1. A phrase query asks for those terms at adjacent positions. Without positions, a document that says “shoes, then red” looks the same as one that says “red shoes”: both ids sit on both lists. Positions are extra integers on the postings. Store them when the product needs phrases. Skip them when you only need “this document mentions both terms,” and say what you gave up.

Tokenization

Tokenization is the function that turns text into terms, on the way in and on the way out. The index stores whatever the function emitted at write time. The query finds something only if the same function emits the same terms at read time.

Lowercase, and split on whitespace and punctuation, and “Red, shoes!” becomes red and shoes, which is what you stored from “red shoes.” Skip the lowercase step on one side only, and the query looks up Red while the index holds red. The document is sitting there. The lookup misses. The bug is not ranking. It is two different functions.

Decide what a word is before you celebrate a result. “New York” can be one token or two. If you index it as two terms, a query for York matches every York in the corpus, and the city is an AND of new and york plus, if you stored positions, a check that they are adjacent. If you index the city as one term, a query that splits it will miss. Numbers, identifiers, and words with punctuation need the same decision. An identifier you smash into pieces cannot be found whole. An identifier you keep whole will not match a query that only has a piece.

Dropping very common terms makes postings shorter. It also deletes the words a phrase was made of. A query that was only those common words has nothing left to look up. If you drop them, drop them on both paths, and do not offer a phrase search you have already destroyed.

The tokenizer is part of the index. Changing it means reindexing the corpus, or living with two generations of terms that do not meet. A partial reindex is a search box that works for new documents and misses old ones for the same query. That looks like relevance and is a migration bug.

Not the primary store

The inverted index is not the database. You do not run the booking transaction inside it. You do not ask it to be the only copy of a document you cannot lose. Updates are “index this document again,” not an in-place field update with the isolation story of the primary. If the index breaks, you rebuild it by reading the primary. If the primary breaks, the index cannot rebuild the business.

Because the index is derived, it is allowed to lag. Event sourcing and CQRS is the general shape: a read model that is a different structure from the write model, and a lag you tolerate on purpose. Search is that read model for terms. A log of document writes is a natural feed for the indexer. Consumers keep an offset and can replay. Queues and logs is the feed. The index is one consumer. The primary is not.

The failure in the middle is a dual write. The primary commits the document, and the process dies before it tells the indexer. That document is saved and never becomes searchable. Lag is not twenty seconds. It is forever, and retries of the user request may insert a second row if you are not careful. Write the document and an outbox row in one transaction, and let a publisher hand the outbox to the indexer. The outbox pattern and sagas closes the hole where the database committed and the bus never heard. The indexer still has to be idempotent. Idempotency and the exactly-once myth applies: delivering “index document 9001” twice must leave one set of postings for 9001, not two. At-least-once delivery plus an idempotent handler is the practical shape. A checkbox labeled exactly-once will not save a handler that appends postings blindly.

Lag, in product terms

Indexing is asynchronous, so search lags writes. A document that just committed is not in the postings yet. The user who searches for the title they just saved gets an empty result. The document is not gone. The view they are looking at is behind.

Read-your-writes for “my document” is a primary read by id, or a session that knows the document is ahead of the index. It is not a search query. The screen that says “saved” has to load the row. The screen that says “search the catalog” can be a few seconds behind, and you should say that where the user can see it if the product cares. Pretending they are the same read is how a successful save looks like a bug.

Waiting for the index inside the save request pulls the index onto the user path. A stuck indexer then means nobody can save. You also add the index update to the latency budget of a button that only needed the primary. Async lag is the trade for a save path that stays up when search is behind. The cost is the window, which you can estimate: writes per second times how far behind the indexer is.

Ranking starts at TF-IDF, and prefixes are a different structure

Term frequency is how often the term appears in this document. Inverse document frequency is the observation that a term in fewer documents is more specific. In the three-document set, shoes appears in two documents and hat appears in one. A match on hat should count more than a match on shoes, all else equal, because hat picks out less of the corpus. A document that says shoes many times scores higher on that term than a document that says it once. A starting score combines those two ideas. That combination is TF-IDF.

It is a starting point, not the ranker. A page that repeats shoes fifty times should not outrank the product the user came to buy. The second signal is not in the postings. Recency, whether the item is in stock, and who is asking are product inputs. Say TF-IDF so you are not sorting by document id. Then say which extra signal this product would actually use. Do not invent weights. A ranker you cannot explain is a sort you will not be able to debug when the wrong row is on top.

Prefix search is not a postings lookup on the full term. The prefix “sho” is not the term “shoes,” so an exact lookup misses. Two structures cover it. A trie stores characters along a path. Under the node for “sho” you can hang shoe, shoes, and shop. Edge n-grams store the prefixes as ordinary terms: s, sh, sho, shoe. A prefix query becomes an exact term lookup on the gram, which reuses the inverted index, and it stores extra terms you have to build at index time. The trie walks characters. The grams multiply the dictionary. Design search autocomplete is that problem with a latency budget and a list of suggestions. Here you only need to know that the exact postings list will not answer a prefix.

Nearest-neighbor search over embeddings is a different structure again. Vector search is that page. Do not draw an inverted index and call it semantic. Keyword postings and a vector index can sit in front of the same primary documents. Neither of them is the primary.

A worked example

You run a catalog people can search. Assumptions:

  • Five million documents are in the index. An interview-sized corpus, not a company figure.
  • After tokenization, a document averages 100 terms. An assumption about the text, not a measured tokenizer.
  • You store an 8-byte document id per posting and, if you keep positions, 4 more bytes. Widths chosen so the arithmetic is visible. Real postings are compressed. Do not quote these widths as a disk bill.
  • One million documents are saved or edited a day. A planning assumption.
  • When things are healthy, the indexer is 20 seconds behind the primary. A lag budget you would alert on, not a benchmark.
postings entries
  5,000,000 documents * 100 terms = 500,000,000

doc ids only, 8 bytes, no compression
  500,000,000 * 8 = 4,000,000,000 bytes = 4 GB

positions at 4 bytes each
  another 2 GB on top of that width

saves per second
  1,000,000 / 86,400 = 11.6 saves/s
  shortcut: 1,000,000 / 100,000 = 10 saves/s

healthy lag of 20 seconds
  11.6 * 20 = 232 documents
  committed on the primary, not in the postings yet

A day is 86,400 seconds, and the shortcut of 100,000 seconds is why a million saves a day is about 12 a second, close to the 11.6 you get if you divide it out. At a 20-second lag, about 232 of those documents are real in the database and invisible to search. One of them is the document someone just saved. Their search for a word in the title returns nothing. A read by id returns the row. The product bug is using the search box as the read path for “show me what I just wrote.”

If the indexer falls an hour behind, the same rate is 11.6 times 3,600, about 42,000 documents. The primary still has them. Rebuilds and retries still work. The search box is a view of an hour ago. That is the moment you page someone, because the feature has quietly become a stale copy rather than a search engine. Lag is the signal, the way a consumer’s offset lag is the signal on a log. A per-document acknowledgement from search is the wrong tool. You are not trying to ack every term. You are trying to notice that the offset stopped.

The three-document postings are the same structure as the five million, just small enough to walk by hand. Red AND shoes emitted document 1. Add positions and you can require that shoes follows red. A query for hat ranks document 3 with a rarer term than a query for shoes, which hits two documents. That is inverse document frequency in a set you can count. It does not decide that document 3 should outrank a newer hat the user already clicked. You do not have clicks in this index. A starting score that pretends otherwise is a story.

The document that is not searchable yet, call it 9001, with the text “red wool hat,” committed two seconds ago. The wool list and the hat list do not contain 9001. The intersection is empty. The row is on the primary. The screen after Save loads 9001 by id. The catalog search does not, and the empty result is the lag, not a tokenizer mismatch. You can tell the two bugs apart: a tokenizer bug misses the document forever, including after the lag catches up, and a lag bug heals when the indexer passes that offset.

flowchart LR
  save[Save document]
  primary[Primary database]
  lag[Async indexer]
  index[Term to postings]
  query[Search query]
  byId[Read by document id]
  save --> primary
  primary --> lag
  lag --> index
  query --> index
  byId --> primary

The search arrow never touches the primary. The read-by-id arrow never touches the postings. A user who must see their own save uses the second arrow. A user who is browsing the corpus uses the first. Mixing them is the bug in the diagram.

Tradeoffs

Choice What you gain What you spend
Inverted index beside the primary Term queries touch postings, not every row A second store to run, and a rebuild path when it drifts
Primary only, scanning text One store, no lag Every query reads far too much once the corpus is large
Positions on the postings Phrase queries can demand adjacent terms Extra bytes per occurrence, on the order of the width you assumed
Document ids only A smaller index and a faster intersection “red shoes” and “shoes red” look identical
Async indexing Saves need only the primary, and search can fall behind without blocking them A window of documents that are saved and not searchable
Index update inside the save request The next search can see the write Search availability and latency join the save path
Trie for prefixes Character-by-character completion without exploding every term A second structure to keep in sync with the corpus
Edge n-grams in the inverted index Prefix lookup reuses postings Extra terms per word, and the same reindex cost when tokenization changes
TF-IDF as the whole ranker A score you can explain from the postings Repetition and very common terms dominate, and product signals are absent

Changing the tokenizer is the expensive row people forget. Every choice above that depends on terms, including n-grams, is wrong until you reindex if the function changes. Budget a rebuild. The primary can feed it. The index cannot invent the original text if you never kept it.

Pitfalls

  • Using search as the source of truth. The symptom is a document you cannot reconstruct after an index bug, because the primary never had it, or had an older copy.
  • Tokenizing the query differently from the documents. The symptom is a permanent miss on text a person can read in the row. Reindexing does not fix it if the query path is still the odd one out.
  • The save screen querying the index. The symptom is “saved” followed by “no results” for a title that committed two seconds ago. About 232 documents sit in that window at the rates above, every moment of a healthy day.
  • A dual write that tells the indexer after the commit, with no outbox. The symptom is one document missing forever after a crash in between, while the lag graph looks fine because the indexer is keeping up with the messages it actually received.
  • An indexer that appends postings on every delivery. The symptom is the same document id twice on a list after a retry, and a score that treats one document as two.
  • Ranking by raw term count. The symptom is a stuffed page on top and the real product under it. TF-IDF already asks you to weight rare terms more, and it still does not know recency or stock.
  • Offering phrase search without positions. The symptom is matches where the words exist and the phrase does not.
  • Changing the tokenizer and not rebuilding. The symptom is new documents found and old documents missing for one query, which gets reported as “search is random.”

In the interview

In the first five minutes, draw term to postings and intersect two short lists out loud. Say the primary database is the source of truth and the index lags, and give the window: writes per second times lag. At about 12 saves a second and 20 seconds of lag, a couple of hundred documents are not searchable yet. The bottleneck is either the postings walk on a very common term or the indexer falling behind. The honest tradeoff is that lag, against putting the index on the save path.

Skip compression tricks and skip a named ranking formula with constants you cannot derive. Say TF-IDF as the start, then one product signal you would add, such as recency or “in stock.” The question that usually follows is “the user cannot find the document they just saved” or “how would autocomplete work?” The first is the lag, and the fix for their own read is the primary by id. The second is a trie or edge n-grams, which are prefix structures, not a hope that the term “shoes” will answer “sho.”

Check yourself

Documents: 1 is red shoes, 2 is blue shoes, 3 is red hat. Which document ids match red AND shoes, and why does blue drop out?

Intersect the postings. Red has 1 and 3. Shoes has 1 and 2. The only shared id is 1. Blue is a different term, and its only document is 2, which is not on the red list. The walk never emits 2 or 3 for this query. Positions are not required for the AND. They would matter if you also demanded that the two terms sit next to each other.

A user saved a document two seconds ago. The indexer is 20 seconds behind. Where do you read if the screen must show that document?

Read it by id from the primary. The postings do not contain it yet, so a search query is the wrong read and will look like a failed save. The lag heals for search when the indexer passes that document. It does not heal if you tokenized the query differently, which is how you tell a permanent miss from a late index.

Why is term frequency times inverse document frequency not the ranker you ship?

It only knows how often the term appears here and how rare the term is across documents. A page that repeats a word scores as if repetition were relevance. Stock, recency, and what this user came for are not in that score. Use TF-IDF so common words do not win by default, then add the product signal you can actually explain. A weight you invented in the interview is not a ranker.

What does a trie or an edge n-gram give you that an exact postings lookup on the full term does not?

A prefix. The letters sho are not the term shoes, so the shoes list does not answer a prefix query. A trie walks those letters and can list the words underneath that node. Edge n-grams store sho itself as a term, so the inverted index can answer with an exact lookup, at the cost of extra terms per word. Both have to be built with the same tokenizer as the rest of the index.

Based on: Designing Data-Intensive Applications, Kleppmann and Riccomini.