Full-text and fuzzy search
LIKE "%term%" cannot rank, tokenise or tolerate typos.
Say it like this
Users need ranked, typo-tolerant search over text, which a database LIKE cannot do, so I keep an inverted index in a search engine fed from the primary store and treat it as a rebuildable derived copy.
Basic solution
Keep an inverted index in a search engine, fed from the primary store by events or CDC.
Derived index fed from the primary store
The database stays the source of truth. A change stream keeps the inverted index current within seconds, and queries scatter to index shards and gather the top results.
How it works
- Documents are analysed at index time: the text is split into tokens (words), lower-cased, stemmed so that running becomes run, and common stop words such as "the" are dropped. The result is the list of terms the document can be found by.
- The engine builds an inverted index: for each term, a posting list of the ids of the documents that contain it, with the positions and how often the term appears. It is "inverted" because it maps word → documents instead of document → words.
- A query goes through the same analyser so its tokens match the index, then the engine intersects (AND) or unions (OR) the posting lists for the query tokens to find candidate documents.
- Matches are scored with BM25, which gives more weight to rarer terms and to shorter documents, and the top k are returned with the matching fragments highlighted.
- The index is a derived copy, never the source of truth. Writes go to the primary database first; an event or change-data-capture stream updates the index within seconds.
What makes it fast
- Posting lists are sorted and compressed, so intersecting them across millions of documents is a merge of a few small lists rather than a scan.
- The index is sharded by document and replicated, so a query scatters to every shard in parallel and gathers each shard's top k.
Worked example
Video search for a streaming platform
- Catalogue of 500M videos; fields title, description, tags, channel. Average document ~1 KB of text.
- Index size: roughly 30% of raw text with positions, about 150 GB; with 2 replicas, 450 GB in all across, say, 15 primary shards of 10 GB each (45 shard copies), so each shard fits comfortably in one node's memory.
- Query load: 100M DAU, 3 searches per user per day ≈ 3,500 queries/s average, ~10K/s at peak. Each query hits all 15 shards, so 150K shard-queries/s; at ~2 ms each that is 300 cores of search capacity, say 40 nodes with headroom.
- Freshness: a new upload becomes searchable within ~5 s via the change stream; a user searching for their own just-uploaded title in under a second may not find it, which the UI explains.
- Ranking: BM25 on title and description, boosted by recency and a popularity signal (views in the last 7 days) applied as a function score on top of the text score.
Variants and when each wins
Dedicated search cluster (Elasticsearch, OpenSearch)
- A separate cluster with analysers, BM25 scoring, aggregations, highlighting and vector search. It wins when search is a product feature in its own right; it is another stateful system to run and keep in sync.
Lightweight engines (Meilisearch, Typesense)
- Typo tolerance and instant results with far less to operate. They win for catalogues up to tens of millions of documents; aggregation features are thinner.
In-database full text (Postgres tsvector + GIN index)
- The database tokenises and ranks inside the same transaction as the data, with no extra system. It wins until search needs typo tolerance or scale; it competes with transactional queries for the same CPU.
Managed (Algolia, Elastic Cloud, OpenSearch Service)
- Someone else runs the cluster and you pay per record or per node. It wins for a small team that would rather not operate search.
Pick Postgres full text until search is a product feature in its own right; then a managed Elasticsearch or OpenSearch, or Meilisearch for a smaller catalogue that needs instant typo-tolerant results.
Failure modes
Index drifts from the database
- Search shows a deleted video or an old title. It happens because an update event was missed, or two updates for the same document were applied out of order. Fix it by versioning each document so an older update cannot overwrite a newer one, and by running a periodic full reindex from the source of truth.
Reindex takes hours and the mapping is wrong
- Changing an analyser or a field type means rebuilding the whole index while search has to stay up. It happens because the mapping (the index's schema) is fixed when the index is created. Fix it by building the new index alongside the old one, backfilling it, then flipping an alias so queries move over at once; never mutate the live index.
Deep pagination
- Page 1,000 of a result list times out. It happens because to return results 10,000 to 10,010 every shard must compute and send its own top 10,010 for the coordinator to merge. Fix it by capping how deep users can page, using search_after with a sort cursor for scrolling, and encouraging users to refine the query.
Hot shard from a bad routing key
- One node is saturated while the others idle. It happens because documents were routed to shards by a skewed key, such as one channel that owns most of the catalogue. Fix it by using the default hash routing by document id, and only custom-route when a tenant is always queried in isolation.
Cluster memory pressure
- Queries slow down and then nodes drop out of the cluster. It happens because sorting or aggregating on a field loaded that whole field into heap memory. Fix it with doc values for sortable fields (columnar storage read from disk), limits on aggregation cardinality, and heaps kept at or under 32 GB with more nodes instead of bigger ones.
Interviewer follow-ups
Answer out loud before you open each one.
How do you keep the index in sync with the database?
Writes go to the database first; a change stream from the transactional outbox or CDC publishes each change, and an indexer applies it with the document version so late updates cannot overwrite newer ones. A nightly or on-demand full reindex from the database is the safety net because the index is a derived copy.
What does the index do with a typo like "netflx"?
Fuzzy matching: it looks for terms within a small edit distance of each query token, usually one or two edits for longer words, and scores those matches lower than exact ones. Edit-distance search is expensive, so engines bound it and often require the first characters to match.
How would you rank results beyond text relevance?
Keep BM25 as the base score and multiply or add signals the product cares about: recency decay, popularity, personalisation. Compute heavy signals offline and store them on the document so the query-time function stays cheap, then evaluate changes offline against click data before shipping.
Why not just add an index on the text column in Postgres?
A B-tree index only helps prefix matches; it cannot find a word in the middle of a sentence, stem words or rank. Postgres full text with a GIN index does tokenise and rank, and is the right first step; a dedicated engine is for typo tolerance, scale and richer ranking.
Connections
- Built on
- Bitmap index · Trie · Inverted index · Quadtree
- Pairs with
- React to database changes · Publish events reliably with the write · Precompute joins · Suggest as the user types · Rank instead of sorting by time
- Pulls against
- Key → value at any scale
The same parts on other clouds
The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.
| AWS | Used here as | Google Cloud | Microsoft Azure | Open source and others |
|---|---|---|---|---|
| Amazon DynamoDB | Metadata DB | Firestore, Bigtable | Cosmos DB | ScyllaDB, Apache Cassandra |
| Amazon Kinesis Data Streams | Change stream | Pub/Sub | Event Hubs | Apache Kafka, Redpanda, Apache Pulsar |
| Amazon EC2 Auto Scaling | Indexer, Search API | Compute Engine managed instance groups | Virtual Machine Scale Sets | Kubernetes Deployment with a HorizontalPodAutoscaler, Nomad |
| Amazon OpenSearch Service | Inverted index | Elastic Cloud on Google Cloud | Azure AI Search | Elasticsearch, OpenSearch, Apache Solr |