Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Concept · 20 min · revision 1

Shards, replicas and scatter-gather queries

Split a search index into primary shards and copy it into replicas, see how documents are routed and how a query fans out and merges, and estimate shard, replica and node counts from data size and query rate.

Contentsand lesson path

What you will learn

  • Scale a search cluster with shards and replicas and serve typeahead within a latency budget.

01. Why it matters

One search index on one machine stops being enough in two ways. The data can outgrow what one node should hold and recover quickly after a failure, and the query rate can outgrow what one node can answer within the latency target. Search engines handle both with two numbers that you choose per index: the number of primary shards, which splits the documents, and the number of replicas, which copies each shard.

The two numbers behave very differently. The primary count is fixed when the index is created, while the replica count can change at any time. They also cost different things: more primaries make every search ask more shards, and more replicas make every write cost more. This lesson shows both on a single OpenSearch node and ends with an estimate you can reuse. It builds on Shard keys, hot spots, index tables and materialized views, which covers scatter-gather for sharded databases.

02. Primary shards and routing

Each shard is a complete Lucene index holding part of the documents. OpenSearch picks the shard for a document by hashing a routing value, which is the document ID unless you supply one, and mapping the hash onto the primary shards. Because the mapping depends on the primary count, that count is final: changing it would move most documents, the problem described in Why hash mod N breaks. To grow, you either split the index into a multiple of its shard count (the index must first be made read-only) or reindex into a new index behind an alias, as in lesson 02.

Run shards_demo.py against the node from lesson 01. It creates an orders index with 3 primaries and 1 replica, indexes 30 documents, uses custom routing for one customer, and then shows two effects of fan-out.

Python 3.12 · shards_demo.py
"""Shards, replicas, routing and per-shard scoring on one OpenSearch node.
Python 3.12, standard library only. Run it against an empty local node."""
import json
import os
import urllib.error
import urllib.request

OS = os.environ.get('OS_URL', 'http://localhost:9200')


def call(method: str, path: str, body=None, ndjson: str | None = None):
    data = ndjson.encode() if ndjson else json.dumps(body).encode() if body else None
    req = urllib.request.Request(OS + path, data=data, method=method,
                                 headers={'Content-Type': 'application/json'})
    try:
        with urllib.request.urlopen(req) as resp:
            return resp.status, json.load(resp)
    except urllib.error.HTTPError as err:
        return err.code, json.load(err)


def bulk(index: str, docs: list[tuple[str, str | None, dict]]) -> None:
    lines = []
    for doc_id, routing, source in docs:
        meta = {'_id': doc_id} | ({'routing': routing} if routing else {})
        lines += [json.dumps({'index': meta}), json.dumps(source)]
    call('POST', f'/{index}/_bulk?refresh=true', ndjson='\n'.join(lines) + '\n')


for name in ('orders', 'notes'):
    call('DELETE', f'/{name}')

print('1. three primaries with one replica each, on a single node')
call('PUT', '/orders', {'settings': {'number_of_shards': 3, 'number_of_replicas': 1},
                        'mappings': {'properties': {'customer': {'type': 'keyword'}}}})
health = call('GET', '/_cluster/health/orders?wait_for_status=yellow&timeout=30s')[1]
print(f"  status={health['status']}"
      f" active_primary_shards={health['active_primary_shards']}"
      f" unassigned_shards={health['unassigned_shards']}")

print('2. documents spread by hash of _id')
bulk('orders', [(str(i), None, {'customer': f'c-{i % 7}'}) for i in range(1, 31)])
rows = call('GET', '/_cat/shards/orders?format=json&h=shard,prirep,state,docs')[1]
for row in sorted(rows, key=lambda r: (r['shard'], r['prirep'])):
    shard, kind, state, docs = row['shard'], row['prirep'], row['state'], row['docs']
    print(f'  shard {shard} {kind} {state:<10} docs={docs}')
_, body = call('POST', '/orders/_search', {'query': {'term': {'customer': 'c-3'}}})
print(f"  search for c-3: shards asked={body['_shards']['total']}, "
      f"hits={body['hits']['total']['value']}")

print('3. custom routing keeps one customer on one shard')
bulk('orders', [(f'r{i}', 'c-99', {'customer': 'c-99'}) for i in range(6)])
_, body = call('POST', '/orders/_search?routing=c-99',
               {'query': {'term': {'customer': 'c-99'}}})
print(f"  search with routing=c-99: shards asked={body['_shards']['total']}, "
      f"hits={body['hits']['total']['value']}")

print('4. each shard scores with its own term statistics')
call('PUT', '/notes', {'settings': {'number_of_shards': 2, 'number_of_replicas': 0}})
by_shard = {}
for n in range(20):  # find one routing value per shard
    shards = call('GET', f'/notes/_search_shards?routing=k{n}')[1]['shards']
    by_shard.setdefault(shards[0][0]['shard'], f'k{n}')
