System Design

Core Concepts

Inverted Indexes

A search query never scans your documents. It reads lists that were written when each document was indexed, so what it can match, what it can see and what each change costs were all decided before anyone typed a word.

Why you are doing this at all

Search looks like a read problem. Someone types two words, and the system finds the documents that contain them. But a search engine does little work when the words arrive. It did most of the work earlier, when each document was written, and the query only reads what that work produced.

The alternative is to read every document at query time. GitHub worked out what that would cost for its code search.

Back of envelopeSearching 115 TB of code, with and without an index
GitHub's own arithmetic, from its code search write-up.
The question is how many queries a second each approach
serves on the same 32 machines of 64 cores.

Scan every byte, as grep would
  per core      13 GB / 2.769 s / 8 cores     ≈ 0.59 GB/s
  cores         32 × 64                           = 2,048
  one query     115 TB / (2,048 × 0.59 GB/s)       ≈ 96 s
  the cluster   one query at a time              ≈ 0.01/s

Read an index instead
  one query     on each machine         ~100 ms of a core
  one machine   64 cores / 0.1 s                  ≈ 640/s
  ───────────────────────────────────────────────────────
  Every query goes to every machine, so the cluster's
  limit is about 640 queries a second, against 0.01
  for the scan.

A B-tree doesn't help either. Indexing and query performance explains why LIKE '%jacket%' can't use one: the index is sorted from the first character, and a word in the middle of a value says nothing about its first character. Choosing a database calls this the wrong index structure, and no amount of hardware fixes it.

An inverted index turns the data around. A document lists its words. An inverted index lists, for each word, the documents that contain it, and that list is called a postings list. A query for two words reads two postings lists and keeps the documents that are on both.

A search index is built before the query arrives: every match, every score and every visible document comes from lists that were written when the documents were indexed.

Where the work happens
At write time, listing 61,203 goes through analysis (1), which splits and lowercases its title, and its ID is added to the postings list of each term (2). At query time, the query goes through the same analysis (3). The engine reads the two lists outlined in green and keeps the IDs that are on both (4). Nothing reads the listing's text during the query.At write time, listing 61,203 goes through analysis (1), which splits and lowercases its title, and its ID is added to the postings list of each term (2). At query time, the query goes through the same analysis (3). The engine reads the two lists outlined in green and keeps the IDs that are on both (4). Nothing reads the listing's text during the query.
Indexing builds the lists; a query only reads them. At write time, listing 61,203 goes through analysis (1), which splits and lowercases its title, and its ID is added to the postings list of each term (2). At query time, the query goes through the same analysis (3). The engine reads the two lists outlined in green and keeps the IDs that are on both (4). Nothing reads the listing's text during the query.

Four things follow from it.

  • A query can match only the terms that analysis wrote. If indexing stored jackets and the query asks for jacket, nothing matches, whatever the user meant.
  • A new document is invisible until its lists exist. Elasticsearch builds them in batches, once a second by default, so search always runs slightly behind the writes.
  • A change rewrites the whole document. No list is edited in place, so changing one field means indexing the document again.
  • Each shard scores with its own lists. The statistics behind a score are counted per shard unless you pay to collect them.

When you don't need a search engine

Postgres has an inverted index of its own. Its full-text search turns a text column into a tsvector, a sorted list of normalised words, and indexes it with GIN, short for Generalized Inverted Index. Postgres's documentation describes GIN as a B-tree over the words, where each word points to a list of the rows that contain it. That's the same structure this page describes, inside the database that already holds the data.

The cost is ranking. Postgres scores each row from that row's words alone: how often the query's words appear, how close together they are, and which part of the row they're in. It doesn't know how rare a word is across the table. And the documentation warns that ranking reads the tsvector of every matching row. So Postgres fits when common words match a modest number of rows, and when that kind of ranking is good enough. Worked example 1 sizes one.

How an inverted index works

The term dictionary and postings lists

An inverted index has two parts. The term dictionary holds every distinct term in a field, in sorted order. The postings hold, for each term, the list of documents that contain it.

Lucene, the library under Elasticsearch, OpenSearch and Solr, stores the dictionary in blocks of terms that share a prefix. A small index over the blocks lets a lookup go straight to the one block that could hold the term. Each term's entry holds its document frequency, the number of documents that contain it, and a pointer to its postings.

Each posting starts with a document ID. Lucene numbers documents with small integers, in the order they were added, and each postings list is sorted by that number. The sort order makes both intersection and compression work. A posting can also carry the term frequency, how many times the term occurs in that document, which ranking uses. And it can carry the positions where the term occurs, which phrase queries use.

Looking up one term
The small index over the dictionary blocks (1) sends the lookup for jacket to the block of terms starting with ja. That block holds jacket's document frequency, 2,000,000, and a pointer (2) to its postings (3): document IDs in ascending order, how often jacket occurs in each, and at which positions.The small index over the dictionary blocks (1) sends the lookup for jacket to the block of terms starting with ja. That block holds jacket's document frequency, 2,000,000, and a pointer (2) to its postings (3): document IDs in ascending order, how often jacket occurs in each, and at which positions.
The dictionary finds the term; the postings say where it occurs. The small index over the dictionary blocks (1) sends the lookup for jacket to the block of terms starting with ja. That block holds jacket's document frequency, 2,000,000, and a pointer (2) to its postings (3): document IDs in ascending order, how often jacket occurs in each, and at which positions.

