Why you need a search system, and when to use one
Scanning every document for a word is fine for a hundred notes and impossible for a hundred million. Users also expect results to be ranked, forgiving of typos and quick. A search system builds an inverted index ahead of time, so a query looks up words rather than reading documents, then ranks the matches.
It gives you two things interviewers always ask about:
- Low latency at scale: answers in tens of milliseconds across millions of documents.
- Relevance: the best matches first, with support for phrases, filters and typo tolerance.
Use it when:
- Users search text by words, with ranking.
- You need filters and facets (price range, brand) alongside text.
- A database
LIKE '%word%'query is too slow or too crude. - You need autocomplete, typo tolerance or highlighting.
Skip it, or use something else, when:
- You search by exact keys or ranges: a database index is enough.
- The data is small: your database's built-in full-text search may be enough.
- You need strong transactional consistency with the source data. A search index is a derived copy that lags behind.
Try it
Search for a word using a scan and using an index. Then add a new document.
Search Systems
Step 1 of 3 · Press Space to play, arrow keys to stepInitial state. The system holds 1000000 documents (each toy document stands for 125,000 real ones). A user searches for "sharding".
- tick:
- 0
- documents examined:
- 0
- documents found:
- 0
1 tick = one step of the simulation.
Things to try:
- Run the Inverted index with a rare word. It examines only the documents that contain it.
- Run Scan every document with the same query and compare the work.
- Choose A document was just added and see which method finds it. Search indexes are refreshed on a schedule, so they are near real time, not instant.
What to watch. The simulation uses 8 toy documents, each standing for 125,000 real ones, so 1,000,000 in all:
- Scan, rare word: 1,000,000 documents examined, 125,000 found.
- Index, rare word: 125,000 examined. That is 8 times less work.
- Index, common word "cache": 500,000 examined, only 2 times less than the scan. The advantage shrinks as more documents match.
- A document was just added: the scan examines 1,125,000 and finds 250,000. The index examines 125,000 and finds 125,000, because the new document is not refreshed into it yet.
Search approaches
| Approach | How it works | Good when | Weakness |
|---|---|---|---|
| Scan all documents | Read each one and look for the words | Tiny datasets | Cost grows with data |
Database LIKE | Pattern match in the database | A few thousand rows | Cannot use a normal index for a leading wildcard, no ranking |
| Database full-text search | Built-in inverted index and ranking | Moderate scale, one database | Fewer features, shares resources with transactions |
| Dedicated search engine | A separate inverted index service, sharded and replicated | Large scale, rich features | Another system to run and keep in sync |
| Vector search | Compare numeric meaning vectors | Search by meaning, not exact words | Approximate, needs embeddings |
Scan vs inverted index
- Scan: cost is proportional to the number of documents, whatever the query.
- Inverted index: a map from each term to a posting list of the documents containing it. A query looks up each term and combines lists. Cost depends on the number of matches, so rare words are very cheap and very common words cost more. With several words, the engine combines lists, so the work also depends on how long they are, and ranking costs more as more matches must be scored.
An index trades space and build time for query speed.
A small illustrative example, using the eight toy documents from the simulation below (numbered 1 to 8):
| Term | Posting list (documents containing it) |
|---|---|
| cache | docs 1, 2, 5, 8 |
| database | docs 4, 5 |
| sharding | doc 4 |
A search for "cache database" looks up two lists and keeps the documents in both. Only doc 5 ("cache and database together") is in both, so the engine never reads docs 3, 6 or 7.
How a search works
- Indexing: each document is split into words (tokenised), lower-cased, stripped of common words (optional, as many engines keep them and rely on ranking) and reduced to a root form (stemming). The terms are added to the inverted index.
- Querying: the query goes through the same steps. For each term, the engine reads its posting list. For "red shoes" it intersects the lists.
- Ranking: matches are scored, usually by TF-IDF or BM25: a term counts more when it appears often in a document and rarely in the whole collection. Business signals such as popularity can be mixed in.
- Scaling out: the index is split into shards, each holding part of the documents. A query goes to all shards, each returns its best results, and a coordinator merges them. Replicas add read capacity and availability.
- Freshness: new documents are added to small in-memory segments that become searchable after a refresh (about a second in many engines), and segments are merged in the background.
Three costs to remember. The shard count is usually fixed when an index is created, so choose it with growth in mind or plan to reindex into a new index. A query waits for its slowest shard, so one overloaded shard slows every search. Deep paging is costly because, for page 10,000, every shard must return all of its top results up to that offset and the coordinator must merge them. Each shard also scores with its own term statistics, so ranking can differ slightly when shards are small or unevenly filled.
Search system vs the alternatives
| Concern | Search engine | Database full-text | Database LIKE |
|---|---|---|---|
| Speed at large scale | Fast | Medium | Slow |
| Ranking and relevance | Rich | Basic | None |
| Typos, synonyms, facets | Yes | Limited | No |
| Always up to date | Near real time | Yes | Yes |
| Extra system to run | Yes | No | No |
| Best for | Search-centred products | Moderate search | Tiny tables |
Use the database's search until it hurts, then move to a search engine and keep it in sync.
Avoiding a new single point of failure
- Source of truth: the database remains the master, and the index is a derived copy that can be rebuilt.
- Cluster: several shards with replicas, so losing a node loses neither data nor capacity.
- Sync: feed changes from the database through a queue or change stream, and run a periodic full rebuild to fix drift. Send the document id and a version (for example a last-modified time) with each update, so a retried or out-of-order update cannot overwrite newer data with older data.
- Fallback: if search is down, show browse pages or a simpler database query.
You accept that search results can lag behind the database by seconds.
Common mistakes
- Treating the search index as the source of truth. It can be rebuilt, the database cannot.
- Updating the index inside the user's request. Use a queue so a slow index does not slow writes.
- Too many shards. Each shard has overhead.
- Indexing everything. Index only searchable fields, and use filters for exact values.
- No reindex plan. Changing the analysis needs a rebuild into a new index and a swap.
- Ignoring deep paging. Fetching page 10,000 is expensive. Use cursors.
- Applying updates without a version. A retry or a late message can replace a newer document with an older one. Version every update.
How to talk about search in an interview
- Define what is searched, the scale, and how fresh results must be.
- Explain the inverted index, tokenising, ranking and sharding with a merge step.
- Say the database is the source of truth and changes flow to the index through a queue.
- Name the trade-off: a separate index gives fast, ranked search but is eventually consistent and one more system to operate.
Related topics
- Replication and sharding for how an index is split and copied.
- Message queues and async for the sync path from database to index.
- Typeahead autocomplete for search-as-you-type on top of an index.
- Storage internals and indexing for how index structures are stored on disk.
- Caching for caching popular queries.