Key technologies
Elasticsearch
A search engine that people keep trying to use as a database. It is extraordinary at relevance and aggregations over text, and it is a derived copy of your data — never the source of truth.
Search appears in a surprising number of interview questions: product search for an e-commerce site, searching messages in a chat app, finding a restaurant “near me that does biryani”, log search in an observability system. The usual answer is “Elasticsearch”, and the usual follow-ups are how does the data get there, how fresh is it, and what happens when the index needs to change.
The one sentence to carry in: Elasticsearch is a search index you feed from your database, not a database you search. (OpenSearch, the AWS fork, behaves the same for everything here.)
What it actually is
Elasticsearch is a distributed layer over Apache Lucene, a library that builds and queries inverted indexes. An index in Elasticsearch is split into shards; each shard is one Lucene index, and each shard has replicas on other nodes for availability and read throughput.
A query fans out to one copy of every shard, each shard returns its best matches, and a coordinating node merges them — the scatter-gather from the partitioning lesson, done for you.
The inverted index
A database index maps a row to its values. An inverted index maps each term to the list of documents that contain it — like the index at the back of a book.
To find documents containing both “wireless” and “headphones”, Lucene intersects two sorted lists of
document ids, which is fast regardless of how long the documents are. A relational LIKE '%wireless%'
has to scan every row; this never does.
Analysis: where the terms come from
Before indexing, text goes through an analyzer: a tokenizer splits it into words, and filters lowercase them, strip punctuation, drop stop words and reduce words to stems (“running” → “run”). The same analyzer runs on the query, so “Running Shoes” matches a document saying “run shoe”.
Mapping a field as text makes it analyzed and searchable by word; mapping it as keyword keeps the
exact value for filtering, sorting and aggregations. Get it wrong and either status: "Shipped"
doesn’t match "shipped", or you can’t sort by a field because it was tokenised. Most string fields
want both: text with a .keyword sub-field. Mappings can’t be changed in place for existing
fields — fixing one means a reindex.
Relevance: why the right result comes first
Matching is the easy part; ranking is the product. By default Elasticsearch scores with BM25:
- Term frequency: a document mentioning “biryani” five times is more about biryani than one mentioning it once — with diminishing returns.
- Inverse document frequency: a match on a rare term (“hyderabadi”) counts for more than on a common one (“restaurant”).
- Length normalisation: a match in a short title counts for more than the same match in a long description.
Then you shape it: boost the title field over description, add a function_score for
popularity or recency, filter by location with geo_distance. Put hard constraints (in stock,
category, price range) in a filter clause — they don’t affect scoring and are cached — and only
the fuzzy matching in must/should.
Near-real-time, not real-time
New documents go into an in-memory buffer and become searchable only after a refresh, which writes a new Lucene segment. The default refresh interval is 1 second. Durability is separate: the translog records each write so it survives a crash before the segment is committed to disk.
So a product updated now appears in search about a second later. That is fine for search; it is wrong for “check stock before checkout”. Read stock from the database.
Segments are immutable, like Cassandra’s SSTables. An update is a delete-mark plus a new document,
and background merging combines small segments and drops deleted documents. Heavy update rates
cost merge work — which is why bulk loads often set refresh_interval: -1 and turn it back on after.
Getting data in: the sync problem
The database is the source of truth, and Elasticsearch has to follow it. Three ways, from worst to best:
- Dual writes from the application. Write Postgres, then write Elasticsearch. If the second write fails or the process crashes between them, the index silently disagrees with the database forever.
- Outbox + worker. Write an “index this” row in the same transaction as the change; a worker reads the outbox and updates Elasticsearch, retrying until it succeeds.
- Change data capture. Debezium reads the database’s WAL, publishes every change to Kafka, and a consumer indexes it. It catches every write path, including migrations and admin edits. See the CDC lesson.
Either way, keep a full reindex path: a job that rebuilds the index from the database. You will need it for every mapping change, and it is the recovery plan when the index drifts.
Reindexing without downtime
Because mappings and shard counts can’t be changed in place:
- Create
products_v2with the new mapping. - Backfill it from the database (or
_reindexfromproducts_v1), while the change stream writes to both indexes. - When caught up, atomically switch the alias
productsfrom v1 to v2. - Delete v1 later.
The application always queries the alias, so it never knows. Use aliases from day one.
Shards: picking the number
The primary shard count is fixed at index creation. Aim for shards of roughly 10–50 GB, and remember every shard costs memory and file handles on its node — a cluster with tens of thousands of tiny shards is slow and unstable. For time-based data (logs, events), use one index per day or week with an alias or data stream over them, so old data is dropped by deleting an index, not by deleting documents.
Where it hurts in production
- Deep pagination.
from: 10000, size: 20makes every shard collect 10,020 hits and sort them. Usesearch_afterwith a sort key instead. - Mapping explosion. Indexing arbitrary JSON with dynamic mapping creates a field per new key
until the cluster state is huge. Set
dynamic: strictor captotal_fields. - Heap pressure. High-cardinality aggregations and big
termslists live in JVM heap. Watch heap and circuit-breaker trips. - Split brain on small clusters. Run three dedicated master-eligible nodes so elections have a quorum.
Elasticsearch versus the alternatives
| Reach for it when | Avoid when | |
|---|---|---|
| Elasticsearch / OpenSearch | Relevance-ranked text search, faceting, log analytics | It would be your only copy of the data |
| Postgres full-text | Up to a few million rows, simple ranking, one less system | Typo tolerance, complex relevance, high query volume |
| Typesense / Meilisearch | Instant, typo-tolerant site search with little tuning | Huge datasets or heavy aggregations |
| ClickHouse | Aggregations over billions of structured events | Relevance ranking on text |
| Vector DB / pgvector | Semantic similarity on embeddings | Exact keyword matching and filters alone |
When to propose it in an interview
Any time the question says “search”: products, messages, documents, places, logs. Say how it is fed and what freshness that gives.
“Products live in Postgres. Debezium streams changes to Kafka and a consumer indexes them into an
Elasticsearch alias, so search is about a second behind and every write path is covered. Title and
brand are text with a .keyword sub-field for facets, filters for category, price and stock go in
filter so they’re cached, and I boost by sales rank. If we change the mapping, we build v2 behind
the alias and flip it. Checkout never reads Elasticsearch.”
Sizing it on the whiteboard
Say 50 million products at ~5 KB indexed each:
- Index size: 50M × 5 KB = 250 GB primary; with one replica, 500 GB on disk.
- Shards: at ~25 GB per shard, 10 primary shards, 20 shard copies in total.
- Nodes: with ~64 GB RAM nodes (half to JVM heap, half to the OS page cache for Lucene), aim to fit the hot index in page cache across nodes: 6–8 data nodes plus 3 small master nodes.
- Query rate: each query hits 10 shards. If one shard copy serves a few hundred queries per second, replicas multiply query throughput — add replicas for reads, not primaries.
The follow-ups, and the one-line answers
- “How is the data kept in sync?” CDC or an outbox, never dual writes, plus a full reindex job.
- “How fresh is search?” About a second, the refresh interval.
- “You need to change a field’s type.” New index, backfill, flip the alias.
- “
textorkeyword?”textto search words,keywordto filter, sort and aggregate — usually both. - “Page 500 of results?”
search_after, notfrom/size. - “Why not just Postgres?” For a few million rows, do. For typo tolerance, relevance tuning and heavy query load, this.