Positions take the most space. Introduction to Information Retrieval (IIR), the standard textbook by Manning, Raghavan and Schütze, puts a positional index at 2 to 4 times the size of one without positions. A field needs them only for phrase and proximity queries, such as "merino jacket" as an exact phrase. A field nobody searches by phrase can leave them out.

Analysis decides what can match

Before a term reaches the dictionary, analysis turns text into terms. In Elasticsearch, an analyzer has three stages. Character filters change the raw text, for example by stripping HTML tags. A tokenizer splits the text into tokens, usually words, and records each one's position. Token filters then change the tokens: they lowercase them, drop common words, or reduce each word to a stem.

A stem is a word with its ending removed, so organize, organizes and organizing all become one term. A stemmer works by rules that strip endings, so it's a rough tool: it merges most forms of a word correctly, and gets some wrong.

The query goes through analysis too, and it has to be the same analysis. Otherwise the query's terms and the document's terms are spelled differently and never meet. So the words a document can be found by were fixed when it was indexed, before anyone searched for it.

The default in Elasticsearch, the standard analyzer, splits text on word boundaries and lowercases it, and that's all. It doesn't stem, and its stop word filter is off by default. Elasticsearch's own example turns Brown-Foxes jumped into brown, foxes and jumped. A search for fox finds nothing there.

One title, two analyzers
The same title goes through two analyzers. The standard analyzer (1) only splits and lowercases, so the index holds jackets and hooded. The query hooded jacket, with both words required, becomes hooded and jacket, and jacket is not in the index, in red. The English analyzer (2) also stems, so both the title and the query become hood and jacket, and they match, in green.The same title goes through two analyzers. The standard analyzer (1) only splits and lowercases, so the index holds jackets and hooded. The query hooded jacket, with both words required, becomes hooded and jacket, and jacket is not in the index, in red. The English analyzer (2) also stems, so both the title and the query become hood and jacket, and they match, in green.
The index only holds the terms analysis produced. The same title goes through two analyzers. The standard analyzer (1) only splits and lowercases, so the index holds jackets and hooded. The query hooded jacket, with both words required, becomes hooded and jacket, and jacket is not in the index, in red. The English analyzer (2) also stems, so both the title and the query become hood and jacket, and they match, in green.

What people type decides the analysis. People search code for pieces of names, such as limits inside rate_limits, and word-based analysis can't find those. GitHub's code search indexes ngrams, overlapping runs of characters, instead of words. With runs of three, limits becomes lim, imi, mit and its, and a search for limits intersects those four lists.

AND queries: intersecting postings

Take the query merino jacket, where a listing must contain both words. Both postings lists are sorted by document ID, so the engine walks them side by side. It compares the two current IDs, keeps the ID if they match, and steps forward in whichever list is behind. That's one pass, and its cost is the two lengths added together.

Two changes make it much cheaper. First, start with the rarest term. The dictionary already holds each term's document frequency, so the engine knows which list is shortest before reading any of them. Every result has to be on that list, so it drives the walk.

Second, skip. A skip pointer lets the walk jump over the part of a list that can't contain the next ID it needs. Lucene stores each list in blocks of 256 IDs, with a skip entry for every block that records the block's last ID. When the short list asks for ID 18,412, the long list reads skip entries until it finds the block that could hold that ID, and decodes only that block. IIR notes that skips help AND queries only. An OR query wants every ID on every list, so nothing can be skipped.

An AND query that skips
merino's short list asks for its first ID, 18,412 (1). The long jacket list reads its skip entries, the last ID of each block (2). Block 13 ends at 17,903 and block 14 at 19,188, so only block 14 is decoded (3), in green. Each block spans about 1,280 IDs, and the grey blocks are never decoded.merino's short list asks for its first ID, 18,412 (1). The long jacket list reads its skip entries, the last ID of each block (2). Block 13 ends at 17,903 and block 14 at 19,188, so only block 14 is decoded (3), in green. Each block spans about 1,280 IDs, and the grey blocks are never decoded.
The short list drives, and the long list decodes only the blocks it lands in. merino's short list asks for its first ID, 18,412 (1). The long jacket list reads its skip entries, the last ID of each block (2). Block 13 ends at 17,903 and block 14 at 19,188, so only block 14 is decoded (3), in green. Each block spans about 1,280 IDs, and the grey blocks are never decoded.
Back of envelopeOne AND query, walked and skipped
A catalogue of 10M listings. The question is how much of
the long list the query "merino jacket" reads.

  "merino"                                   500 listings
  "jacket"                                    2M listings
  blocks        2M / 256 per block                ≈ 7,800

Walk both lists side by side
  IDs read      500 + 2M                             ≈ 2M

Let the short list drive, and skip in the long one
  each of the 500 IDs lands in one block,
  so at most 500 blocks are decoded
  IDs read      500 × 256                       = 128,000
  ───────────────────────────────────────────────────────
  about 16 times fewer IDs read

