Scrivio Interview library
DebuggingIntermediate5 min read · updated 12 November 2026

In a test environment with 3 shards and 20 documents, search ranking is inconsistent between runs and differs from production. What causes this and how do you deal with it?

By default each shard scores documents with its own statistics, so IDF and average field length come from the documents on that shard only; with 20 documents spread over 3 shards those local numbers vary wildly, and so do the scores. Replicas can also differ slightly, because deleted documents still count in statistics until segments merge, so the same query can rank differently depending on which copy answers. In tests we use one shard or search_type=dfs_query_then_fetch for global statistics, in production we use preference with a session id so a user keeps hitting the same copies, and the explain API shows how each score was computed.

Why this question is asked

Inconsistent ranking in a test environment is a classic source of flaky tests and confused bug reports: the same query returns results in a different order on two runs, and neither matches production. It looks like a bug in the engine, but it is a direct consequence of how distributed scoring works. Interviewers ask this debugging question to see whether we know that relevance statistics are per shard and what that means for small indices. In this answer, we will recap how a distributed search is scored, see why 20 documents on 3 shards are a worst case, look at the replica effect, and go through the fixes for tests and for production.

1A Quick Recap of Distributed Scoring

An Elasticsearch or OpenSearch index is split into shards, and each shard is a separate Lucene index with its own copies, a primary and replicas. A search goes to one copy of every shard. Each shard finds its matching documents and scores them, the coordinating node merges the top results by score, and then fetches the documents. This default is called query_then_fetch.

The important detail is where scoring statistics come from. BM25 needs the number of documents, the number containing each term, for IDF, and the average field length. In query_then_fetch, each shard uses its own local values. On large indices that is fine, because documents are spread randomly and every shard's statistics are close to the global ones. On tiny indices they are not.

2Why 20 Documents on 3 Shards Is a Worst Case

Documents are assigned to shards by hashing their id, so a 20-document index puts roughly 6 or 7 documents on each shard, in no controlled way. Suppose the term 'kafka' appears in 4 documents.

Shard-local statistics for the term 'kafka'
ShardDocumentsContaining 'kafka'Local IDF
073ln(1 + 4.5/3.5) = 0.83
171ln(1 + 6.5/1.5) = 1.67
260no match on this shard
Whole index204ln(1 + 16.5/4.5) = 1.54
The same term is worth twice as much on shard 1 as on shard 0.

A document on shard 1 that mentions 'kafka' gets roughly twice the IDF of an equally good document on shard 0, purely because of where its id hashed. Average field lengths vary the same way. So the order of results reflects shard placement more than relevance. Production, with millions of documents, has much more even statistics, which is why the two environments disagree.

3Why Runs Differ: Replicas and Deleted Documents

That explains a wrong order, but not an order that changes between runs. The second cause is replicas. Each search picks one copy of each shard, and the copies are not always identical at the segment level. When a document is updated or deleted, Lucene marks the old version as deleted, but it still counts in statistics such as document frequency until a merge removes it. Primary and replica merge independently, so for a while one copy may count 5 documents with 'kafka' and the other 4.

Tests often update and reindex the same few documents over and over, which is exactly the pattern that leaves many deleted documents around. With 20 live documents, a handful of deleted ones change the statistics noticeably, and each run may land on different copies. Equal scores add a third source of variation: ties are broken by internal document order, which differs between shards and copies.

4Fixes for Tests

The simplest fix in a test environment is one shard: all statistics are then global by construction. The other option is dfs_query_then_fetch, which first asks every shard for its term statistics, combines them, and then scores with the global numbers.

Java
PUT /products-test
{ "settings": { "number_of_shards": 1, "number_of_replicas": 0 } }
GET /products/_search?search_type=dfs_query_then_fetch
{ "query": { "match": { "title": "kafka streams" } },
"sort": [ "_score", { "id": "asc" } ] }
// same order on every run: global IDF, and ties broken by id