a, b = by_shard[0], by_shard[1]
bulk('notes', [('a1', a, {'text': 'red wool socks'}), ('a2', a, {'text': 'red cap'}),
               ('a3', a, {'text': 'red scarf'}), ('a4', a, {'text': 'red gloves'}),
               ('b1', b, {'text': 'red wool socks'}), ('b2', b, {'text': 'blue cap'}),
               ('b3', b, {'text': 'green scarf'}), ('b4', b, {'text': 'black gloves'})])
query = {'query': {'match': {'text': 'red'}}}
for search_type in ('query_then_fetch', 'dfs_query_then_fetch'):
    body = call('POST', f'/notes/_search?search_type={search_type}', query)[1]
    scores = {h['_id']: h['_score'] for h in body['hits']['hits']}
    print(f"  {search_type:<21} a1={scores['a1']:.4f} b1={scores['b1']:.4f}")

print('5. deep pages are refused')
status, body = call('POST', '/orders/_search?from=9995&size=10', {})
reason = body['error']['root_cause'][0]['reason']
print(f'  from=9995 size=10 -> {status}: {reason[:60]}')
Expected output (python3 shards_demo.py, OpenSearch 2.19.4, one node)
1. three primaries with one replica each, on a single node
  status=yellow active_primary_shards=3 unassigned_shards=3
2. documents spread by hash of _id
  shard 0 p STARTED    docs=6
  shard 0 r UNASSIGNED docs=None
  shard 1 p STARTED    docs=13
  shard 1 r UNASSIGNED docs=None
  shard 2 p STARTED    docs=11
  shard 2 r UNASSIGNED docs=None
  search for c-3: shards asked=3, hits=4
3. custom routing keeps one customer on one shard
  search with routing=c-99: shards asked=1, hits=6
4. each shard scores with its own term statistics
  query_then_fetch      a1=0.0927 b1=1.0595
  dfs_query_then_fetch  a1=0.4334 b1=0.4334
5. deep pages are refused
  from=9995 size=10 -> 400: Result window is too large, from + size must be less than or

Read the first three parts:

  • The health is yellow: all 3 primaries work, but the 3 replicas stay unassigned. OpenSearch does not put a replica on the node that holds its primary, because one machine failure would then lose both. A single-node lab stays yellow while replicas are set; a production cluster should be green.
  • Hashing spread 30 documents as 6, 13 and 11. Hashing evens out over many documents, not over a handful, so judge balance on real volumes.
  • A search for customer c-3 had to ask all three shards, because that customer's orders are spread by ID. With routing=c-99, all six orders of customer c-99 sit on one shard and the search asks only that shard.

Custom routing is the search version of choosing a shard key. It turns a per-tenant or per-customer search into a single-shard search, but one very large tenant then makes one shard much bigger than the rest. The index setting routing_partition_size spreads each routing value over a small group of shards instead of one, at the cost of asking that group on every search.

03. Replicas: availability and read capacity, paid for by writes

A replica is a full copy of one shard on another node. It does two jobs. If a node fails, a replica of each lost primary is promoted, so the index keeps answering. And any copy, primary or replica, can serve a search, so more copies on more nodes give more search capacity.

Copies are not free. Each one needs the same disk and a share of memory and cache. By default OpenSearch uses document replication: the primary indexes a document and forwards it, and every replica indexes it again on its own node. Two replicas therefore triple the indexing work of the cluster. OpenSearch can instead use segment replication, where replicas copy the finished index files from the primary; that saves CPU on replicas but uses more network, and replicas trail the primary by a little. Plan replicas for availability first (at least one copy beyond the primary for production data), then add copies when searches, not writes, are the bottleneck.

04. Scatter-gather: query, then fetch

The node that receives a search becomes its coordinator. In the query phase it sends the query to one copy of every shard involved. Each shard finds its own best from + size hits and returns only their IDs and scores. The coordinator merges these lists into one ranking, and in the fetch phase it asks the shards that hold the final page for those documents. Three consequences follow, and parts 4 and 5 of the output show two of them.

  • The slowest shard sets the pace. The coordinator waits for every shard, so a query over many shards is slower and less predictable than any single shard; fewer, well-sized shards help.
  • Each shard scores with its own statistics. BM25 needs document counts per term, and by default each shard uses its own. In part 4 the same text, red wool socks, scores 0.0927 on the shard where red is in every document and 1.0595 on the shard where it is rare. search_type=dfs_query_then_fetch first collects the counts from all shards, so both score 0.4334, for the price of an extra round trip. With many documents and routing by ID, per-shard statistics come close to the global ones, so this mostly matters for small indexes or uneven custom routing.
  • Deep pages are expensive. For page 1,000 of 10 results, every shard must find its best 10,000 hits, and the coordinator must sort all of them. OpenSearch refuses from + size above index.max_result_window, 10,000 by default, as part 5 shows. For deep paging use search_after with a sort key.

05. Estimating shards, replicas and nodes