Two common words: "waterproof" (1.5M) and "jacket"
  1.5M targets spread over 7,800 blocks, so every
  block of both lists is decoded
  IDs read      1.5M + 2M                          ≈ 3.5M

The rarest word sets the cost of an AND query. A query
made only of common words reads every block of every list.

So load-test with queries that have no rare word in them.

Compressing postings

A document ID in Lucene is a 32-bit integer, and storing each one at full width would waste most of those bits. So a postings list stores gaps instead: the difference between each ID and the one before it. IIR's example is the word computer, whose IDs 283154, 283159 and 283202 are stored as gaps of 5 and 43. A common word appears in many documents, so its gaps are small, and small numbers need few bits.

There are two common ways to pack the gaps.

Variable-byte codes. Each byte carries 7 bits of the number and 1 bit saying whether the number continues. A gap under 128 takes one byte, and a gap under 16,384 takes two. IIR measured this on 800,000 Reuters news stories, where it cut the postings from 250 MB, at 20 bits an ID, to 116 MB.

Frame of reference, or bit packing. A block of gaps is stored at one bit width, set by the largest gap in the block. Lucene packs each block of 256 gaps this way. Fixed-width numbers decode quickly, and that matters because every query decodes them.

Gaps instead of IDs
jacket's IDs 3, 7, 12, 14, 19 and 26 become the gaps 3, 4, 5, 2, 5 and 7 (1). The largest gap is 7, so the block packs every gap into 3 bits, against 32 for a raw ID (2). merino is in one listing in 20,000, so its gaps average about 20,000 and need about 15 bits each (3).jacket's IDs 3, 7, 12, 14, 19 and 26 become the gaps 3, 4, 5, 2, 5 and 7 (1). The largest gap is 7, so the block packs every gap into 3 bits, against 32 for a raw ID (2). merino is in one listing in 20,000, so its gaps average about 20,000 and need about 15 bits each (3).
A common term's gaps are small, so they pack into a few bits each. jacket's IDs 3, 7, 12, 14, 19 and 26 become the gaps 3, 4, 5, 2, 5 and 7 (1). The largest gap is 7, so the block packs every gap into 3 bits, against 32 for a raw ID (2). merino is in one listing in 20,000, so its gaps average about 20,000 and need about 15 bits each (3).

Compression saves disk, but the reason it matters is memory. A query is fast when the lists it reads are already in memory. Elasticsearch tells you to give at least half of a node's memory to the filesystem cache, the operating system's copy of recently read files. That keeps the busy parts of the index in memory.

Back of envelopeDoes the catalogue's index fit in memory?
The question is how many shards and machines the
10M-listing catalogue needs. IIR's rule of thumb: a
compressed index with positions is a third to a half
of the size of the raw text.

  text          10M × 2 KB                        = 20 GB
  index         20 GB × 1/3 to 1/2           ≈ 7 to 10 GB
  Elasticsearch also keeps a compressed copy of each
  listing; assume it's no bigger than the text
  stored copy                                     ≤ 20 GB
  ───────────────────────────────────────────────────────
  on disk       at most                           ≈ 30 GB
  one shard     Elasticsearch's guidance      10 to 50 GB

Memory on one node with 64 GB
  cache         half of memory                    = 32 GB

The index fits in one shard, and its postings fit in the
cache of one node with room to spare. The copy of each
listing is read only for the hits on the page. Replicas
add copies for load and for failover; nothing here needs
a second shard.

Ranking: TF-IDF and BM25

Matching gives you a set. Ranking puts the set in order, and the standard scores are built from three signals.

  • Term frequency. A document that mentions the term more often is more likely to be about it.
  • Inverse document frequency (IDF). A term that appears in few documents tells you more than one that appears in most of them.
  • Length. One mention in a short title means more than one mention in a long description.

TF-IDF multiplies the first two. BM25, the default in Elasticsearch, adds two changes. Each extra mention of a term adds less than the one before, so term frequency levels off. The parameter k1 sets how fast. And it scales term frequency down for documents longer than average, and up for shorter ones, by an amount the parameter b sets. IIR reports that k1 between 1.2 and 2 and b of 0.75 work well without tuning. Lucene and Elasticsearch default to 1.2 and 0.75.

Back of envelopeScoring 'merino jacket' with BM25
The 10M listings again, with Elasticsearch's defaults,
k1 = 1.2 and b = 0.75. The question is which part of
the score decides the order, and whether common words
like "the" have to be removed to keep ranking right.

Rarity, as Lucene computes it, with N = 10M:
idf = ln(1 + (N − df + 0.5) / (df + 0.5))
  "merino"      df 500    ln(1 + 19,979)            ≈ 9.9
  "jacket"      df 2M     ln(1 + 4.0)               ≈ 1.6
  "the"         df 9.9M   ln(1 + 0.01)             ≈ 0.01

Repetition, as Lucene computes it, with L the listing's
length over the average:
tf / (tf + k1 × (1 − b + b × L)), so tf / (tf + 1.2) at L = 1
  tf = 1        1 / 2.2                            ≈ 0.45
  tf = 2        2 / 3.2                           = 0.625
  tf = 10       10 / 11.2                          ≈ 0.89
  any tf        never more than                       1

