Highlights

Contents

Part IX
09

Search engines

We run search as its own system, kept in step with the database. Elasticsearch and OpenSearch distribute Lucene’s inverted indexes across machines, and the backend’s job is feeding them, changing them safely and keeping queries fast. We will cover how the engine stores and distributes data, the indexing pipeline with consistency and reindexing, and query latency across shards.

CHAPTER ATLAS / FOLLOW THE READING PATHCHAPTER ATLAS / FOLLOW THE READING PATH1Realtime options2The WebSocket protocol3Realtime applicationconcerns4Scaling realtime5File uploads6Object storage7Searching the database8Full-text search9Search engines10Vector and hybrid search11Track, upload and searchend to end

#Section 27Lucene, shards and segments

Lucene, the Java search library Doug Cutting began in 1999, implements everything in Part VIII, analyzers, inverted indexes, positions, BM25 and far more. Elasticsearch, released by Shay Banon in 2010, and OpenSearch, the Apache-licensed fork Amazon created in 2021, turn Lucene into a distributed service with a JSON API. Solr is an older sibling built on Lucene too.

An Elasticsearch index, a collection of documents such as Wren’s menu index, is split into shards, each a complete Lucene index holding a subset of the documents, routed by a hash of the document id. Each shard has a primary and one or more replicas on other nodes. Writes go to the primary and are copied to replicas. Reads can go to any copy, so replicas add both availability and read capacity. If a node dies, a replica on another node is promoted, and the cluster rebuilds missing copies elsewhere.

AN INDEX SPLIT INTO SHARDS, EACH WITH A REPLICA ON ANOTHER NODEAN INDEX SPLIT INTO SHARDS, EACH WITH A REPLICA ON ANOTHER NODEnode 1node 2node 3P0R1P1R2P2R0primaries (orange) take writes; any copy serves reads; losing a node loses no shard
Figure 12.35Three primaries spread across three nodes, each with a replica somewhere else.

A mapping defines each field’s type and analyzer, name as text with Wren’s food analyzer plus a keyword subfield for exact filtering and sorting, price as an integer, location as a geo point, cuisine as a keyword for faceting. Mappings are mostly fixed once data is indexed, since changing a field’s analysis means the stored terms are wrong, which is why mapping changes need the reindexing of the next section.

Inside each shard, Lucene writes data in segments, small immutable inverted indexes. New documents go first into an in-memory buffer. A refresh, every 1 s by default, turns the buffer into a new searchable segment, so a newly indexed document becomes visible to searches within about a second. That is why Elasticsearch is called near real-time rather than real-time. A translog, a write-ahead log, makes writes durable between the less frequent flushes that commit segments to disk. Segments are immutable, so deletes only mark documents as deleted, and updates are a delete plus a new document. Background merges combine small segments into larger ones and drop deleted documents.

INSIDE A SHARD: IMMUTABLE SEGMENTS, A REFRESH EVERY SECOND, BACKGROUND MERGESINSIDE A SHARD: IMMUTABLE SEGMENTS, A REFRESH EVERY SECOND, BACKGROUND MERGESin-memory bufferrefresh 1 smerged segmentnew documents become searchable at refresh, about 1 s: near real time, not immediatedeletes mark documents; merges reclaim them; a translog makes writes durable between commits
Figure 12.36New documents become a searchable segment at each refresh. Merges tidy small segments into big ones.

These internals explain common operational advice. A refresh interval of 1 s is expensive for bulk loads, so it is raised or disabled during a full reindex. Many updates to the same documents create many deleted entries until merges catch up. And very many small shards waste memory, since each shard has fixed overhead, which is why guidance suggests shards of roughly 10 to 50 GB.

#Section 28The indexing pipeline, consistency and reindexing

The search index is a copy, not the source of truth. Menu items live in PostgreSQL, and the index must follow every change. The indexing pipeline is the path from one to the other, and it has the same shape as Unit VII’s event-driven cache invalidation. Change data capture reads PostgreSQL’s WAL, Unit VIII, and publishes each change to a menu-events topic. An indexer service consumes the topic, builds the search document for each changed item, often joining data from several tables such as the restaurant’s name, location and rating, and writes it to Elasticsearch with the bulk API.