A plan starts from two inputs: how much data the index will hold, and how many searches per second it must answer at peak. AWS's guidance for OpenSearch suggests shards of 10–30 GiB when search latency matters most and 30–50 GiB for write-heavy workloads such as logs. Treat that as a starting range, not a law; your own load test decides.

The script works through a jobs board with 30 million listings. Every input is an assumption written as a constant, including the per-node capacity: the number of shard searches, one query on one shard copy, that one data node can run each second at your latency target. That number only comes from a load test with real queries; the script brackets it with a worst, expected and best case.

Python 3.12 · shard_plan.py
"""Back-of-the-envelope shard and replica plan for a jobs board. Every input is an
assumption to replace with your own measurements. Python 3.12, standard library."""
import math

LISTINGS = 30_000_000  # expected in 18 months
BYTES_PER_LISTING = 4_500  # index size per listing; measure it on a sample
TARGET_SHARD_GIB = (20, 30)  # inside the 10-30 GiB guideline for search latency
PEAK_QPS = 1_200  # searches per second at the busiest hour
NODE_CAPACITY = {'worst': 1_500, 'expected': 2_500, 'best': 4_000}  # shard searches/s

data_gib = LISTINGS * BYTES_PER_LISTING / 2**30
low, high = (math.ceil(data_gib / size) for size in reversed(TARGET_SHARD_GIB))
primaries = math.ceil((low + high) / 2)
shard_gib = data_gib / primaries
print(f'primary data {data_gib:.1f} GiB -> {low} to {high} primaries, '
      f'choose {primaries} ({shard_gib:.1f} GiB each)')

shard_searches = PEAK_QPS * primaries  # each search asks one copy of every shard
print(f'{PEAK_QPS} searches/s x {primaries} shards = {shard_searches} shard searches/s')
print('case      nodes  +spare  replicas  copies/node  GiB/node')
for case, capacity in NODE_CAPACITY.items():
    nodes = math.ceil(shard_searches / capacity) + 1  # survive losing one node
    replicas = max(1, math.ceil(nodes / primaries) - 1)  # every node gets a copy
    copies = primaries * (1 + replicas)
    print(f'{case:<9} {nodes - 1:>5} {nodes:>7} {replicas:>9} '
          f'{copies / nodes:>12.1f} {copies * shard_gib / nodes:>9.1f}')
Expected output (python3 shard_plan.py)
primary data 125.7 GiB -> 5 to 7 primaries, choose 6 (21.0 GiB each)
1200 searches/s x 6 shards = 7200 shard searches/s
case      nodes  +spare  replicas  copies/node  GiB/node
worst         5       6         1          2.0      41.9
expected      3       4         1          3.0      62.9
best          2       3         1          4.0      83.8

The steps are the reusable part:

  1. Primaries come from data size: 125.7 GiB of index at 20–30 GiB per shard gives 5 to 7 primaries, and 6 is chosen.
  2. Every search asks one copy of every shard, so 1,200 searches per second become 7,200 shard searches per second. More primaries make each search more expensive.
  3. Nodes come from the measured capacity, plus one spare so the cluster still meets its target with a node down: 6, 4 or 3 nodes across the three cases.
  4. Replicas make sure each shard has at least two copies and every node holds some: one replica gives 12 copies, 2 to 4 per node.
  5. Check memory and disk last: 42–84 GiB of index per node, plus room for merges, growth and a rebuild of the index.

If the expected case is right, 4 nodes with 6 primaries and 1 replica fit. If the load test lands on the worst case, you add nodes and keep the same index, because replicas and nodes can change later. Only the primary count is hard to change, which is why it is sized for the data you expect in 18 months, not today.

06. Check your understanding

Practice check · 3 questions

Shards, replicas and fan-out

Three questions on replica cost, per-shard scores and shard searches.

Q1. A logging cluster uses document replication, and indexing CPU is its bottleneck. To add capacity, an engineer raises `number_of_replicas` from 1 to 2 on the same nodes. What happens to ingest?
Q2. A new 4-shard index holds 400 products, routed by seller. Two sellers list the same item with identical text, yet one copy scores far higher than the other for the same query. What explains it?
Q3. An index has 12 primary shards and peaks at 900 searches per second. A load test shows one data node runs about 3,000 shard searches per second within the latency target. How many nodes does search need, before adding a spare?
Practice only: not graded, not saved, not evidence.

07. Apply it

Add the cluster section to this skill's practice design, product search at 5,000 searches per second:

  1. Estimate the index size per product by indexing a sample of 10,000 products and reading the store size, then project 18 months ahead.
  2. Choose primaries with shard_plan.py, and say whether any routing value (such as seller) would help or hurt.
  3. Write down the per-node capacity you assume, and how a load test would confirm it.
  4. Choose replicas and nodes with one spare, and check memory and disk per node.
  5. Note what you would change first if the load test lands on the worst case.

08. Review prompt

Without looking back, explain: how a document finds its shard and why the primary count is fixed; what a replica gives and what it costs with document replication; the query and fetch phases; why scores can differ between shards; why deep pages are refused; and the five steps of a shard and node estimate.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check