Length: one mention, in a listing twice the average
  tf = 1        1 / (1 + 1.2 × (0.25 + 0.75 × 2))  ≈ 0.32

One mention of "merino" is worth 9.9 × 0.45, about 4.5.
Ten mentions of "jacket" are worth 1.6 × 0.89, about
1.4. "the" scores almost nothing however often it
appears, so stop words can stay in the index, where
phrase queries need them.

A query for jacket matches 2 million listings, and the page shows 10. Lucene doesn't score all 2 million. Its postings store, for each block, enough to work out the highest score any document in that block could reach. So a top-10 query skips the blocks that can't beat its current tenth result. A product can also mix the text score with other signals, such as popularity.

Segments: how the index changes

Lucene never changes a file once it has written it. New documents collect in a buffer in memory. When the buffer is written out, it becomes a segment: a small, complete inverted index with its own dictionary and postings, covering only the documents in it. Lucene's file format documentation says an index changes in two ways only: new segments for new documents, and merges of existing segments.

A search runs against every segment and combines the results. Each extra segment is one more dictionary to look up and one more set of lists to read on every query. So a background merge keeps the count down. Lucene's default merge policy merges segments of about the same size, up to 10 at a time, and stops growing a segment at about 5 GB.

A delete can't remove anything from a segment. Instead, each segment has a small extra file that marks which of its documents are still live, and a delete marks the document dead there. The dead document's postings stay on disk, and every query that reaches them checks the mark and skips them. They go only when a merge copies the segment's live documents into a new segment. By default, Lucene merges often enough to keep deleted documents under 20 percent of the index.

An update is a delete and then an add. Elasticsearch's update API saves a round trip, and its documentation says the document must still be reindexed. So changing one field costs as much as indexing the document from scratch: it's analysed again, written into a new segment, and the old copy waits for a merge.

How an index changes
Each refresh writes the buffer out as a new segment (1). Updating listing 42 marks its old copy in segment 1 as deleted, in grey, and writes the whole new listing into segment 3, in green (2). A merge copies only the live documents of segments 1 to 3 into one bigger segment (3), and the deleted copy is gone.Each refresh writes the buffer out as a new segment (1). Updating listing 42 marks its old copy in segment 1 as deleted, in grey, and writes the whole new listing into segment 3, in green (2). A merge copies only the live documents of segments 1 to 3 into one bigger segment (3), and the deleted copy is gone.
Nothing is edited: new segments are added, and merges drop what was deleted. Each refresh writes the buffer out as a new segment (1). Updating listing 42 marks its old copy in segment 1 as deleted, in grey, and writes the whole new listing into segment 3, in green (2). A merge copies only the live documents of segments 1 to 3 into one bigger segment (3), and the deleted copy is gone.

Log-structured merge (LSM) trees use the same design for key-value storage, as LSM trees vs B-trees describes. The shape matches, and two details differ.

LSM treeLucene
written fromthe memtable, when it fillsthe indexing buffer, at each refresh or flush
the file, once writtenan SSTable, never changeda segment, never changed
background workcompactionmerging segments of similar size, like size-tiered compaction
a deletea tombstone, written as a new entrya mark against the old copy, in its segment's live-documents file
a readstops at the newest copy; Bloom filters skip filesreads the term in every segment and combines the results

The reads differ because the questions differ. An LSM point read wants one key, so it can stop at the newest copy, and a Bloom filter lets it skip most files. A search for jacket wants every document that contains it, and jacket is in every segment. No filter can rule a segment out, so every query pays for every segment, and that's why merging matters to search.

The deletes differ because a document lives in exactly one segment. An LSM tombstone has to move down through compaction until it meets the old value. Lucene can mark the old copy directly in its own segment's live-documents file, which is a separate small file, so the segment itself doesn't change. The space comes back when that one segment is merged.

Near-real-time refresh

Writing a segment durably to disk is a Lucene commit, and it's too slow to run on every change. So Elasticsearch does two cheaper things. Before it acknowledges a write, it records it in the translog, its write-ahead log, so an acknowledged write survives a crash. Write-ahead logs covers how that log works. Then once a second it runs a refresh. A refresh writes the buffer out as a new segment into the filesystem cache, without waiting for the disk, and opens it for search.

That's what near-real-time means. A write is safe when it returns, and searchable after the next refresh, up to a second later. Until then, no list holds it, so no query can find it.

Acknowledged, but not yet searchable
The write is recorded in the translog and acknowledged at 0.2 s (1). A search at 0.5 s reads only the segments that existed before the write, so it misses the new listing, in red (2). The refresh at 1.0 s writes the buffer out as a segment (3), and a search at 1.3 s finds it, in green (4).The write is recorded in the translog and acknowledged at 0.2 s (1). A search at 0.5 s reads only the segments that existed before the write, so it misses the new listing, in red (2). The refresh at 1.0 s writes the buffer out as a segment (3), and a search at 1.3 s finds it, in green (4).
A search between the write and the refresh misses it. The write is recorded in the translog and acknowledged at 0.2 s (1). A search at 0.5 s reads only the segments that existed before the write, so it misses the new listing, in red (2). The refresh at 1.0 s writes the buffer out as a segment (3), and a search at 1.3 s finds it, in green (4).

