Sub topic 10
Scaling with shards and replicas
This chapter assumes you know what an inverted index is, how a mapping is defined, and the basics of horizontal scaling and replication from general distributed systems. It covers how a search service spreads one logical index across many machines, and the decisions that are hard to change later.
Why one node stops being enough
A single search node eventually hits one of three limits:
- Storage. The index no longer fits on the node's disk, or no longer fits in the operating system's file cache. Search is fast mostly because hot index segments sit in memory, so a cache that is too small makes queries slow.
- Query throughput. The node's CPUs are saturated by concurrent queries.
- Availability. The node is a single point of failure. If it dies, search is down.
Two mechanisms address these limits, and they solve different problems:
| Mechanism | What it does | Problem it solves |
|---|---|---|
| Sharding | Splits the index into disjoint pieces stored on different nodes | Data size, indexing throughput |
| Replication | Keeps extra copies of each piece on other nodes | Query throughput, availability |
Keeping this distinction clear avoids a common mistake: adding replicas does not help when the data is too large for one node's cache, and adding shards does not make the cluster survive a node loss.
Sharding: splitting the index
A shard is a self-contained slice of the index. Each shard is a complete inverted index over a subset of the documents. In Elasticsearch and OpenSearch a shard is a Lucene index. Solr and other engines use the same idea under different names.
The engine decides which shard owns a document by hashing a routing value, which defaults to the document ID:
shard = hash(routing_value) % number_of_primary_shardsThe modulo is the reason the number of primary shards is fixed when the index is created. If you changed it, existing documents would hash to different shards and the engine could no longer find them. Changing the shard count means creating a new index and reindexing into it, which the reindexing chapter covers.
The following sketch shows the routing and the query side together. It uses no search engine, only the idea:
import heapq
import zlib
NUM_SHARDS = 3
def shard_for(doc_id, num_shards=NUM_SHARDS):
# A stable hash. Python's built-in hash() is randomized per process for strings.
return zlib.crc32(str(doc_id).encode()) % num_shards
# Each shard holds doc_id -> relevance score for one fixed query.
shards = [dict() for _ in range(NUM_SHARDS)]
scores = {1: 0.9, 2: 2.4, 3: 1.1, 4: 0.3, 5: 3.0, 6: 1.8}
for doc_id, score in scores.items():
shards[shard_for(doc_id)][doc_id] = score
def search_shard(shard, k):
# Each shard returns only its own top k.
return heapq.nlargest(k, shard.items(), key=lambda item: item[1])
def search(k):
partial = []
for shard in shards: # in a real system these calls run in parallel
partial.extend(search_shard(shard, k))
return heapq.nlargest(k, partial, key=lambda item: item[1])
print(search(3)) # [(5, 3.0), (2, 2.4), (6, 1.8)]The search function shows the query pattern used by every sharded engine, often called scatter-gather.
How a query runs across shards
A client sends a query to any node. That node acts as the coordinating node for the request. It does the following:
- It sends the query to one copy (primary or replica) of every shard.
- Each shard runs the query locally and returns its top
from + sizehits, with only IDs and scores. - The coordinator merges those lists into one global ranking.
- It fetches the stored fields for the winning documents from the shards that hold them and returns the result.
Several consequences follow from this design:
- Latency is set by the slowest shard. A query finishes when the last shard answers. One slow node, a long garbage collection pause, or a hot shard raises tail latency for every query that touches it.
- Every query touches every shard, unless you use routing. Doubling the shard count does not halve query cost. It adds more per-shard work and more merge work.
- Deep pagination is expensive. To return page 1000 of 10 results, each shard must return its top 10,000 hits, and the coordinator merges all of them. Most engines cap this with a limit such as
index.max_result_window(10,000 by default in Elasticsearch). Use a cursor-style method such assearch_afterfor deep traversal. - Scores are computed per shard. BM25 uses document frequency and average document length, and by default each shard computes these from its own data. On small or unevenly distributed indexes, the same term can get a different idf on different shards, which makes cross-shard ranking slightly inconsistent. Engines offer a mode that gathers global term statistics first, at the cost of an extra round trip. On large, evenly hashed indexes the difference is usually negligible.
Replication: copies for reads and survival
Each shard has one primary and zero or more replicas. Writes go to the primary first. The primary applies the operation, forwards it to its replicas, and acknowledges the client after the in-sync replicas confirm. Reads can be served by the primary or any replica, so each replica adds read capacity.
Replicas also provide failover. If the node holding a primary fails, the cluster promotes one of its replicas to primary. The cluster then builds a new replica elsewhere to restore the target copy count.
The engine never places a replica on the same node as its primary, because that would protect nothing. A cluster with number_of_replicas: 1 needs at least two data nodes to be fully allocated.
The settings are given when the index is created:
PUT /products
{
"settings": {
"number_of_shards": 6,
"number_of_replicas": 1
}
}The two settings differ in how you can change them:
| Setting | Change after creation? | Notes |
|---|---|---|
| `number_of_shards` | No (needs a new index, or split/shrink APIs with constraints) | Fixed by the hash modulo |
| `number_of_replicas` | Yes, at any time, with a settings update | Adds or removes copies without downtime |
Because replicas are adjustable, you can scale read capacity up for a busy season and back down afterward.
Choosing the number of shards
You choose the shard count before you know your final data size, so you are estimating. Practical guidance:
- Target a shard size in the range of roughly 10 to 50 GB. Smaller shards waste overhead, since each shard has fixed memory and file-handle costs. Larger shards recover slowly after a failure and are slow to rebalance.
- Estimate growth. Take the expected data size in 12 to 18 months, divide by the target shard size, and round up to a figure that suits your node count.
- Match the node count. Shards distribute most evenly when the count is a multiple of the number of data nodes. Six shards over three nodes balances; five does not.
- Avoid oversharding. Hundreds of tiny shards per node is a common failure. Each shard consumes heap for metadata and adds per-query overhead, and cluster state grows, which slows master operations.
- Avoid undersharding. One huge shard cannot be spread over more nodes, so you hit a ceiling that only a reindex fixes.
For time-based data such as logs, a different pattern fits better: one index per day or month, with rollover rules. Product catalogs that update in place usually use a single index, or a small number of indexes, with a fixed shard count.
Routing to reduce fan-out
If most queries concern one tenant or one user, you can supply a custom routing value so that all of that tenant's documents land in the same shard. A query with the same routing value then touches only one shard instead of all of them.
Trade-offs:
- Hot shards. A very large tenant fills one shard while others stay small. Skew breaks the even-size assumption behind your capacity plan.
- Correctness depends on the client. If a document is indexed with routing and later fetched or updated without it, the engine looks in the wrong shard and reports the document missing.
- Cross-tenant queries still need all shards.
Use routing only when query patterns clearly isolate to a key, and monitor shard sizes.
Capacity planning with replicas
Replicas multiply storage and indexing work. With number_of_replicas: 1, you store twice the data and every write is applied twice. For read-heavy search workloads that trade-off is usually acceptable.
A useful planning rule: size the cluster so that it can lose one node and still hold all shards with enough memory and CPU for peak load. If a node's loss pushes the remaining nodes past their disk watermarks, the engine may stop allocating shards or make indexes read-only. That turns one failure into a wider outage.
Common failure modes at this stage:
- Yellow or red cluster status. Yellow means all primaries are assigned but some replicas are not. Red means at least one primary is unassigned, and searches over that shard fail or return partial results.
- Partial results. By default, many engines return results from the available shards and flag the response as partial. Decide whether your application should accept that or treat it as an error.
- Rebalancing storms. Adding or removing nodes triggers shard movement, which consumes network and disk. Throttle recovery during peak hours.
- Split brain protection. Run an odd number of master-eligible nodes, normally three, so that a network partition cannot produce two competing clusters.
Exercise
A product search index has 3 primary shards, 1 replica per shard, and runs on 3 data nodes. Search traffic doubles and queries become CPU-bound, but the data size is stable. Which change is the best first step, and why would adding primary shards be the wrong first step?
Show answer
Raise numberofreplicas from 1 to 2 and, if needed, add data nodes so each node holds a copy of each shard. This is a settings update with no downtime, and it adds read capacity because more copies can serve each shard's part of a query. Adding primary shards requires creating a new index and reindexing, since the hash modulo fixes the shard count. It would also increase per-query fan-out and merge work without addressing the real limit, which is query capacity rather than data size.