Shard Sizing Strategy at Scale in Elasticsearch
Learn how to choose the size and number of shards so that a cluster with thousands of shards and hundreds of nodes stays fast, stable and affordable, and how to fix it when the numbers were chosen badly.
Picture a huge library that must store ten million books. You could keep everything in one gigantic room, but then every visitor would wander the same crowded floor and finding anything would take forever. You could also split the collection into ten million tiny closets, one book each, but then the librarians would spend their days managing closets and keys instead of helping readers. The smart choice lies between the two extremes: rooms that are big enough to be efficient and small enough to be quick to move, clean and search. In Elasticsearch, a shard is that room, and deciding how big to make it, and how many to build, is one of the most important design decisions you will ever make.
1Why Shard Sizing Deserves Its Own Strategy
Most Elasticsearch performance problems that appear at scale trace back to a shard decision made months earlier.
The quiet decision that shapes everything
When you create an index, Elasticsearch asks how many primary shards it should have. Many beginners accept the default and move on, because everything works perfectly with a small amount of data. The trouble is that this choice stays hidden for a long time. The cluster runs happily for months, then data grows, more teams arrive, and suddenly the master node is slow, restarts take hours and dashboards stutter.
The reason the problem appears late is that a shard count is baked into an index when it is created. You cannot simply edit it afterwards. Changing it later means shrinking, splitting or reindexing, and each of these takes planning, spare capacity and time. A little thought on day one saves a very stressful month later.
What “at scale” really means
At a small scale, almost any shard layout works. Scale begins when the number of shards, indices or nodes is large enough that the fixed cost of each shard becomes visible. That can mean tens of terabytes of data, thousands of shards, or dozens of teams sharing one cluster. At that point, small mistakes are multiplied by thousands, and a wasteful pattern that cost nothing in a test environment becomes the single biggest drain on the system.
Designing a city street grid is easy for a village of fifty houses. For a city of ten million people, the width of the roads and the size of each block decide whether traffic flows or freezes. Shard sizing is the city planning of your cluster.
There is no magic number that fits every cluster. What exists is a well-tested range, a set of trade-offs, and a method to measure your own workload. This tutorial teaches all three.
2The Building Blocks, Explained Simply
Every term below is used again and again, so it is worth defining each one carefully.
Index
A named collection of documents that share a purpose, such as all orders or all web logs of one service.
Primary Shard
One slice of an index that holds a portion of the documents. Every document lives in exactly one primary shard.
Replica Shard
A full copy of a primary shard on a different node, used for safety and to share the reading load.
Lucene Index
Each shard is really a complete search engine library index called a Lucene index. Elasticsearch is a distributed layer above many of them.
Segment
An immutable file set inside a shard. New documents create small segments, and background merging combines them into bigger ones.
Heap
The memory reserved for the Elasticsearch process itself. Shard bookkeeping consumes part of it.
Cluster State
The master node’s map of every index, shard, mapping and node. It is shared with every node, so its size matters.
Data Stream
A single name for time-based data that automatically creates a new hidden backing index whenever the old one rolls over.
The relationship between them
An index is divided into primary shards. Each primary shard can have zero or more replica shards. All these shards are spread across the data nodes of the cluster. A search request has to visit one copy of every relevant shard, and an indexing request has to reach the primary shard that owns the document and then its replicas. So the number and size of shards directly decide how much work each request creates and where that work happens.
An index is an encyclopedia set. Each primary shard is one volume. A replica is a photocopy of a volume stored in a different building. A node is a building. To answer a question about the whole encyclopedia, someone must open one copy of every volume that might be relevant.
Why each shard is a full search engine
This point is the root of the whole topic. Because a shard is a complete Lucene index, it has its own segment files, its own memory structures, its own caches and its own transaction log. Creating a shard is therefore never free. Even an empty shard has a small cost, and the cost does not shrink when the shard holds only a few documents. That is why many tiny shards are so wasteful, and it is the seed of the guidance you will read in the next chapters.
3What a Single Shard Really Costs
To pick a good size, first learn what you are paying for every time you create a shard.
Heap memory
Each open shard keeps metadata about its segments and fields in memory. More segments and more fields mean more heap used.
File handles
Every segment is made of several files, and the operating system limits how many files a process may hold open at once.
Cluster state space
Each shard adds an entry to the cluster state that the master must build, publish and every node must store.
Search threads
A search thread handles one shard at a time, so more shards means more tasks queued for the same limited threads.
Background work
Each shard schedules its own refreshes, merges and flushes, which add up across thousands of shards.
Recovery and snapshot effort
Every shard must be recovered after a restart and included in every snapshot, adding management overhead.
The heap link
Elasticsearch documentation has long offered a rule of thumb that a node should hold no more than about twenty shards per gigabyte of heap. On a node with thirty gigabytes of heap, that suggests around six hundred shards as an upper comfort level. Newer versions reduced the memory footprint of a shard, and the true limit depends on how many fields and segments each shard has, so treat the figure as a sanity check rather than a law. Still, the direction is clear: the more shards a node holds, the less room remains for searching, aggregating and caching.
Remember also that Elasticsearch recommends keeping the heap at no more than half of the machine’s memory and below the size where the Java virtual machine loses a memory-saving trick, which is roughly thirty gigabytes. The rest of the memory is left for the operating system to cache files. So you cannot fix a shard explosion by simply buying a bigger heap.
The thread link
Searches run on a thread pool whose size is based on the number of processor cores. Each thread works on one shard at a time. If a single search touches four hundred shards on a node with eight cores, most of those shard tasks wait in a queue. Fewer, larger shards let the same threads finish the job with less waiting, up to the point where a single shard becomes too large to search quickly.
A bank with eight tellers can serve a customer with one big form very efficiently. If a customer arrives with four hundred tiny forms, each needing its own stamp and its own queue position, the tellers spend their day on paperwork overhead instead of on the actual banking.
Some people think that empty or nearly empty indices are harmless because they hold no data. They are not harmless. An empty shard still takes heap, cluster state space and management time, and the cost is roughly the same as for a modest shard.
4The Small Shard Trap: Oversharding
Oversharding means having far more shards than your data and hardware can efficiently support.
How it usually happens
Oversharding rarely comes from one bad decision. It builds up from many reasonable ones. A team creates one index per day. Another creates one index per customer. A third uses the older default of five primary shards for every index. Each choice looks harmless alone, but they multiply. Consider two hundred services, each writing a daily index with five primary shards and one replica, kept for thirty days. That is two hundred times five times thirty, which equals thirty thousand primary shards, or sixty thousand with replicas.
Now suppose the whole cluster holds nine thousand gigabytes of primary data. Divided across thirty thousand shards, the average shard holds only about three tenths of a gigabyte. The cluster is carrying sixty thousand units of overhead to store data that would fit comfortably in a couple of hundred well-sized shards.
flowchart LR
A["200 services"] --> B["Daily index each"]
B --> C["5 primary shards each"]
C --> D["30 day retention"]
D --> E["30000 primary shards"]
E --> F["About 0.3 GB per shard"]
F --> G["Heap pressure and slow master"]
The symptoms
Slow master and cluster state updates
Every index creation, mapping change or shard move must update the state. With huge state, these tasks pile up as pending tasks.
High heap usage with little data
Nodes show heavy memory pressure and frequent garbage collection even though the disks are mostly empty.
Slow searches across many indices
A query over a wide date range fans out to thousands of shards, and the coordinating node struggles to merge so many partial answers.
Painful restarts and upgrades
After a rolling restart, thousands of shards must be recovered one after another, stretching maintenance windows from minutes to hours.
Hitting shard limits
Elasticsearch enforces a per-node shard limit, by default one thousand for normal data nodes, and refuses new indices when it is reached.
Raising the maximum shards per node setting to make an error message go away. The limit is a safety fence, not a nuisance. Raising it hides the cause, and the cluster will then fail in a less friendly way, usually through memory trouble.
5The Giant Shard Trap: Undersharding
The opposite mistake is just as real, though it is quieter and less discussed.
What goes wrong with huge shards
Because a shard is the smallest unit Elasticsearch can move, copy or recover, a very large shard turns every routine event into a long operation. Moving a two hundred gigabyte shard to another node takes far longer than moving a forty gigabyte one, and during that time the network and disks of both nodes are busy. If the node holding the only copy fails, the time to rebuild the replica is proportional to the shard size.
A simple calculation shows the effect. A fifty gigabyte shard copied at one hundred megabytes per second takes about eight and a half minutes. A two hundred gigabyte shard at the same speed takes about thirty-four minutes. Multiply by dozens of shards after a node loss and you see why very large shards prolong periods of reduced safety.
Other problems with giant shards
A large shard cannot be searched by more than one thread at a time in the usual case, so one heavy query on one enormous shard cannot be sped up by adding more cores. Merges of large segments require large amounts of temporary disk space and produce long bursts of input and output activity. Uneven data placement also becomes likely, because a cluster of nodes holding a few huge shards each cannot balance itself smoothly. One node may hold three giants while another holds one.
There is also a hard technical ceiling. A single Lucene index cannot hold more than about two billion documents. Long before you reach that limit you will have suffered from slow merges and slow recovery, but it shows that unlimited growth of a single shard is impossible in any case.
Moving house with a few enormous crates is difficult. Each crate needs a special truck, two strong people and half a day. If a crate is dropped, you lose a huge portion of your belongings at once. Medium-size boxes are easier to lift, easier to pack into any vehicle, and cost you less when one is damaged.
Advantages of Fewer, Larger Shards
- Less heap and cluster state overhead per gigabyte
- Fewer tasks per search, so less queueing
- Simpler management and fewer objects to monitor
- Better compression and fewer segments to search
Disadvantages / Trade-offs
- Slow relocation and recovery after failures
- Lower search parallelism inside one index
- Heavy merges and large temporary disk needs
- Uneven balance and hot nodes
- Harder to correct later without reindexing
6Finding the Sweet Spot: Size Guidelines
Between too small and too large lies a comfortable range that works for most clusters.
The widely used range
Elastic’s own guidance suggests aiming for shards between about ten and fifty gigabytes for many search and logging workloads. Shards near the top of this range are typical for time-based data such as logs, where most reads cover recent windows and merging efficiency matters. Shards nearer the lower end are common for search-heavy workloads where each query is latency sensitive and users expect very quick answers. It is also wise to keep the number of documents per shard below a couple of hundred million, because document count affects search cost independently of gigabytes.
| Workload | Typical Shard Size | Main Reason |
|---|---|---|
| Logs and metrics on the hot tier | Around 30 to 50 GB | Efficient merging, fewer shards, mostly recent reads |
| Logs after shrink on warm tier | Up to about 50 GB or a little more | Read-only data compresses well and needs fewer shards |
| User-facing search such as a product catalog | Around 10 to 30 GB | Keeps each query fast and predictable |
| Small indices under a few gigabytes | One primary shard | Splitting tiny data only adds overhead |
| Frozen or snapshot-backed data | Often larger, sized for efficient object storage reads | Few shards mean fewer repository requests and cheaper caching |
Why a range and not one number
The best size depends on several things at once: how fast the disks are, how much memory the node has, how complex the queries are, how much recovery time you can tolerate, and how the data is queried. A cluster on fast local drives with quick recovery can safely run bigger shards than a cluster on slow network disks. A workload of simple filtered searches tolerates bigger shards than one running heavy aggregations. So the published range is a starting point, and your own measurements are the final judge.
flowchart TD
S["Start: estimate data per index or per day"] --> T{"Is the data time-based?"}
T -->|Yes| U["Use data streams and roll over by primary shard size"]
T -->|No| V["Estimate total size and growth for one to two years"]
U --> W["Target 30 to 50 GB per shard"]
V --> X["Target 10 to 30 GB per shard"]
W --> Y["Benchmark with real data and real queries"]
X --> Y
Y --> Z["Adjust and document the decision"]
Write down the reasoning behind your chosen size, including disk speed, recovery target and query type. Six months later, a new engineer will thank you, and you can quickly see which assumption changed when something starts to hurt.
7Primary Shard Count and Write Throughput
Sometimes the number of shards is chosen not for size but to spread the write load.
How writes use shards
Every document written to an index is routed to exactly one primary shard, decided by hashing the document’s routing value, which by default is its identifier. The primary shard processes the write and forwards it to the replicas. Because different primaries live on different nodes, a large number of primaries lets many nodes index in parallel. A single primary shard, in contrast, handles all writes for its index through one node’s resources.
For a busy write index, such as the current index of a big log stream, a single shard can become a bottleneck long before it becomes big. A common approach is to set the number of primaries for the write index close to the number of hot data nodes, or a small multiple of it, so the indexing work is spread evenly. When that index later rolls over, the old one can be shrunk to fewer shards for cheap long-term storage.
Balancing the two goals
You now have two forces. Size guidance pushes towards fewer shards, while write throughput pushes towards more. The trick is to treat them as belonging to different stages of the index’s life. During the hot stage, use enough primaries to spread writes. During the warm stage, shrink to the number that suits the final data size. The shrink step makes it possible to have both.
Measure the ingest rate
Find how much data per hour arrives and how much one node can index comfortably during peaks, with headroom.
Choose primaries for the write index
Pick a count that lets every hot node share the load, avoiding many more primaries than nodes.
Roll over by size
Set a rollover condition on primary shard size so each finished index has shards of the intended size.
Shrink later if needed
When the index moves to a lower tier, reduce the primaries to match the final size target.
A supermarket opens many checkout lanes during the evening rush so customers are served in parallel, and closes most of them at night. The lanes are the primaries: plenty during heavy traffic, few when things are quiet.
Setting a very high primary count “for future growth”. The extra shards cost you today and rarely help tomorrow, because for time-based data, tomorrow’s index is a new index that can use a better number.
8Replica Strategy at Scale
Replicas multiply your shard count, so they belong in every sizing calculation.
What replicas give you
A replica gives you two benefits. First, resilience: if a node fails, a copy of its shards exists elsewhere, and the cluster can promote it to primary. Second, read capacity: searches can be served by either the primary or any replica, so more copies means more places to run queries. A cluster serving a lot of search traffic can raise the replica count to spread reads across more machines.
What replicas cost
Every replica stores a full copy of the data, so one replica doubles the disk needed. Each replica also repeats the indexing work in normal Elasticsearch, so heavy write loads pay a price in processor time and network traffic. And each replica is another shard in the cluster state, adding to all the overhead described earlier. At scale, the cost of an unnecessary replica is multiplied by thousands of shards.
| Replica Count | Storage Cost | Resilience | Read Capacity |
|---|---|---|---|
| 0 | Lowest | None, data loss possible if a node fails unless a snapshot exists | One copy only |
| 1 | Double | Survives one node loss | Two copies to share reads |
| 2 | Triple | Survives two node losses | Three copies to share reads |
Choosing replicas by data value
Fresh data on the hot tier normally deserves at least one replica, since it is precious and heavily read. Older data on cheaper tiers may keep fewer, particularly when searchable snapshots provide an independent durable copy. Data that can be re-created easily from another source, such as a rebuildable analytics index, may run with no replicas at all, accepting a rebuild if something fails. The point is to decide deliberately rather than leave the default in place everywhere.
High-value fresh data
One or more replicas, spread across availability zones, to protect against node and zone failures.
Read-heavy search application
Extra replicas can be added or removed dynamically to handle traffic peaks, since replica count can change without recreating the index.
Rebuildable data
Zero replicas with a tested rebuild procedure, saving half of the storage and a large part of the shard overhead.
Unlike the primary count, the replica count can be changed at any time on a live index. This makes replicas a flexible tool for quick adjustments, while primaries need the careful planning covered in this tutorial.
9Sizing Time-Based Data with Rollover
For logs, metrics and events, the best sizing tool is not a fixed number of shards, but a rule about when to start a new index.
The problem with one index per day
Creating an index every day looks tidy, but data volume is not tidy. A quiet weekend day may fill only a few gigabytes, giving you a tiny wasteful shard. A traffic peak may fill several hundred gigabytes, giving you a giant one. With hundreds of sources, the mixture of sizes is chaotic, and you cannot choose one primary count that suits them all.
Rollover by primary shard size
Rollover solves this by watching the index instead of the calendar. A lifecycle policy can roll the write index over when the largest primary shard reaches a chosen size, such as fifty gigabytes, or when the index reaches a maximum age, or when a document count limit is reached. Whichever happens first triggers a new index. The result is that every finished index has shards close to the target size, whether the day was quiet or busy.
Newer versions also allow minimum conditions, so that an index does not roll over merely because it is old if it is still nearly empty. That protects you from creating a stream of tiny indices during quiet periods. If your version does not support this, choose a maximum age long enough that a slow source still produces a reasonable shard.
sequenceDiagram
participant App as Log source
participant DS as Data stream
participant W as Write index
participant ILM as Lifecycle policy
App->>DS: Send documents
DS->>W: Store in current write index
ILM->>W: Check primary shard size and age
W-->>ILM: Largest shard reaches target size
ILM->>DS: Roll over to a new write index
DS->>W: Old index becomes read-only for writes
A worked example
Imagine a platform that produces three hundred gigabytes of indexed primary data each day and keeps thirty days online. That is nine thousand gigabytes. With a target of fifty gigabytes per shard, you need about one hundred and eighty primary shards in total, or three hundred and sixty with one replica. Compare this with the thirty thousand primaries in the oversharded example of Chapter 4. The difference in overhead is nearly two orders of magnitude, while the searchable data is identical.
Instead of changing the notebook every morning whether it is full or not, you change it when the pages run out. Every notebook then holds a similar amount, and none is wasted.
Combine small data sources into shared data streams where their access rules and retention are the same. Two hundred small streams create two hundred rolling indices, while a handful of shared ones create far fewer.
10Sizing Data That Is Not Time-Based
Product catalogs, customer profiles and document libraries do not roll over, so they need a different way of thinking.
Estimate total size and growth
With data that lives for years and is updated in place, you cannot rely on rollover. Instead, estimate the size the index will reach within a planning horizon, perhaps one to two years, and pick a primary count so that shards stay in your target range at that size. A catalog that holds twenty gigabytes now and is expected to reach sixty gigabytes might do well with two or three primaries. One that will stay under five gigabytes forever is best with a single shard.
Do not oversize for the far future
It is tempting to plan for ten times growth by creating twenty primaries on day one. That would give twenty tiny shards today, each carrying full overhead and each slowing every query, all for a future that may never arrive. Elasticsearch offers a safer route: the split operation can multiply the primary count of an index later, when it is truly needed, as long as the original index was created with enough routing space. Planning for that flexibility is far cheaper than paying for unused shards every day.
Small stable data
Use one primary shard with one replica. This is the simplest and fastest layout for data under a few gigabytes.
Steadily growing data
Choose a modest primary count for the expected size in about a year, and review it regularly. Plan a split or a reindex for the next stage.
Data with large tenants and small tenants
Do not give every tenant the same shard layout. Handle the very large ones separately, as described in Chapter 15.
When you buy shoes for a growing child, you choose a size a little bigger, not four sizes bigger. Shoes that are far too large make walking harder today, and children grow at a pace you can plan for and adjust.
Believing that more primaries always mean faster searches. For a small index, extra shards only add coordination work, so queries often become slower rather than faster.
11Internal Working: How Requests Touch Shards
Seeing the journey of a request explains why shard count and size affect latency so strongly.
The journey of a search
A search arrives at any node, which becomes the coordinating node for that request. It determines which indices match, and from them which shards could hold results. It sends the query to one copy of each shard. Each shard runs the query on its own segments, keeps the best results, and returns them to the coordinator. The coordinator then merges all these partial lists into one final list and, in a second step, fetches the actual documents for the winning results.
sequenceDiagram
participant U as User
participant C as Coordinating node
participant S1 as Shard A
participant S2 as Shard B
participant S3 as Shard C
U->>C: Search request
C->>S1: Query phase
C->>S2: Query phase
C->>S3: Query phase
S1-->>C: Top results
S2-->>C: Top results
S3-->>C: Top results
C->>C: Merge and rank
C->>S1: Fetch phase for winners
C-->>U: Final response
Why many shards slow the merge
The coordinating node must hold and merge results from every shard. With three shards, that is a tiny task. With three thousand, the memory needed to hold the partial results grows, and the coordinator may need to reduce results in batches. The response time is also set by the slowest shard, so the more shards there are, the higher the chance that at least one is slow at that moment, a pattern often called tail latency.
Skipping shards that cannot match
Elasticsearch includes a lightweight pre-check step. Before running the real query on many shards, it asks each shard whether the query could possibly match, using information such as the range of timestamps stored in the shard. Shards that cannot match are skipped. This step is very helpful for time-based data, which is one more reason to always include a time filter in queries on data streams.
The journey of a write
A write request also lands on a coordinating node. The node hashes the routing value to find the correct primary shard, forwards the document there, and the primary writes it into memory buffers and the transaction log, then sends it to the replicas. The write is confirmed once the required copies have accepted it. Regular refresh operations make the new data visible to searches, by default about once per second on active indices. Each shard has its own refresh and its own merge activity, so thousands of shards means thousands of small background jobs.
A search is like a teacher collecting homework from a class. With thirty pupils, it is quick. With three thousand pupils, even a very fast teacher spends the whole day just gathering and sorting the papers, and one late pupil delays everything.
Encourage every team to add a time range filter and, where possible, target specific data streams instead of a wildcard across every index. Fewer shards touched means faster and cheaper queries.
12Shards per Node and Cluster Limits
A cluster has both soft rules of thumb and hard guardrails that limit how many shards it can carry.
The guardrail settings
By default, Elasticsearch limits each normal data node to about one thousand open shards, and each frozen data node to about three thousand, because frozen shards are lighter. If creating an index would exceed the total allowed by the cluster, the request is refused. These limits exist to protect the cluster from a slow slide into instability, so they should be treated as a warning bell, not as an obstacle to remove.
The master node view
The master node has its own scaling concern, since it must maintain and publish the cluster state. Elastic’s guidance suggests keeping the number of indices roughly proportional to the master heap, on the order of a few thousand indices per gigabyte of master heap. A dedicated master with a small heap can be overwhelmed by a large state, and its trouble is felt by every node because every change waits for the master.
| Limit or Guideline | What It Protects | Typical Value |
|---|---|---|
| Shards per data node | Heap and stability of each node | Default limit of about 1000 for normal nodes |
| Shards per frozen node | Cache-based nodes with light shards | Default limit of about 3000 |
| Shards per gigabyte of heap | Memory available for real work | Rule of thumb of about 20 or fewer |
| Documents per shard | Search cost and Lucene limits | Keep well under a few hundred million |
| Indices per gigabyte of master heap | Master responsiveness | A few thousand at most |
Making the count work for you
Take the nodes you plan to run, multiply by a safe shards-per-node figure based on your heap, and compare the result with the shards your design creates. If the design needs more, you have three choices: enlarge the shards, reduce the number of indices, or add nodes. Adding nodes is the most expensive fix and often not the right one, since it treats the symptom rather than the cause.
The last figure above is a theoretical ceiling, not a target. A node also needs free disk for merges, recovery and watermark safety, and its real search workload may need far fewer shards to stay quick.
13Allocation, Balance and Hot Spots
Even perfectly sized shards cause trouble if they are placed unevenly across the nodes.
How the cluster places shards
The master runs an allocation process that decides which node receives each shard. It follows rules, such as never placing a primary and its replica on the same node, respecting tier roles, and obeying disk watermarks. Within those rules, it tries to balance the cluster by spreading shards and, in newer versions, by considering factors such as disk usage and write load, not only shard counts.
What a hot spot looks like
A hot spot happens when one node does much more work than its neighbours. The classic cause is that several busy write shards land on the same node, because the balancer only saw them as equal shards. That node then shows high processor use, a long indexing queue and slow responses, while other nodes sit idle. Users see the slowness as random spikes, which makes the cause hard to find.
flowchart LR
subgraph Uneven
N1["Node 1: 3 active write shards"]
N2["Node 2: 1 active write shard"]
N3["Node 3: 0 active write shards"]
end
subgraph Balanced
M1["Node 1: 1 active write shard"]
M2["Node 2: 1 active write shard"]
M3["Node 3: 1 active write shard"]
end
Uneven --> Balanced
Tools to keep placement healthy
Match primaries to nodes
Using a primary count that divides evenly across the hot nodes makes a balanced layout natural.
Per-node shard cap for an index
A setting can limit how many shards of one index sit on a single node, forcing spread. Use with care, since a cap that is too tight can block allocation.
Even shard sizes
Rollover by size keeps shards similar, so counts on each node reflect real load.
Allocation explain
A diagnostic feature that tells you exactly why a shard sits where it does or why it cannot be placed.
If all the heaviest boxes in a moving truck are put on one side, the truck leans and drives badly even though the total weight is fine. Balance matters as much as the total.
Whenever you add or remove nodes, watch how shards rebalance. A cluster with well-sized shards rebalances smoothly, while one with giant shards can spend hours moving a few heavy items around.
14Fixing Mistakes: Shrink, Split, Merge and Reindex
If your shards are already the wrong size, you have several repair tools, each with its own rules.
Shrink: fewer, larger shards
The shrink operation creates a new index with fewer primary shards from an existing one. The target count must be a factor of the source count, so an index with eight primaries can become four, two or one. The source index must be read-only, and all its shards must first be gathered on a single node, which is why enough free disk on that node matters. Shrink is efficient, because it can reuse the underlying files instead of re-reading every document. It is the natural fix for oversharded read-only data and a standard step in the warm phase.
Split: more, smaller shards
Split does the reverse, creating a new index with more primaries. The target count must be a multiple of the source count, and the operation depends on the routing space that was set when the index was created. It is useful when a growing index has shards that have become too large but still needs to keep the same name and content.
Force merge: fewer segments
Force merge does not change the number of shards. It rewrites the segments of each shard into fewer, larger ones, reducing overhead and improving search efficiency for read-only data. It uses a lot of input and output activity and temporary disk space, so it should only be applied to indices that are no longer receiving writes.
Reindex: the universal fix
When nothing else fits, reindexing copies documents from the old index into a new one with the right settings. It is slow and resource-hungry, but it is always possible, and it lets you also fix mappings and other design errors at the same time. For huge datasets, it should be planned like a migration, with monitoring, throttling and a clear plan for switching over.
Diagnose the size problem
List shards with their sizes and find which indices are too small or too big.
Pick the least disruptive tool
Prefer shrink or split over reindex when their rules allow it, since they are faster and cheaper.
Prepare capacity
Make sure enough free disk and network bandwidth exist, and schedule the work outside peak hours.
Fix the template so it does not recur
Update index templates and lifecycle policies, or the same problem will return with tomorrow’s new indices.
| Tool | Changes | Main Requirement | Best For |
|---|---|---|---|
| Shrink | Fewer primaries | Read-only source, target is a factor of source | Oversharded read-only data |
| Split | More primaries | Target is a multiple of source | Shards grown too big |
| Force merge | Fewer segments | No further writes | Cheaper searching of old data |
| Reindex | Anything | Time and spare capacity | Fundamental redesign |
Fixing existing indices but forgetting the template. Tomorrow’s rollover then creates another badly sized index and the cleanup becomes a never-ending chore.
15Multi-Tenancy: Many Customers, One Cluster
Serving thousands of customers is where shard sizing choices are tested hardest.
Three common designs
Software companies that host many customers in one cluster generally pick one of three designs. The first is an index per tenant. The second is one shared index for all tenants, with a tenant identifier filtering each query. The third is a hybrid where big tenants get their own indices and small tenants share. Each has strengths, and each interacts with shard sizing in a different way.
flowchart TD
T["Incoming tenant data"] --> D{"How large is the tenant?"}
D -->|Very large| A["Dedicated index with its own shards"]
D -->|Medium| B["Shared index group with routing by tenant"]
D -->|Small| C["Large shared index with filtered alias"]
Index per tenant
Simple isolation and easy deletion of a tenant, but thousands of tenants means thousands of tiny shards and heavy overhead.
Shared index with filter
Very efficient in shard count, but a busy tenant can affect others and every query must be carefully filtered for security.
Hybrid
Large tenants get their own indices, while small ones share. It balances efficiency and isolation at the cost of more logic.
Custom routing
Routing all documents of one tenant to the same shard means a tenant query touches one shard instead of all of them.
Routing to reduce fan-out
In a shared index with many shards, a query for one tenant would normally visit every shard. By supplying a routing value equal to the tenant identifier at both write and read time, the query goes only to the shard that holds that tenant’s data. This can cut latency and resource use dramatically. The trade-off is uneven shard sizes when tenants differ greatly in size, because a huge tenant places all of its data on a single shard. That is why the hybrid approach gives very large tenants their own indices.
Protecting tenants from each other
Filtered aliases give each tenant a named view of the shared index, with the filter built in, which reduces the chance of a query forgetting the tenant condition. Role-based security can restrict users to their alias or to documents matching their tenant. Resource limits, quotas and separate lifecycle policies help stop a noisy tenant from harming the rest.
Starting with an index per tenant because it is simple, then reaching ten thousand tenants. The cluster state and shard counts explode long before the data volume does, and migrating later is painful. Decide on a tenancy model with the expected number of tenants in mind.
16Shard Sizing Across Hot, Warm, Cold and Frozen Tiers
The ideal shard is not the same at every stage of an index’s life.
Hot tier
On hot nodes the priority is write throughput and quick access to fresh data. Shards are sized so they can be written to in parallel across nodes, and they often reach the upper end of the size range before rollover. Replicas are common for safety and read capacity. Merges are ongoing, so disk speed matters.
Warm tier
When an index is no longer written to, it can be reshaped. Shrinking reduces the number of primaries, force merge reduces the segments, and read-only status protects the data. The aim is fewer, well-compressed shards that use little memory per gigabyte, since warm nodes are expected to hold a lot of data per machine.
Cold and frozen tiers
With searchable snapshots, the shard layout of the snapshot becomes the layout of the mounted index. Large, well-merged shards work well here, because every shard means extra requests to the repository and extra overhead in the cache. Frozen nodes tolerate a higher number of shards per node than normal nodes, because their shards are cache-backed and light, but that does not mean shard count is free.
| Tier | Shard Goal | Typical Actions | Replica Approach |
|---|---|---|---|
| Hot | Spread writes, moderate size | Rollover on size | Usually one or more |
| Warm | Fewer, compact shards | Shrink, force merge, read-only | Often one |
| Cold | Compact, efficient shards | Snapshot and mount | Can be none with snapshot backing |
| Frozen | Large, few shards | Partial mount | None, repository is the copy |
Clothes you wear every day hang loosely in your wardrobe, easy to grab. Clothes for the off-season are folded compactly and vacuum-packed in the loft. The same item takes different shapes depending on how often you need it.
Design the shard plan across the entire lifecycle, not only for the first day. A layout that suits fresh writes but cannot be shrunk cleanly later will cost you at every later tier.
17Recovery, Snapshots and the Cost of Failure
Shard size decides how quickly the cluster heals, so it is a reliability decision as much as a performance one.
Recovery time and risk
When a node fails, its shards must be rebuilt on other nodes from surviving copies. The time needed grows with shard size and with the number of shards on the failed node. During that window, some data exists in fewer copies than intended, and a second failure could cause real loss. Smaller shards recover in parallel and in shorter individual times, which narrows the danger window. Recovery speed is also throttled to protect normal traffic, so raising the limit trades safety speed against search performance.
Snapshots and shard count
Snapshots copy shard files to the repository. Each shard adds bookkeeping, so tens of thousands of tiny shards make snapshots slow to start and to finish, and make repository listings heavy. On the other hand, very large shards make each snapshot task long. Well-sized shards make snapshots both quick to organise and quick to restore, which matters when you need to recover from a real disaster.
| Shard Size | Time to Copy at 100 MB per Second | Risk Comment |
|---|---|---|
| 10 GB | About 1.7 minutes | Very quick to move and heal |
| 50 GB | About 8.5 minutes | Comfortable for most clusters |
| 200 GB | About 34 minutes | Long window of reduced safety |
| 500 GB | About 85 minutes | Painful to move, heal or restore |
Restart behaviour
During a rolling upgrade, each node stops, restarts and rejoins. Its shards recover while the next node waits. If each node holds a manageable number of moderate shards, this takes minutes. If it holds huge numbers of tiny shards, the recovery phase alone can take many times longer, and upgrades that should fit in a night stretch across days.
After a warehouse fire drill, workers can return to their desks quickly if everyone sits in a few open rooms. If every worker sits in a separate locked cubicle, each door must be opened one by one, and the return takes all day.
Decide the longest recovery time you can accept, then work backwards to a maximum shard size. This turns a vague preference into a number you can defend in a design review.
18Finding Your Own Number: A Benchmarking Method
Published ranges are a starting point. The real answer for your data comes from a small, careful experiment.
Prepare realistic data
Use a sample of real documents with real mappings and real field values, because compression and search cost depend on the content.
Build a single-shard test index
Use one primary shard and no replica on a node with the same hardware as production, so you measure one shard in isolation.
Add data in stages and measure
After each stage, run your typical queries and record latency and resource use. Find the size at which results stop meeting your targets.
Apply a safety margin
Choose a target size comfortably below the breaking point, leaving room for busier queries, growth and merges.
Test the whole cluster
Repeat with the intended node count and concurrency, including a simulated node failure, to verify recovery time and search behaviour.
Write it down and revisit
Record the numbers, the assumptions and the date. Repeat the test when hardware, mappings or query patterns change materially.
What to measure
Query latency percentiles
Look at slow percentiles, not only the average, because users notice the slow cases.
Indexing throughput
Documents per second at sustained load, with merges running as they would in production.
Heap and cache behaviour
Garbage collection frequency, memory pressure and cache hit rates as data grows.
Recovery and restore time
How long it takes to relocate a shard and to bring a node back after a restart.
Elastic provides a benchmarking tool called Rally, designed for repeatable tests with realistic tracks. It is a good way to make experiments consistent and comparable.
Benchmarking with random or overly simple test data. Real data compresses differently and has different field cardinality, so a test on toy data can give a shard size that fails in production.
19Monitoring and Troubleshooting Shard Health
Shard sizing is not a one-time task. Data changes, so you must keep watching the numbers.
The numbers worth tracking
Shard count per node
Compare it with the heap and with the configured limits, and track its trend.
Average and extreme shard sizes
Find indices whose shards are far below or above your target range.
Pending cluster tasks
A growing queue on the master is a classic sign of state overload from too many indices or shards.
Heap usage and garbage collection
Frequent long collections on data nodes with little data suggest shard overhead.
Search and indexing thread queues
Rejections indicate that the nodes cannot keep up with the tasks that the shard layout creates.
Disk usage per node
Uneven usage points to imbalance, and high usage threatens watermarks and merge space.
A troubleshooting flow
flowchart TD
P["Symptom: slow cluster or unstable nodes"] --> Q{"Many pending master tasks?"}
Q -->|Yes| R["Check total shard and index count, look for oversharding"]
Q -->|No| S{"Some nodes much busier than others?"}
S -->|Yes| T["Check shard placement and hot spots"]
S -->|No| U{"Slow recovery or long merges?"}
U -->|Yes| V["Check for very large shards"]
U -->|No| W["Check queries, mappings and hardware"]
Useful diagnostic views
Elasticsearch provides compact listing views for shards, indices and allocation, which show sizes, document counts and node placement. It also provides cluster health, pending task and node statistics views. Together with the allocation explain feature, these answer most questions about why shards are where they are and whether they are healthy. Monitoring dashboards in Kibana present the same data over time, which is essential for spotting slow trends before they become emergencies.
Only looking at disk usage and CPU. A cluster can be at thirty percent disk and thirty percent CPU and still be in trouble because its heap and cluster state are drowning in shards.
20Security and Governance Around Shard Design
Sizing decisions touch security more than people expect, especially in shared clusters.
Isolation and its price
Strong isolation between teams or tenants is easiest with separate indices, since permissions can be granted per index. But separate indices for every team creates the small-shard problem. Shared indices reduce overhead but rely on document-level security and filtered aliases to keep data apart. Choosing between them is a balance of risk, cost and operational effort, and it should be decided together by the architecture and security teams, not by the shard count alone.
Protecting the platform from careless users
Because index creation is cheap for the user but costly for the cluster, uncontrolled creation of indices is a genuine risk. Index templates, naming rules and permission limits can prevent teams from creating thousands of tiny indices by accident. Applications that create an index per request or per user session are a well-known source of shard explosions, and a governance rule against them saves a great deal of pain.
Data protection duties
Deleting one customer’s data is much simpler when it lives in its own index than when it is mixed inside a shared one, where it needs a delete-by-query and a later cleanup of segments. If your legal duties require prompt erasure, that should influence your tenancy and shard design. Encryption in transit and at rest, audit logging, and guarded snapshot repositories apply regardless of the shard design, but they must scale with it.
Governance rule: templates decide settings
Let templates define shard counts and lifecycle policies, and restrict who may create indices that bypass them.
Governance rule: budget for shards
Give teams a shard budget, much like a cost budget, and review it regularly so growth stays intentional.
Write retention and erasure duties into the lifecycle policy and the tenancy design together, so deletion is automatic and provable instead of a manual scramble.
21Design Patterns and Anti-patterns
Patterns that keep shard counts under control, and traps that keep appearing in real clusters.
Patterns worth adopting
Size-based rollover everywhere
Use data streams and roll over by primary shard size, so every index carries shards in the target range regardless of daily traffic.
Hot with parallelism, warm with compaction
Use enough primaries for writes when the index is hot, then shrink and merge once it is read-only.
Shared streams for small sources
Group small applications with similar retention into shared streams, and separate fields or labels distinguish them.
Hybrid tenancy
Give big tenants dedicated indices, and let small tenants share with routing and filtered aliases.
Shard budget and review
Track shards per node and per team, and review them like any other capacity metric.
Anti-patterns to avoid
Problem
Every index is created with the same default primary count, no matter how much data it will hold.
Why It’s Harmful
Tiny indices get too many shards, and giant ones get too few. Neither is tuned to real volume.
Correct Approach
Set the primary count through templates based on expected size, and use rollover to keep shards near the target.
Problem
An application creates a new index for every user, request or short-lived job.
Why It’s Harmful
Index and shard counts grow without bound, the master slows down, and the cluster eventually refuses new indices.
Correct Approach
Store such data in a shared index with an identifier field, and use routing or aliases for isolation and speed.
Problem
Planning for ten years of growth by creating a very high primary count today.
Why It’s Harmful
You pay the overhead of a huge layout for years, and the layout may still not suit the data you eventually have.
Correct Approach
Size for the near future and use split or reindex when real growth arrives.
Problem
Raising shard limits or adding nodes whenever the cluster complains, without examining shard sizes.
Why It’s Harmful
Costs rise and the underlying inefficiency stays, so the same problem returns at a larger scale.
Correct Approach
Diagnose shard sizes and counts first, correct the design, then scale hardware only as a last step.
Problem
Allowing a single shard to grow to hundreds of gigabytes because “it still works”.
Why It’s Harmful
Recovery, relocation and merges become very slow, and any failure has a large and long-lasting impact.
Correct Approach
Enforce a maximum shard size through rollover and review any index that exceeds it.
22Best Practices and Common Mistakes
A checklist of habits that keep a large cluster calm.
Set a target range
Agree on a shard size range and document why, so everyone designs to the same target.
Use templates and policies
Let index templates and lifecycle policies enforce shard settings automatically.
Include time filters
Make sure queries on time-based data always carry a time range and target specific streams.
Review regularly
Check the distribution of shard sizes every quarter and after any major change in traffic.
Test recovery
Practice node failures and restarts so you know real recovery times before an emergency.
Keep headroom
Leave free disk, heap and shard capacity, since merges, moves and growth all need spare room.
Copying a shard count from a blog post or another company’s cluster. Their data, queries and hardware differ from yours, so their number is a hint at best.
Ignoring the document count. Shards with small documents can hold a great many of them at modest gigabyte sizes, so watch both dimensions.
Treat shard settings like code. Keep templates and policies in version control, review changes, and roll them out step by step, because a small edit can shape terabytes of data.
23Real-World Scenarios
These illustrative examples show how the ideas combine in different kinds of organizations.
Central logging platform
A company gathers logs from hundreds of services and discovers that thousands of tiny daily indices are slowing the master. They merge sources into a small number of shared data streams, roll over on primary shard size, and shrink old indices. Shard counts fall dramatically, restarts become routine, and dashboards speed up.
E-commerce search
An online store keeps a product index of moderate size and needs very fast queries. They use a few primaries sized for the index at its expected size, add replicas during seasonal peaks, and reindex to a new layout once a year when growth demands it.
Software-as-a-service analytics
A provider hosts thousands of customers. Tiny customers share indices with routing, mid-size ones share fewer groups, and a handful of giants get dedicated indices. The cluster keeps a predictable shard count while giving big customers isolation.
Security analytics team
A team keeps a year of events and mostly queries recent weeks. They use hot indices sized for parallel writes, shrink and merge in the warm phase, and keep older data as compact snapshot-backed shards. Recovery is measured in minutes and costs stay controlled.
These scenarios are illustrations, not measurements from named companies. Your own results depend on your data and hardware, which is why Chapter 18 recommends running your own tests.
24Advantages and Trade-offs of a Deliberate Strategy
A shard sizing strategy takes effort, so let us be honest about what it returns and what it demands.
Advantages
- Lower memory use and a lighter master
- Faster and more predictable searches
- Quicker recovery, upgrades and snapshots
- Better balance and fewer hot spots
- Lower hardware cost for the same data
- Clearer capacity planning and easier growth
Disadvantages / Trade-offs
- Requires upfront analysis and testing
- Needs ongoing review as data and queries change
- Compromises exist between write speed and compact storage
- Mistakes still require costly repair operations
- Governance rules may feel restrictive to teams
When you can keep it simple
If your data is small, your cluster has only a handful of indices, and growth is slow, the default single shard is often perfectly good. Elasticsearch’s own default of one primary shard per index in recent versions reflects that most indices are small. Deliberate strategy pays off when volume, number of indices or number of teams grows, and it is best to start the habit before the pain arrives.
If you have more than a few hundred shards, or any single index above about fifty gigabytes per shard, or an ongoing struggle with slow restarts or heavy heap use, it is time to adopt a written shard strategy.
25Frequently Asked Questions
A common starting range is about ten to fifty gigabytes per shard, with larger values for logs and smaller for latency-sensitive search. The right value for you comes from testing with your own data and queries.
Not by simply editing it. You can use shrink, split or reindex to create a new index with a different count. That is why planning at creation time matters.
Yes. The replica count can be changed at any time on a live index, so it is a flexible tool for adjusting resilience and read capacity.
No. More shards add parallelism up to a point, but each one carries overhead. Beyond that point, extra shards only add coordination work and memory use.
A common comfort level is around twenty shards or fewer per gigabyte of heap, and by default a normal data node is limited to about one thousand. The practical number depends on shard content and workload.
Usually it is better to use data streams and roll over by size, so that each index holds a sensible amount of data no matter how busy the day was.
Shrink reduces the number of primary shards by creating a new index. Force merge keeps the same shards but reduces the number of segments inside each one.
Not always. It suits a small number of large tenants. With thousands of small tenants, it creates too many tiny shards, and a hybrid design is usually better.
It sends all documents that share a routing value to the same shard, so queries with that value visit one shard instead of all. The risk is uneven shard sizes when groups differ greatly.
Typical signs are slow cluster state updates, high heap use with little data, slow restarts, many tiny shards, and errors about shard limits.
Search cost relates to how many documents a shard holds, not only its gigabytes. A shard with tiny documents can reach very high counts at a modest size, so both should be watched.
It reduces the operational work, and some newer serverless offerings hide much of it. Still, in many deployments the shard design remains yours, so the principles here continue to apply.
26Summary and Key Takeaways
Shard sizing strategy is the discipline of choosing how big each shard should be and how many the cluster should carry. Too many small shards drain memory, slow the master and make restarts painful. Too few huge shards make recovery, movement and merging slow and risky. The healthy middle, guided by ranges such as ten to fifty gigabytes and checked by your own tests, is reached by using data streams, rollover by size, tier-aware reshaping, careful replica choices, and a tenancy model that matches your customer count. Add monitoring, governance and regular reviews, and you get a cluster that stays fast and affordable as it grows.
Key Takeaways
- Every shard has a fixed cost — heap, file handles, cluster state space and thread time are spent per shard, however small it is.
- Aim for a healthy range, then measure — about ten to fifty gigabytes is a good starting point, and your own benchmarks give the final answer.
- Roll over by size, not by calendar — data streams and size-based rollover keep shards even across quiet and busy periods.
- Plan the whole lifecycle — use enough primaries for writes while hot, then shrink and merge when data becomes read-only.
- Size for recovery and balance — shard size sets healing time, and even placement prevents hot spots.
- Match tenancy to tenant count — use a hybrid design with routing and filtered aliases instead of an index for every tenant.
- Watch and govern continuously — track shard counts and sizes, enforce templates, and fix causes before adding nodes or raising limits.