Refresh has a cost. Each one makes a segment, and every segment is searched and later merged. Elasticsearch's indexing guide says frequent refreshes hurt indexing speed, and suggests a longer interval when the product can wait.

A seller lists a jacket, then searches for it to check, and it isn't there. The write succeeded, and search hasn't caught up. So how does the seller see their own listing, without making every write pay for it?

Naive

Force a refresh on every write

Elasticsearch has a parameter for it: refresh=true makes the write visible before the call returns. It's one flag, and the seller's listing appears every time.

Elasticsearch's own documentation warns against it. Each forced refresh makes a tiny segment, so you pay three times: to write it, to search it on every query, and to merge it later. The catalogue fits in one shard, so at 100 listings a second that's 100 new segments a second, 8.6 million a day, every one of them searched until it's merged.

Senior

Wait for the next refresh on the seller's write

Use refresh=wait_for on the write the seller makes. The call doesn't force anything. It waits until the regular refresh has made the change visible, then returns. Segments are made at the usual rate, and the seller's next search finds the listing.

This is what most teams do. The cost is that saving a listing now takes up to one refresh interval longer, up to a second at the default. And it only works when the application writes to the index itself. If the listing reaches the index through a change stream from the database, the seller's request never touches the index, so there's nothing to wait on. The next tier asks whether search has to show this listing at all.

Staff

Show the seller's write from the source, and let search lag

Only one person needs to see this listing at once: the seller who just made it. So serve that from the database, which already has it. The response to "create listing" returns the new listing. The client adds it to the seller's results for the next few seconds, or the seller's "my listings" page reads the database directly. Search stays eventually consistent for everyone, and no write waits on it.

Size the window. It's the pipeline's lag plus up to one refresh interval, a few seconds, and only the writer is inside it. Every other user would see the listing a few seconds late anyway, and none of them knows it exists yet.

What you give up: the client now merges two sources, and the added listing's position is a guess rather than a score. If the seller's other devices must see it too, the merge moves to the server. The search service reads the user's recent listings from the database and adds them to that user's results.

Sharding by document or by term

An index too big for one machine has to be split, and IIR names the two ways.

By document. Each shard holds a complete index of some of the documents. IIR also calls this a local index.

By term. Each shard holds the complete postings of some of the terms. IIR calls this a global index.

Splitting by term looks efficient, because a two-word query touches at most two shards. IIR gives the reasons it's the less common choice. To intersect two terms, one shard has to send its list to the other. The engine sends the shorter list, so merino jacket ships only merino's 500 IDs. Two common words are the expensive case: waterproof jacket ships at least 1.5 million IDs, about 1 MB at 6 bits an ID, for one query. The load also follows which words people search for, and that shifts and spikes. And a new document touches the shard of every term in it, so indexing gets harder.

Two ways to split one index
On the left, each shard indexes a quarter of the listings, so the query goes to all four (1), each returns its own top 10, and the coordinating node merges them (2). On the right, shard A holds the terms a to l and shard B holds m to z. The query touches only those two, but waterproof's 1.5M IDs, the shorter list, in red, have to travel to shard A for the intersection (3).On the left, each shard indexes a quarter of the listings, so the query goes to all four (1), each returns its own top 10, and the coordinating node merges them (2). On the right, shard A holds the terms a to l and shard B holds m to z. The query touches only those two, but waterproof's 1.5M IDs, the shorter list, in red, have to travel to shard A for the intersection (3).
By document, every query asks every shard; by term, long lists cross the network. On the left, each shard indexes a quarter of the listings, so the query goes to all four (1), each returns its own top 10, and the coordinating node merges them (2). On the right, shard A holds the terms a to l and shard B holds m to z. The query touches only those two, but waterproof's 1.5M IDs, the shorter list, in red, have to travel to shard A for the intersection (3).

Elasticsearch splits by document. Each document goes to the shard that its routing value hashes to, and the routing value is the document's ID unless you set one. Every search goes to every shard. Each shard runs the query on one thread and returns its own top hits, and the node that received the search merges them. That's scatter-gather, and partitioning and sharding works out its cost: a search that asks N shards waits for the slowest of them.

Splitting by document also splits the statistics. By default, Elasticsearch scores each document with the term counts of its own shard. Its dfs_query_then_fetch search type first collects the counts from every shard, which is slower.

Shards are for size, and replicas are for searches. Elasticsearch's guidance is shards of 10 to 50 GB and under 200 million documents, and the number of primary shards is fixed when the index is created.

To serve more searches, add replicas. A replica is a full copy of a shard, and it can answer any search for that shard.

Keeping the index in step with the source

A search index is a derived data store: everything in it was built from a database that holds the truth. It needs every change, deletes included, and the dependable way to get them is the database's own log. Change data capture covers reading that log, the order of changes to one row, and making a late or repeated change harmless.

Three things are specific to the index end.

The indexer needs the full row. The index can't apply "price changed" to a listing. Each change has to arrive as the row as it stands after the change, or the indexer reads the row from the source.

Staleness adds up. A change is searchable after the pipeline's lag, plus up to one refresh interval.