THE INDEXING PIPELINE: THE DATABASE STAYS THE TRUTH, THE INDEX FOLLOWSTHE INDEXING PIPELINE: THE DATABASE STAYS THE TRUTH, THE INDEX FOLLOWSPostgreSQLCDCmenu-eventsindexersearchindexa price change appears in search about 1 to 2 s later; the menu page reads the databaseindexers upsert by id with the source version, so replays and reorderings are harmless
Figure 12.37The database stays the truth. Changes flow through CDC and an indexer into the search index.

This makes search eventually consistent with the database. A price change commits at time 0, reaches the topic in tens of milliseconds, is indexed in a bulk request shortly after, and becomes searchable at the next refresh, so 1 to 2 s in total. Product design accepts that. Search results show prices from the index, and the menu page, opened from a result, reads the current price from the database, so a stale search result never becomes a wrong charge.

Incremental indexing must survive replays, reordering and failures. The indexer upserts by document id, writes the source row’s version with Elasticsearch’s external versioning, so an older event arriving late is rejected rather than overwriting newer data, and processes deletes as well as updates, since a dish removed from the menu must disappear from search. Unit VIII’s idempotency rules apply in full.

Some changes need a full reindex, an analyzer change, a new field derived from all data, a mapping fix, or recovery from a pipeline bug. Reindexing a live index in place is impossible, since the old and new terms would mix. The safe pattern uses an alias, a name that points to a real index. Searches use the alias menu, which points to menu_v7. Wren creates menu_v8 with the new mapping, backfills it from PostgreSQL in batches, with refresh disabled for speed, while the indexer writes every new change to both indexes. When menu_v8 has caught up and passes checks against judged queries, one atomic alias update points menu at menu_v8. Searches switch instantly, and menu_v7 stays for a few days as a rollback.

REINDEX WITHOUT DOWNTIME: BUILD BESIDE, THEN SWING THE ALIASREINDEX WITHOUT DOWNTIME: BUILD BESIDE, THEN SWING THE ALIASmenu (alias)menu_v7menu_v8new mappingbackfill v8 from the database, dual-write new changes, swap atomically, keep v7 for rollback
Figure 12.38Build the new index beside the old one, then swing the alias in one atomic step.

That is Unit VI’s expand and contract, applied to a search index, and it makes even large changes to search a routine operation.

#Section 29Query latency across shards

A search request to an index with 10 shards is a scatter-gather operation. The node that receives it, the coordinator, sends the query to one copy of every shard. Each shard finds and scores its own top results, say its top 20, and returns them. The coordinator merges the 10 lists, keeps the overall top 20, and fetches the full documents for those, a second round trip to the shards that hold them.

The query is as slow as its slowest shard. If each shard answers within its own p99 latency 99% of the time, the chance that all 10 do is 0.99¹⁰ ≈ 0.904, so about 9.6% of queries wait on at least one slow shard. With 50 shards, only 0.99⁵⁰ ≈ 60.5% of queries avoid every slow shard. This is the tail at scale of Unit X in its purest form, and it is why adding shards does not always make search faster.

SCATTER-GATHER: A QUERY IS AS SLOW AS ITS SLOWEST SHARDSCATTER-GATHER: A QUERY IS AS SLOW AS ITS SLOWEST SHARDcoordinatorshard 7 is slowif each of 10 shards is under its p99 99% of the time, 1 − 0.99¹⁰ = 9.6% of queries wait on a slow one
Figure 12.39Ten shards answer in parallel, and the query waits for the slowest.

The levers are several. Fewer, larger shards reduce fan-out, within the 10 to 50 GB guidance. Replicas give the coordinator a choice, and adaptive replica selection sends each shard request to the copy that has been answering fastest. Routing sends a query to a single shard when the data allows, for example routing each restaurant’s documents by restaurant id, so a search within one restaurant’s menu touches one shard. Caches help repeated queries, the node query cache for filters and the shard request cache for whole results. And timeouts with partial results let a query return what most shards found rather than waiting for a straggler, which suits many search products.

Query shape matters as much. Filters, such as cuisine = indian or is_open = true, do not affect scoring and are cached as bitsets, so they are cheap. Leading-wildcard queries and regular expressions over large text fields are expensive, the same as in PostgreSQL. Deep pagination, asking for results 10,000 to 10,020, makes every shard rank and return 10,020 results to the coordinator, Unit V’s offset problem multiplied by the shard count, so engines cap it and offer cursor-like search_after instead. Wren monitors search latency by query type, and the slow log records any query over 200 ms with its full body.