The extra round trip of dfs_query_then_fetch costs latency, which is trivial in tests and usually not worth it for large production indices, whose local statistics are already close to global. The explicit tie-breaker sort on a unique field removes the last source of randomness. Tests that assert an exact order should also index their data, refresh, and avoid repeated updates, or force a merge in setup.

5Fixes for Production and How to Check

In production, the visible symptom is a user seeing results shuffle when they page or refresh, because consecutive requests hit different copies. The preference parameter routes requests with the same value to the same shard copies, so passing a session or user id keeps one user's results stable.

Java
GET /products/_search?preference=session-8f2c41
{ "query": { "match": { "title": "kafka streams" } } }
GET /products/_explain/17
{ "query": { "match": { "title": "kafka" } } }
// "value": 1.21, "description": "weight(title:kafka in 3) [PerFieldSimilarity]"
// "idf, computed as log(1 + (N - n + 0.5) / (n + 0.5))" n = 1, N = 7
// "tf, computed as freq / (freq + k1 * (1 - b + b * dl / avgdl))"
Step throughDiagnosing unstable ranking
  1. Run explain on two runscompare N, n and avgdl
  2. N smaller than the index size?per shard statistics
    YesShard-local stats: 1 shard or DFSNoLook further
  3. Counts differ between runs?copy differences
    YesReplicas or deleted docs: preferenceNoCheck ties
  4. Equal scores?
    YesAdd a tie-breaker sortNoRanking is stable

4 steps in order. Play them, or step through them one at a time.

The explain API, or explain: true in a search, shows each score's ingredients. Seeing N = 7 instead of 20 in the explanation is the proof that shard-local statistics are at work, and comparing explanations for two runs shows whether deleted documents changed the counts.

6Follow-up questions

Why not use dfs_query_then_fetch everywhere?

It adds a round trip to every shard before the real query, which raises latency, and on large indices the local statistics already match global ones closely. It is the right tool for small indices and tests.

Does force merging fix the replica differences?

Merging removes deleted documents, so it reduces the differences, and in a test setup a force merge after indexing helps. On a live index with ongoing writes, the copies will diverge again, so preference is the lasting fix for user experience.

Should production use one shard too?

Only if the index is small enough for one shard to hold and serve it. Shard count is a capacity decision; for small indices one shard is often right anyway and avoids this problem.

7Conclusion

In this answer, we saw that query_then_fetch scores with per-shard statistics, so 20 documents over 3 shards give each shard very different IDF and average lengths, and that replicas with different deleted-document counts make the ranking change between runs. In tests we use a single shard or dfs_query_then_fetch plus a tie-breaker sort, in production preference with a session id keeps users on the same copies, and the explain API shows the statistics behind every score.

What to say in the interviewAbout 80 seconds aloud

Open with

The cause is that scoring statistics are per shard by default. With query_then_fetch, each shard computes BM25 using its own document count, its own count of documents containing each term for IDF, and its own average field length.

Then, if they want more

With 20 documents over 3 shards, each shard has six or seven documents chosen by id hashing, so those numbers swing wildly: the same term can be worth twice as much on one shard as on another, and the ranking reflects shard placement more than relevance. Production, with millions of documents, has even statistics, which is why they disagree.

The run-to-run changes come from replicas: each search picks a copy of each shard, and copies can hold different numbers of deleted documents, which still count in statistics until segments merge, and tests that update the same documents repeatedly create lots of them. Ties also break differently across copies.

For tests I would use a single shard, or search_type dfs_query_then_fetch, which gathers global statistics first, plus a tie-breaker sort on a unique field. In production I would pass preference with a session id so a user consistently hits the same copies.

And to confirm, I would use the explain API: if it shows N as seven rather than twenty, shard-local statistics are the reason.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Elasticsearch documentation
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "In a test environment with 3 shards and 20 documents, search ranking is inconsistent...": https://scrivio-interview-library.netlify.app/databases/search-engines/b709e99068/