Rebuilds are routine. A new analyzer, a changed field type, or drift you can't explain all end the same way: build a new index from the source and move the readers to it. In Elasticsearch, readers query an alias, a name that points at an index. The aliases API moves the name from the old index to the new one in one atomic step. It's the same move as changing the key in caching strategies and invalidation: nothing is edited in place, and readers are pointed at a new name.

Rebuilding behind an alias
The application searches the alias listings, which points at listings_v1. A rebuild job copies the source into listings_v2 with the new analyzer (1), and the indexer applies changes from the database's log to both indexes, from the point where that copy began (2). When v2 has caught up, one atomic call moves the alias (3), and v1 is deleted later.The application searches the alias listings, which points at listings_v1. A rebuild job copies the source into listings_v2 with the new analyzer (1), and the indexer applies changes from the database's log to both indexes, from the point where that copy began (2). When v2 has caught up, one atomic call moves the alias (3), and v1 is deleted later.
Readers never see a half-built index, because they follow a name. The application searches the alias listings, which points at listings_v1. A rebuild job copies the source into listings_v2 with the new analyzer (1), and the indexer applies changes from the database's log to both indexes, from the point where that copy began (2). When v2 has caught up, one atomic call moves the alias (3), and v1 is deleted later.

The new index has to start from a copy of the source that lines up with a point in the change stream, or changes made during the copy go missing. Every write into the index carries a version in commit order, so a row copied early can't overwrite a newer change. The copy runs through the connector as an incremental snapshot, so its rows share that order. The change data capture page covers both. The question here is how long a rebuild takes, because that decides whether you can afford one.

Back of envelopeHow long a full rebuild takes
The question is whether rebuilding from the source is a
routine job or a project. The working figure for writes
to a search node, from choosing a database: 5,000 to
20,000 a second.

The 10M-listing catalogue: one shard, so one node indexes
  time     10M / 20,000 to 10M / 5,000    ≈ 8 to 33 minutes

A 500M-document index on 10 nodes
  rate     10 × 5,000 to 10 × 20,000  = 50,000 to 200,000/s
  time     500M / 200,000 to 500M / 50,000
                                ≈ 42 minutes to 2.8 hours

  disk     while both indexes exist        twice the index

For scale, GitHub re-indexes its whole code search corpus,
15.5B documents, in about 18 hours, because delta
indexing skips over half of them.

A rebuild takes minutes to hours, so it can be the plan
for every change to analysis, not a project.

A team that has never rebuilt is stuck with the analysis it chose on the first day, because every list in the index was written by it.

The method

1. Write the searches as sentences. "Find listings that match the words a buyer typed, best first." "Find notes inside one tenant." "Find this exact phrase in a title." Note which need phrases, substrings, filters or a sort order.

2. Choose the analysis for each field. Stemmed words for descriptions, ngrams for substrings, exact values for IDs and filters. Store positions only on fields that are searched by phrase.

3. Size the index. A compressed index with positions is a third to a half of the raw text. Check that the postings fit in half of a node's memory.

4. Price the slowest search. That's the one with no rare word, the one that pages deep, and the number of shards every search asks.

5. Set the freshness from the product. Choose the refresh interval, and decide how a writer sees their own write.

6. Choose the shards. Keep each shard at 10 to 50 GB, and route by tenant if every search carries one.

7. Plan the feed and the rebuild. Feed the index from the database's log, send whole documents, read through an alias, and know how long a full rebuild takes.

Worked examples, start to finish

Each of these three examples breaks a different obvious answer.

A help centre, where Postgres is enough

A software company keeps 6,000 help articles in Postgres, about 1,500 words each. Customers search them about 20 times a second. The reflex answer is to add Elasticsearch.

Size it first. At about 6 characters a word, the articles hold 6,000 × 1,500 × 6 bytes, about 54 MB of text. Even if the tsvector column and its GIN index were each as big as the text, the total would be under 200 MB, which fits in the memory of a small database server. A search whose words appear in every article ranks 6,000 rows, and most searches rank far fewer.

So stay in Postgres. Add a generated tsvector column built from the title and the body, with title words labelled A and body words labelled D, and index it with GIN. Rank with ts_rank, whose default weights count an A word 10 times a D word, 1.0 against 0.1.

That decision removes a second data store, the change pipeline, the refresh gap and the rebuild plan. A help article is searchable the moment its transaction commits.

Watch two numbers to know when to move. The first is how many rows the commonest search words match, because every search ranks all of them. The second is whether the product needs rarity in its ranking, the IDF that ts_rank doesn't have. When either becomes a problem, a search engine is worth the pipeline it needs.

View counts, where every update rewrites the listing

A marketplace indexes 10 million listings of about 2 KB each. Sellers create or edit 100 listings a second. The team wants search to rank by popularity, so it puts a view_count field in each listing and updates it on every view, 3,000 views a second.

Back of envelopeWhat view counts cost when they live in the index
The question is what the index does when every view
updates the listing's count.

Listings indexed
  edits         sellers' creates and edits          100/s
  views         each a whole listing              3,000/s
  ───────────────────────────────────────────────────────
  indexed       100 + 3,000                     = 3,100/s
  counts only   3,000 / 3,100                       ≈ 97%

Deleted copies left behind
  per second    one per view                      3,000/s
  per day       3,000 × 86,400                     ≈ 259M
  about 26 times the 10M live listings

Merging them away
  Lucene keeps deleted copies under 20% of the index.
  If deletes are spread evenly, a merge copies about
  4 live listings for each deleted one it drops.
  copied        3,000 × 4                      = 12,000/s
  bytes         12,000 × 2 KB                   ≈ 24 MB/s

For 100 real changes a second, the index analyses 3,100
listings a second and merges about 24 MB a second.

The rate isn't the problem: choosing a database puts a search node at 5,000 to 20,000 writes a second, so one node can take 3,100. The cost is 31 times the indexing CPU that the sellers' edits need, and merges that never stop, competing with queries for disk and the filesystem cache. So take the count out of the index.

Keep live view counts in Redis or the database, where an increment is one small write. Add a popularity field to the index, recomputed once a night and written in one bulk job. That rewrites each listing once a day instead of 26 times, and a full pass over 10 million listings takes 8 to 33 minutes on one node, by the rebuild worksheet above. The results page shows exact counts by reading them from Redis for the 10 listings it displays.

What you give up: ranking uses last night's popularity, so a listing that becomes popular in the morning doesn't rank higher until the next night's job. If that matters, recompute every hour, and write only the listings whose popularity moved enough to change their rank.

Search inside each tenant, where every query hits every shard

A notes app has 20,000 tenants and 500 million notes, and every search is inside one tenant. Assume the index is 600 GB on disk, so it gets 20 shards of 30 GB, inside Elasticsearch's 10 to 50 GB guidance. At peak, users run 2,000 searches a second, and the team wants room to grow.

Back of envelopeShard searches for 2,000 tenant searches a second
The question is how much work each layout does per
search. Assume a shard search costs about 10 ms of one
core with or without routing: each shard holds a
twentieth of all notes either way, and one small
tenant is a tiny part of that. Each shard answers
slower than its own p99, the time 99 in 100 of its
answers beat, one time in 100.

Every search goes to all 20 shards
  shard searches  2,000 × 20                   = 40,000/s
  cores busy      40,000 × 10 ms                    = 400
  hit a slow one  1 − 0.99^20                       ≈ 18%

Each tenant's notes on one shard
  shard searches  2,000 × 1                     = 2,000/s
  cores busy      2,000 × 10 ms                      = 20
  hit a slow one  one shard                          = 1%

Routing means 20 times fewer shard searches, so 20 times
less CPU on that assumption, and the slow tail falls from
about one search in five to one in 100.

So how should the index grow to serve more searches, when every search belongs to one tenant?

Naive

Add shards

More shards means more machines working on each search, so it feels like the way to scale.

The worksheet breaks it. Every search already asks all 20 shards, so each new shard adds one more shard search to every query. At 40 shards, the same 2,000 searches a second become 80,000 shard searches, and the chance of waiting on a slow shard rises from 18 to 33 percent. Elasticsearch's own sizing guide warns that a search across many small shards can use up a node's search threads.

Senior

Keep shards sized by data, and add replicas for searches

Set the shard count from the data, 20 shards of 30 GB, and add replicas to serve more searches. Each replica is a full copy that can answer any search for its shard, so two replicas give three copies to spread the load over. Filter every search by tenant_id.

This is what most teams run. The cost is that every search still asks 20 shards: 400 cores busy at today's peak, and more hardware for every extra search. The next tier asks why a search for one tenant asks shards that hold none of its notes.

Staff

Route by tenant, so each search asks one shard

Index every note with routing set to its tenant ID, and send the same routing value with every search. Elasticsearch hashes the routing value instead of the document ID, so all of one tenant's notes land on one shard, and its searches go only to that shard. Each search still filters by tenant_id, because the shard holds other tenants' notes too. The worksheet prices it: 2,000 shard searches a second instead of 40,000, 20 cores instead of 400, and a slow tail of 1 percent.

The cost is balance. Tenants differ in size, and one shard holds whatever tenants hash to it. A tenant with 5 percent of the notes would fill a 30 GB shard alone. Elasticsearch's routing_partition_size spreads each routing value over a few shards instead of one, at the cost of asking that many shards per search. The biggest tenants can also get an index of their own.

Two more costs. Every write, read and delete has to carry the routing value, or a note can end up on two shards, and Elasticsearch can make the value required. And the shards now hold documents grouped by tenant, so the term counts behind each score come partly from whichever tenants share the shard.

Where it goes wrong

These are ordered by how often they come up.

1. Expecting a match that analysis never wrote

A search for fox misses foxes under the standard analyzer, because it doesn't stem. The index holds only what analysis produced, and the query only matches that. Run your own text and the queries users type through the _analyze API, and compare the terms before you blame ranking.

2. Updating the index like a table row

A field that changes on every view or click turns a small edit rate into constant reindexing and merging, so keep it outside the index.

3. Forcing a refresh on every write

Each refresh=true makes a tiny segment that every search reads until it's merged; show the writer their write from the database instead.

4. Adding shards to serve more searches

Every search asks every shard, so each shard you add is one more shard search per query, as worked example 3 shows.

5. Paging deep with from and size

To return results 10,000 to 10,010, every shard has to find and send its own top 10,010, because any shard could hold them. Elasticsearch refuses to page past 10,000 hits this way by default. Use search_after, which continues from the last hit of the previous page.

6. No plan for a rebuild

An index fed by a pipeline and never rebuilt drifts from the source, and the first analyzer change turns into a migration. Read through an alias, and know how long a full rebuild takes before you need one.

If you memorise nothing else

factwhy it matters
A B-tree can't find a word inside a valuean inverted index maps each term to the documents that contain it
Every match, score and visible document comes from lists built at write timethe query only reads them
A query matches only the terms analysis wrotethe same analysis runs on the query; a new analyzer means a full reindex
Elasticsearch's standard analyzer doesn't stemfox doesn't match foxes
An AND query is driven by its rarest termskips decode only the blocks it lands in; all-common queries read everything
Postings store gaps, packed into few bitsthe lists queries read stay in memory
A positional index is 2 to 4 times one without positionsstore positions only where phrases are searched
BM25 levels off with repetition and weights rare termsdefaults k1 = 1.2, b = 0.75; stop words already score near zero
Segments are never changed; merges drop deleted copiesthe same design as an LSM tree, with deletes marked in a separate file
An update is a delete plus a whole new documentfast-changing fields don't belong in the index
A write is searchable after the next refresh, 1 second by defaultrefresh=true on every write makes tiny segments
Split by document, and every search asks every shardshards for size, replicas for searches, routing for tenants
Shards of 10 to 50 GB, under 200M documentsthe shard count is fixed when the index is created
A search index is derived from the sourcefeed it from the log, read through an alias, rebuild in minutes to hours

What is expected at each level

Mid-level

Know what an inverted index is: a sorted term dictionary, and a sorted postings list of document IDs for each term. Know that analysis turns text into terms, that the query is analysed the same way, and that an AND query intersects the lists. Know that Elasticsearch is near-real-time: a new document becomes searchable after a refresh, about a second later.

You aren't expected to size postings or choose a sharding layout unprompted. If asked "why can't we use LIKE?", a good mid-level answer is "a B-tree is sorted from the first character, so it can't find a word in the middle of a value."

Senior

You lead this part of the discussion, and three things must come up without prompting.

Analysis per field. Say what each field becomes on the way in: stemmed words, ngrams or exact values. Say that changing it means a reindex.

The cost of a change. Name the fields that change too often to live in the index, and say what each change costs.

Freshness and the feed. State the lag in seconds, and say how the index stays in step: change data capture from the source, not a dual write.

Two things are disqualifying: treating the search index as the source of truth, and adding shards to serve more searches.

Staff+

Producing a correct design is still the bar. A staff answer stands out by placing the work where it's cheapest, with numbers.

Price the query shape. The rarest term sets an AND query's cost, every shard pays for every search, and deep pages cost every shard. Find the slowest search before you size anything.

Route instead of broadcasting. When every search carries a tenant, route by it, and say where the biggest tenants go.

Keep read-your-writes out of the index. Show the writer their own write from the source, and let search lag for everyone else.

Make the rebuild routine. Readers on an alias, a rebuild measured in minutes to hours, and analysis changes planned as rebuilds.

And say what you would not build. Each of these can cost a team a quarter.

One is an Elasticsearch cluster and its sync pipeline for a few thousand help articles that Postgres's GIN index serves from memory. Another is a term-partitioned index built for query efficiency, when multi-word queries of common words would ship long lists across the network. A third is a tuning project on refresh and merges for an index that is slow because view counts are written into it.

Another is a cluster grown to 40 shards to serve more searches, when routing by tenant would have cut each search to one shard search. And the last is a custom stemmer, before anyone has run the queries users type through the _analyze API.

Sources

These are the pages behind the stated figures. The sizing, skip, scoring and merge arithmetic is worked out on this page from them.

  • Introduction to Information Retrieval, Manning, Raghavan and Schütze, Cambridge University Press 2008, free online. Intersecting postings rarest term first, and skip pointers for AND queries only. Variable-byte codes with the Reuters figures. Positional indexes at 2 to 4 times the size, and a compressed index at a third to a half of the text. BM25's usual parameters, and partitioning by term against by document.
  • Lucene's postings format, for gaps packed in blocks of 256, a skip entry per block and per-block scores, and BM25Similarity, for the scoring formula and its defaults of 1.2 and 0.75. The index file formats for 32-bit document IDs, and TieredMergePolicy for merges of up to 10 segments, 5 GB segments and the 20 percent limit on deleted documents.
  • Elasticsearch's guides. Near real-time search for the one-second refresh, and shard sizing for 10 to 50 GB and 200 million documents a shard. Search speed for half of memory to the filesystem cache, and pagination for the 10,000-hit limit.
  • PostgreSQL's text search controls: ranking that reads every matching row's tsvector, and the default weights of 0.1 to 1.0.
  • The technology behind GitHub's new code search, GitHub, 2023. The grep arithmetic, the ngram index, every query sent to every shard at about 100 ms each, and re-indexing 15.5 billion documents in about 18 hours.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.