The Merge Policy in Elasticsearch
A complete, friendly guide to the quiet housekeeping rules that decide when Elasticsearch combines many small pieces of an index into fewer big ones, why that keeps searches fast and disks tidy, what it costs, and how to tune, monitor, and troubleshoot it in production.
Imagine you keep a diary, but you are not allowed to erase or edit anything you have written. Every hour you start a fresh, tiny notebook and write the newest notes in it. At the end of a week you own two hundred little notebooks. Finding a fact now means opening all two hundred, and your desk is a mess. So you make a rule: whenever there are ten small notebooks, you copy them neatly into one thicker notebook, skip anything that was crossed out, and recycle the small ones. When there are ten thick notebooks, you copy them into an even thicker binder, and so on.
That rule is a merge policy. Elasticsearch keeps its data in pieces that can never be edited, so it needs exactly this kind of rule to stay tidy. The rule decides when to combine pieces, which pieces to combine, and how big the result may grow. Get the rule right, and searches stay quick, disks stay lean, and nobody thinks about it. Get it wrong, and you meet slow searches, throttled writes, and disks that fill up for no obvious reason.
In this guide you will learn what a merge policy is, why Elasticsearch needs one, how the default policy thinks, which settings control it, and how it interacts with searching, indexing, disks, and data lifecycle. You do not need any background in search engines. Every new word is explained the first time it appears, and each big idea comes with an everyday comparison.
1What Is a Merge Policy?
The shortest possible answer: a merge policy is the set of rules that tells a shard which of its small data pieces, called segments, should be combined into a bigger one, and when.
Let us build the definition slowly. Elasticsearch is a search and analytics engine. Companies use it to search products, explore application logs, count events, and draw charts. Data lives in indices, which are like big labeled cabinets of documents. Each index is cut into pieces called shards, so that many servers can share the work.
Inside every shard, Elasticsearch relies on a search library called Lucene. A Lucene index stores its data in many small, read-only bundles of files called segments. Once a segment is written, it is never changed. New documents go into new segments. A search must look at every segment in the shard and combine the results.
Because segments pile up as data arrives, something must clean up. The cleaning job is called a merge: several segments are read, their live contents are written into one new, larger segment, and the old segments are deleted. The merge policy is the decision maker for this job. It looks at the current list of segments, and it answers three questions: is a merge needed now, which segments should take part, and how large may the result be?
Think of a mailroom in a big office. Letters arrive all day and are dropped into small trays. If nobody ever combined the trays, finding one letter would mean checking hundreds of trays. The mailroom manager has a rule: “When ten trays of similar size pile up, empty them into one bigger box and throw away the returned or cancelled mail.” The manager’s rule is the merge policy. The clerk who actually carries the mail to the big box is a different role, called the merge scheduler, which you will meet in Chapter 7.
The default policy
Elasticsearch, like Lucene, uses a policy named the tiered merge policy by default. It groups segments into tiers by size, like sorting coins into small, medium, and large piles, and merges the members of a tier when the pile gets too tall. Most of this guide explains how that policy thinks and how its settings shape its behavior.
Why you rarely notice it
Merges happen quietly in the background, dozens or hundreds of times a day on a busy shard. When the policy suits the workload, you never see them. You only notice when something goes wrong: writes slow down because merges cannot keep up, searches are sluggish because too many segments exist, or disks are fuller than the number of documents suggests.
You may hear “segment merging,” “compaction,” and “merge policy” used loosely. In Elasticsearch, a merge is the act of combining segments, the merge policy is the rule that selects segments, and the merge scheduler is the worker that runs the merges. The force merge is a separate operation that you ask for by hand.
What a merge policy is not
A merge policy does not decide which documents match a search, it does not move shards between servers, and it does not copy data to replicas. It only reorganizes the files inside one shard copy. It also does not fix a bad design: a shard with millions of tiny documents and huge mappings will still be heavy after a perfect merge.
Where you will meet it
You will meet the merge policy when you tune a bulk data load, when you plan how old time-based indices are compacted, when you see log lines about throttled indexing, when a busy update-heavy index carries many deleted documents, and when someone suggests running a force merge and you must judge whether that is a wise idea. Knowing how the policy thinks turns each of these into a clear decision.
2Why It Exists: Immutable Segments and the Small-Files Problem
Segments never change once written. That gives Elasticsearch speed and safety, but it creates a housekeeping problem that only merging can solve.
Why does Lucene store data in read-only segments at all? Because read-only files are easy to cache, easy to share between many searches at once, and impossible to corrupt halfway through an edit. A search can read a segment without locking anything, and the operating system can keep its contents in memory very efficiently. These benefits are a large part of why Elasticsearch searches so fast.
The price is that updates and deletes cannot change a segment in place. To change a document, Elasticsearch marks the old version as deleted and writes a new version somewhere else. To delete a document, it only marks it. Chapter 5 explains this trick. The result is that segments slowly fill with dead entries, and new segments keep appearing.
Three problems that pile up
- Too many segments. Each search must visit every segment in the shard. Every visit has a fixed overhead, so a hundred tiny segments are far slower to search than one big segment with the same content.
- Too many files. Each segment is several files on disk. Thousands of files strain the operating system, which limits how many files a process may keep open.
- Wasted space. Deleted documents still occupy their old segments. Without cleaning, the disk keeps carrying data that no search will ever return.
Picture a library where books may never be altered after they are shelved. When a book has a mistake, the librarian shelves a corrected copy and puts a “do not lend” sticker on the old one. Over the years, the library fills with sticker-covered books and thousands of thin leaflets. Readers waste time walking between shelves. Once a year, the staff take all the leaflets and the sticker books, reprint the good content into a few sturdy volumes, and discard the rest. Merging is that yearly reprint, done continuously and in small steps.
The alternative that would be worse
A different design would edit files in place. That approach needs locks, careful recovery after crashes, and slower caching. Lucene chose immutability plus merging. This kind of design is sometimes called a log-structured approach: write new data quickly in small pieces, and reorganize it later in the background. Many modern databases use the same idea, because it makes writing fast and reading safe.
An illustrative story
ShelfSpark, an imaginary bookstore chain
ShelfSpark stores its product catalog in one Elasticsearch index. Prices change all day, and each change rewrites the product document. After a week without any tuning of merges, a shard that should hold about 40 GB of live data occupies 55 GB, and searches touch 180 segments instead of 20. The team learns that the natural merge policy was keeping up with the number of segments but that heavy updates left a large share of deleted documents in the big segments. This story is invented, but the pattern is real: updates create deleted documents, and merging is how the space returns.
A short history
Lucene has used segment merging since its earliest days. Over time, its default policy has improved. The tiered policy became the default in the 3.x era of Lucene, replacing older “log” style policies. In more recent years, Lucene added a limit on the share of deleted documents that a segment may carry and improved how it treats very large segments. Elasticsearch exposes the important controls as index settings and keeps sensible defaults so that most users never touch them.
A merge policy cannot make a badly designed index fast. It keeps the internal structure tidy. If your queries are heavy or your mapping is huge, merging will not solve that. It is one layer of housekeeping among several.
3The Building Blocks You Need to Know First
To follow the rest of this guide you need eight simple ideas: shard, segment, deleted document, refresh, flush, translog, merge, and the two roles called policy and scheduler.
One slice of an index
Each shard is a complete, small search engine. The merge policy works inside a single shard copy, never across shards.
A read-only bundle of files
A segment holds a batch of documents with their search structures. Once written, it never changes until a merge replaces it.
A document marked as dead
A deleted document still sits inside its segment, but a small bit map tells searches to ignore it until a merge removes it for good.
Making new data searchable
A refresh turns recently buffered documents into a new segment so that searches can see them. It happens about once per second by default.
Making data durable on disk
A flush writes a safe checkpoint of all segments to disk and clears old log entries. It is about safety, not visibility.
The safety diary
The transaction log records every write before it is acknowledged, so that data survives a crash between flushes.
Combining segments
A merge reads several segments and writes one new segment that contains only their live documents.
The decider and the worker
The policy chooses what to merge. The scheduler runs merges with limited threads and speed limits.
Two kinds of document counts
When you ask Elasticsearch how many documents an index holds, it can report two numbers: the count of live documents and the count of deleted ones that still occupy space. The gap between them is a direct sign of how much cleaning work the merge policy has waiting. Keep these two numbers in mind, because they come back in Chapters 5, 24, and 26.
What is inside a segment
A segment is not a single file. It is a small family of files, each with its own job. There is a structure that maps words to the documents containing them, used for text search. There is a compact column store of values, used for sorting and grouping. There are stored copies of the original document source. There are helper structures for numbers, geographic points, and vectors. And there is a small file recording which documents are deleted. A merge rewrites all of these together, which is why it costs real reading and writing.
Think of a segment as a sealed folder from a filing office. Inside are an alphabetical index, a copy of every paper, a list of totals, and a sticky note saying which papers are cancelled. When the office merges folders, clerks open ten sealed folders, copy all the papers that are not cancelled into one new folder, rebuild the index and the totals for the combined set, and seal it. Nothing is edited inside a sealed folder; new folders replace old ones.
Where merging sits in the data path
The diagram shows how a document travels from a client to a shard and where merging takes place. The client usually reaches the cluster through a load balancer or an API gateway, which passes the request to a node. The node routes it to the primary shard, which writes it to its memory buffer and translog, and later turns the buffer into segments. Merging then works on those segments in the background.
flowchart TD
A["Client application"] --> B["Load balancer or API gateway"]
B --> C["Elasticsearch node"]
C --> D["Primary shard"]
D --> E["In-memory indexing buffer plus translog"]
E -->|Refresh| F["New small segment, now searchable"]
F --> G["Merge policy checks the list of segments"]
G -->|Merge needed| H["Merge scheduler runs a background merge"]
H --> I["One larger segment replaces several small ones"]
D -.->|Copies the write| R["Replica shard: keeps its own segments and its own merges"]
Notice the dotted line to the replica shard. A replica receives the same writes, but it builds and merges its own segments independently. Two copies of the same shard usually contain the same documents but have different segment layouts. This matters for caching and for monitoring, and Chapter 18 returns to it.
Everything in this guide happens per shard copy. When someone says “the index has 40 segments,” they usually mean the total across all shards, or a particular shard. Always check which one is meant.
4How Data Becomes Segments: Refresh, Flush, and the Buffer
Merging only makes sense once you see where segments come from. Every segment starts life in a memory buffer and is born at a refresh.
When a document is indexed, three things happen almost at once. It is added to an in-memory buffer, where Lucene collects new documents. It is written to the translog, the safety diary, so that a crash does not lose it. And it is sent to the replica copies. At this moment the document is safe but not yet searchable.
The refresh: birth of a segment
A refresh takes the current contents of the memory buffer and writes them as a brand-new segment. From that moment, searches can see those documents. The setting index.refresh_interval controls how often refresh happens, and its default is one second for indices that are actively searched. That means a busy shard creates a new small segment roughly every second, and each of those segments is tiny.
The memory buffer can also fill up before the timer fires. The node has a budget for indexing buffers, controlled by indices.memory.index_buffer_size, which defaults to ten percent of the heap. When the buffers of the shards on a node together exceed that budget, Elasticsearch writes some of them out as segments even without a refresh.
The flush: a safe checkpoint
A flush is different. It asks Lucene to make all segments durable on disk with a commit, and then it clears the parts of the translog that are no longer needed. Flushes happen automatically when the translog grows too large or after a period of time. Flushing does not directly create the small segments that merging cares about, but it does make the current set of segments permanent.
Picture a teacher who collects homework on a desk. The stack on the desk is the memory buffer. Every hour, the teacher staples the stack into a folder and puts it on the class shelf so students can read it, which is a refresh. At the end of the day, the teacher locks the shelf and records in a logbook exactly which folders are there, which is a flush. If the day’s stack were never stapled, nobody could read it, and if the logbook were never written, a power failure could lose track of what exists.
How many segments does a busy shard create?
A shard that receives steady traffic with the default one-second refresh interval creates about one new segment per second. In an hour, that is thousands of tiny segments if nothing merged them. This is why merging is not optional: without it, a busy shard would drown in files within minutes. It also shows why the refresh interval is such a strong lever: lengthening it from one second to thirty seconds creates thirty times fewer tiny segments, and the merge policy has far less to do.
| Event | What it does | Creates a segment? | Effect on merging |
|---|---|---|---|
| Index a document | Adds it to the memory buffer and translog | No | None yet |
| Refresh | Writes the buffer as a new searchable segment | Yes, usually a small one | Adds work for the policy |
| Buffer full | Writes buffers of busy shards out to segments | Yes | Adds work for the policy |
| Flush | Commits all segments and trims the translog | No | Makes the segment list durable |
| Merge | Combines several segments into one | Yes, a bigger one, replacing several | Reduces the segment count |
Segments and searches
Every search opens a consistent view of the shard called a reader, which lists the segments that exist at that moment. If a merge finishes while a search is running, the search keeps using its old view, and the old segments remain on disk until the last search using them ends. This is why merges never disturb running searches and why disk space from merged segments is freed only after the readers that use them are closed.
If an index does not need near-instant visibility of new data, lengthen its refresh interval. A refresh interval of ten to thirty seconds is a very effective way to reduce merge pressure, and many analytics and logging workloads can accept it.
Idle shards and the refresh timer
Modern Elasticsearch pauses scheduled refreshes on shards that have not been searched for a while, and refreshes them the next time a search arrives. This reduces the number of tiny segments created on shards that nobody is reading, and it helps large clusters with many quiet time-based indices.
5Deletes and Updates: Why Dead Data Stays Around
Because segments never change, a deleted document is only marked. The bytes stay until a merge rewrites the segment without them.
When you delete a document, Elasticsearch does not remove it from its segment. Instead, it records the deletion in a small side structure called the live documents bit map. Searches consult this bit map and skip the marked documents. The document’s bytes are still on disk, still part of the segment, until a merge produces a new segment that leaves the dead ones out.
An update is a delete plus an insert
Updating a document works the same way. Elasticsearch marks the old version as deleted and indexes the new version as a fresh document, in whichever segment is currently being built. So an update-heavy index produces a constant stream of deleted documents in old segments and new documents in new segments. If ten percent of documents are updated each day, ten percent of the space in the older segments becomes dead each day.
sequenceDiagram
participant C as Client
participant S as Shard
participant Old as Old segment
participant New as New segment
participant M as Merge
C->>S: Update document 42
S->>Old: Mark version 1 of document 42 as deleted
S->>New: Write version 2 of document 42
Note over Old: Dead bytes remain on disk
M->>Old: Later, read live documents only
M->>New: Write live documents into a merged segment
M->>Old: Old segment removed, dead bytes reclaimed
Imagine a printed phone directory that cannot be erased. When a person changes their number, you cross out the old line with a pen and add the new line at the back in a supplement. The book gets thicker with crossed-out lines, and it stays fat until someone reprints a clean copy without the crossed-out lines. The reprint is the merge.
How much waste is normal?
Some waste is normal and even healthy: merging costs time and disk activity, and reclaiming every dead byte immediately would be wasteful. The merge policy tolerates a certain percentage of deleted documents before it becomes eager to clean. The setting index.merge.policy.deletes_pct_allowed controls this, and its default in current versions is twenty percent. A shard that shows more than that share of deleted documents across its segments is a candidate for cleaning by the policy.
Some deleted documents are kept on purpose
Elasticsearch uses a feature called soft deletes to keep a short history of changes on each shard. Replicas and cross-cluster replication use that history to catch up after a temporary disconnection, without copying the whole shard. A document that was deleted may therefore be retained in a special form for a while, held by a retention lease with a default period of twelve hours. During that time, merges keep the history, and the count of deleted documents may not drop right after a merge. This is normal and not a sign of a broken policy.
Deleting whole indices is different
When you delete an entire index, Elasticsearch removes its files at once. There is no merge involved and no reclamation delay. This is the reason why time-based designs, where old data is removed by deleting whole daily or weekly indices, are so efficient: they avoid the slow, expensive process of removing individual documents.
Why this matters for capacity planning
A common surprise is that the disk usage of an index is larger than the size of its live data would suggest. For append-only data such as logs, the difference is small. For catalogs, profiles, or any workload with frequent updates, it can be large. When you plan storage, include a margin for deleted documents and for the temporary space that merges need, which Chapter 17 explains.
If you delete a document for privacy reasons, its bytes remain in a segment until a merge removes them and until old copies in snapshots expire. Chapter 23 explains what this means for compliance.
6What a Merge Actually Does
A merge is a careful copy. It reads several old segments, writes one new one, and only then lets the old ones go. Knowing the steps explains its costs and its benefits.
Let us follow one merge from start to finish. Imagine a shard with ten segments of similar size, and the policy decides that they should be combined.
The plan is handed over
The policy names the ten segments. The scheduler assigns a merge thread to run the job. The old segments stay fully searchable during the whole process.
Live documents are read
The merge thread reads each segment and skips every document that is marked as deleted, except for those kept on purpose as history.
New structures are built
Term dictionaries, postings, column values, stored fields, and other structures are rebuilt for the combined set of documents and written to new files.
The new segment is checked and registered
Checksums are written, and the new segment is added to the shard’s list of segments, replacing the ten old ones in a single atomic step.
Searches switch over
New searches use the merged segment. Searches that were already running finish on the old view.
Old segments are deleted
When no search is using the old segments any more, their files are removed and the disk space returns.
flowchart LR
subgraph Before["Before the merge"]
S1["Segment A: 100 MB, 15 percent deleted"]
S2["Segment B: 100 MB, 10 percent deleted"]
S3["Segment C: 100 MB, 20 percent deleted"]
end
Before --> M["Merge: read live documents, rebuild structures"]
M --> After["After the merge: one segment of about 255 MB, no deleted documents"]
Think of moving several half-empty storage boxes into one new box. You pick up every item you still want, leave the broken ones behind, and pack the new box neatly. Until the new box is ready and closed, the old boxes stay in the room, so you temporarily need extra floor space. Only after the move is finished do you carry away the old boxes.
The costs of a merge
- Disk reads and writes. All live data in the merged segments is read once and written once. For big merges, that is many gigabytes of input and output.
- CPU work. Rebuilding search structures and compressing data uses processor time. Fields with heavy structures, such as vectors or complex text analysis results, cost more.
- Temporary disk space. The new segment exists together with the old ones until the switch, so a merge needs extra space roughly equal to the size of the merged output.
- Memory pressure on the file system cache. New files compete for the operating system’s cache with files that searches use. After a large merge, some search data may have to be read from disk again.
The benefits of a merge
- Fewer segments. Each search visits fewer places, so it wastes less time on fixed per-segment overhead.
- Reclaimed space. Deleted documents are removed for good, unless they must be kept as history.
- Better compression and locality. Larger segments compress better, and related data sits closer together on disk.
- Fewer files. The operating system keeps track of fewer open files, which lowers the risk of reaching limits.
- More useful caches. Some caches, such as the node query cache, only consider segments above a size threshold, so bigger segments can make them work.
A merge is a copy, not a move
The most important idea is that a merge always writes new data. It never edits old segments. This is why merging is safe: if the process is interrupted, the old segments are still there and still correct, and the half-written new segment is simply discarded. It is also why merging has a cost: every byte that survives is rewritten.
Merges keep documents in order
Segments preserve the order in which documents were added within each segment. A merge concatenates the surviving documents of each source segment in a chosen order. If an index uses index sorting, a feature that keeps documents ordered by certain fields, the merge sorts the combined set, which is more expensive but produces benefits for queries that match the sort order.
Think of merge cost as “bytes rewritten.” Every setting that makes merges more frequent, or makes them combine larger amounts of data, increases the bytes rewritten. Every setting that avoids creating tiny segments in the first place reduces it.
7The Merge Policy and the Merge Scheduler: Who Decides What
Two separate parts work together: the policy chooses which segments to merge, and the scheduler decides how and when the merges actually run.
People often say “merge policy” when they mean the whole system. It helps to separate the two parts, because they have different settings and different failure modes.
| Aspect | Merge policy | Merge scheduler |
|---|---|---|
| Main question answered | Which segments should be merged, and is a merge needed now? | How many merges may run at once, and how fast may they go? |
| Default implementation | Tiered merge policy | Concurrent merge scheduler |
| Looks at | Segment sizes, counts, and deleted document shares | Number of running merges, backlog, and I/O speed |
| Typical settings | Segments per tier, max merge at once, max merged segment, floor size, deletes allowed | Maximum thread count, automatic throttling |
| What it changes | Shape of the segment list over time | Speed, parallelism, and pressure on disks and CPU |
| Symptoms when wrong | Too many segments, too much wasted space, or merges that rewrite too much | Merges that lag behind, indexing throttled, or merges that starve searches of I/O |
A construction company has a planner and a crew. The planner looks at the list of jobs and says, “These ten repairs should be done together, and they should be done now.” The crew boss then decides how many workers to send and how fast they may work so that the neighbors are not disturbed. The planner is the policy. The crew boss is the scheduler. A good plan with a tiny crew still falls behind, and a big crew with a bad plan wastes effort.
How they talk to each other
The conversation happens inside the Lucene writer that owns the shard’s segments. Whenever the set of segments changes, because of a refresh, a flush, or a finished merge, the writer asks the policy whether any merges are needed. The policy returns a list of proposed merges. The writer hands the list to the scheduler, which starts merge threads within its limits. When a merge finishes, the writer asks the policy again, because the new segment list may call for another merge.
sequenceDiagram
participant W as Shard writer
participant P as Merge policy
participant S as Merge scheduler
participant T as Merge thread
W->>W: New segment created by refresh or flush
W->>P: Any merges needed for the current segments?
P-->>W: Yes, merge these ten segments
W->>S: Please run this merge
S->>T: Start a merge thread within the limits
T->>T: Read live documents and write the new segment
T-->>W: Merge finished
W->>P: Any more merges needed now?
P-->>W: No
Why the separation is useful
Because the two parts are independent, you can tune them separately. If merges are choosing the wrong segments, you adjust the policy. If merges are right but too slow or too disruptive, you adjust the scheduler. Many operational problems that look like “merge policy trouble” are really scheduler trouble, such as too few merge threads on fast disks or too many on slow ones.
Other policy types
Lucene supports other policies, such as ones that merge neighboring segments in order of creation. Elasticsearch uses the tiered policy by default because it handles mixed workloads well. Some newer versions of Elasticsearch offer an alternative choice for special time-ordered data, where keeping neighboring documents together has extra benefits. If you use such features, read the documentation of your version for the options that apply. For most users, the default is the right answer.
The merge policy and scheduler settings are marked as expert settings. The documentation advises leaving them at their defaults unless you have measured a problem. Treat every change as an experiment with a way back.
8The Tiered Merge Policy: The Default Explained
The tiered policy sorts segments into size tiers, like coins into piles, and merges a tier when its pile grows too tall.
The main idea is simple. Small segments are cheap to merge and are created constantly, so they should be merged often. Big segments are expensive to rewrite and change little, so they should be merged rarely. The tiered policy creates this behavior by organizing segments into tiers of roughly similar size, where each tier is about ten times bigger than the one below it.
Four numbers that shape the policy
The smallest size that counts
Segments smaller than the floor size, two megabytes by default, are treated as if they were exactly that size. This makes a crowd of tiny segments merge together instead of being ignored.
How many segments per tier
The policy allows about ten segments in each tier by default. When a tier holds more than that, a merge is due.
How many segments in one merge
A single merge combines up to ten segments by default. Merging more at once means fewer passes but a bigger single job.
The largest merged segment
The policy avoids creating segments larger than about five gigabytes by default. Beyond that, segments stay separate.
How tiers form over time
Watch a busy shard. Each refresh adds a tiny segment. When about ten tiny segments of a couple of megabytes each exist, the policy merges them into one segment of around twenty megabytes. When ten of those exist, they merge into one of around two hundred megabytes. When ten of those exist, they merge into one of around two gigabytes, and the pattern continues until segments reach the ceiling.
flowchart LR
T1["Tier 1: about 10 segments of 2 MB"] -->|Merge| T2["Tier 2: about 10 segments of 20 MB"]
T2 -->|Merge| T3["Tier 3: about 10 segments of 200 MB"]
T3 -->|Merge| T4["Tier 4: about 10 segments of 2 GB"]
T4 -->|Merge| T5["Tier 5: segments near the 5 GB ceiling, merged rarely"]
Think of a coin bank sorted by value. When you have ten small coins, you exchange them at the bank for one bigger coin. When you have ten of those bigger coins, you exchange them for a note, and so on. Nobody exchanges a single coin, and nobody keeps a thousand pennies in a jar. The tiered policy is the same exchange rule for segments.
Write amplification: how often is each byte rewritten?
Every time a document climbs a tier, it is copied once. A document that starts in a two-megabyte segment and ends in a multi-gigabyte segment is therefore rewritten about four or five times over its life. This repeated copying is called write amplification. It is the price of keeping the segment count low. Doubling the refresh interval does not double this cost, but making segments start bigger, with a longer interval, removes the lowest tiers altogether.
| Tier | Typical segment size | Typical number allowed | How often merged |
|---|---|---|---|
| 1 | About 2 MB or less | Up to about 10 | Very often, many times per hour on a busy shard |
| 2 | About 20 MB | Up to about 10 | Often |
| 3 | About 200 MB | Up to about 10 | Occasionally |
| 4 | About 2 GB | Up to about 10 | Rarely |
| 5 | Near the 5 GB ceiling | As many as the data requires | Only for cleaning deleted documents |
What this means for segment counts
A healthy shard therefore carries roughly ten segments per active tier. A young, small shard has a handful. A shard of tens of gigabytes typically settles at a few dozen segments. A shard that has grown to several hundred gigabytes has many segments near the ceiling, because these large segments are no longer merged with each other, so the count grows slowly with size. These figures are approximations that depend on how the data arrived, but they are useful for judging whether a count looks reasonable.
The “floor” trick for tiny segments
Without a floor, segments of a few kilobytes would each form their own tier and would never be merged with anything of similar size. The floor makes all segments smaller than two megabytes count as two megabytes. That way, ten segments of ten kilobytes each are treated as ten segments of two megabytes, and the policy merges them into a proper segment. This is a small but important detail for workloads with very short refresh intervals.
Ask Elasticsearch to list the segments of one busy shard, sorted by size. If you see clusters of similar sizes, roughly ten in each cluster, you are looking at tiers in action. That view teaches more than any description.
9How the Policy Chooses: Scoring, Deletes, and Big Segments
When a merge is due, the policy does not pick at random. It scores possible groups and chooses the best one, favoring balanced, cheap, and cleaning merges.
After each change to the segment list, the policy asks a first question: does this shard have more segments than it should, given its total size and the per-tier setting? If yes, it looks for the best group of segments to merge. If no, it asks a second question: are there segments with too many deleted documents? Only if both answers are no does it do nothing.
The allowed number of segments
The policy calculates how many segments it would accept for the current size of the shard. It starts with the floor size and asks how many segments of that size fit into the data, then repeats with segments ten times bigger, and so on, allowing up to the per-tier number at each level. The sum of these is the allowed segment count. When the real count exceeds the allowed count, a merge is due.
The score of a candidate merge
To choose which segments to merge, the policy looks at candidate groups of up to the “merge at once” number and gives each a score. Lower scores are better. The score rewards three qualities.
- Balance. Merging segments of similar size is better than mixing one large and many small ones, because a large segment would be rewritten just to absorb a few small ones. The policy measures this as the “skew” of the group.
- Cost. Smaller total size means less data to rewrite, so cheaper merges are preferred.
- Reclaimed space. Groups with more deleted documents free more space, so they receive a better score.
Consider a moving company deciding which boxes to combine. It prefers to combine boxes of similar size, because putting one big box and three tiny ones into a new giant box means lifting the big box for no reason. It prefers cheap moves, meaning fewer heavy items. And it prefers boxes full of broken items that can be thrown away, since that frees up the most room. The policy’s score is a way of saying all this in numbers.
Big segments and the half-ceiling rule
The largest segments need special care. Rewriting a segment of several gigabytes just to remove a few deleted documents is a poor use of resources. So, the policy treats segments that are larger than about half of the ceiling as too big for ordinary merging. They are considered only when their share of deleted documents rises above the allowed percentage, at which point cleaning them is worth the cost.
The deleted documents limit
The setting index.merge.policy.deletes_pct_allowed caps the share of deleted documents that the policy tolerates across the shard. When the share goes above the limit, the policy prefers merges that reclaim the most dead space, even if a segment is large. Lower values keep the index leaner but cause more rewriting. Higher values save effort but let dead bytes accumulate.
flowchart TD
A["Segment list changed"] --> B{"More segments than the allowed count?"}
B -->|Yes| C["Score candidate groups: balance, cost, reclaimed space"]
B -->|No| D{"Deleted documents above the allowed percentage?"}
D -->|Yes| E["Choose segments that free the most dead space"]
D -->|No| F["Do nothing now"]
C --> G["Propose the best group of up to ten segments"]
E --> G
G --> H["Scheduler runs the merge"]
Why the policy sometimes seems lazy
Operators sometimes see a shard with more segments than they expected and conclude that merging is broken. Usually the policy is doing what it should: the count is within the allowed number for that data size, and the extra segments are too big to be worth combining. A merge would cost more than the benefit. The right judgment is to compare the actual count with the allowed count for your data, not with an ideal of one segment.
Merges are proposed, not guaranteed to run at once
The policy only proposes merges. The scheduler starts them subject to its thread limits. When the shard is busy, proposals may wait in a queue. This delay is normal and usually short. If it grows long, the scheduler is the place to look, as explained in the next chapter.
Trying to reach a single segment per shard on an active index fights the policy. Every new refresh adds segments again, and a huge merged segment cannot be merged efficiently later. Aim for a healthy count, not for the minimum.
10Merge Policy Settings Explained
Six settings shape the tiered policy. All are set per index, all can be changed on a live index, and the defaults are good for most workloads.
| Setting | Default | What it controls |
|---|---|---|
index.merge.policy.floor_segment | 2 MB | Segments smaller than this count as this size, so tiny segments are merged together |
index.merge.policy.segments_per_tier | 10 | How many segments per tier are allowed before a merge is due |
index.merge.policy.max_merge_at_once | 10 | The most segments combined in one merge |
index.merge.policy.max_merged_segment | 5 GB | The rough ceiling for segment size produced by normal merging |
index.merge.policy.deletes_pct_allowed | 20 percent | How much deleted data is tolerated before cleaning becomes a priority |
index.merge.policy.expunge_deletes_allowed | 10 percent | The share of deleted documents above which a segment is chosen when you ask to expunge deletes |
What happens when you change them
| Change | Effect on segments | Effect on cost | When it might help |
|---|---|---|---|
| Lower segments per tier | Fewer segments overall | More merging and more rewriting | Search-heavy indices that rarely change |
| Raise segments per tier | More segments overall | Less merging and less rewriting | Write-heavy indices where search speed matters less |
| Raise max merge at once | Fewer passes per byte | Bigger single merges, spikier I/O | Rarely; keep it in step with segments per tier |
| Raise max merged segment | Fewer very large segments | Heavier big merges | Large read-only indices, used with care |
| Lower max merged segment | More mid-sized segments | Lighter big merges | Update-heavy indices where large segments hold lots of dead data |
| Lower deletes percent allowed | Leaner segments | More rewriting of large segments | Disks are tight and updates are frequent |
| Raise deletes percent allowed | More dead bytes tolerated | Less rewriting | Disk space is plentiful and write load is high |
Think of a tidiness rule at home. “Sort the laundry when there are ten shirts” is the per-tier setting. “Never wash more than ten shirts at once” is the merge-at-once limit. “Stop combining when the basket gets too heavy to lift” is the ceiling. “Throw out clothes once more than a fifth of the closet is worn out” is the deletes limit. A stricter household rule keeps the closet neat but takes more time every week.
Golden rules for changing settings
- Keep the segments per tier at least as large as the merge at once. If the per-tier value is smaller, the policy would want to merge more segments than it is allowed to combine at once, causing repeated small merges.
- Change one setting at a time. Two changes together hide which one had the effect.
- Change on one index first. Test on a single index that represents your workload, and compare merge statistics and search timing before and after.
- Use index templates for future indices. Settings on an index do not follow it to new indices. A template applies them at creation time.
- Write down the reason. Non-default settings are easy to forget, and the reason for them is more important than the numbers.
Related settings around the policy
A few other settings have a strong effect on merging even though they are not part of the policy. The refresh interval controls how many tiny segments are born. The codec, set with index.codec, chooses how stored data is compressed: the default is fast, while the best compression option uses more CPU during writes and merges in exchange for smaller files. The number of replicas multiplies the merging work across the cluster, because every copy merges independently.
Setting the values in practice
These are index settings, so they are changed through the update index settings operation, or placed in an index template. Because they are dynamic, a change takes effect for the next merge decision, and it does not rewrite existing segments by itself. To bring an existing index to a new shape, you would rely on natural merging over time or on a planned force merge, which Chapter 13 discusses.
Names, defaults, and extra options can change between Elasticsearch releases. The names above are the long-standing core settings. Confirm them, and any newer option, in the documentation for the version you run.
11The Merge Scheduler and Throttling
The scheduler is the crew boss. It limits how many merges run in parallel, adjusts their speed, and, when merges fall far behind, slows down indexing to let them catch up.
Elasticsearch uses the concurrent merge scheduler. It runs merges in separate background threads, so that indexing and searching keep going while merges work. Three controls matter.
Maximum merge threads
index.merge.scheduler.max_thread_count sets how many merges may run at the same time on a shard. The default depends on the number of processors: it is half of them, with a minimum of one and a maximum of four.
Automatic I/O throttling
index.merge.scheduler.auto_throttle is on by default. It adapts the merge speed to the backlog: slower when merges are easy to keep up with, faster when they are piling up.
Maximum merge count
When too many merges are waiting or running, the scheduler protects itself by slowing incoming indexing. The limit is related to the thread count and can be set with index.merge.scheduler.max_merge_count.
Why merges are throttled
Merges compete with searches and indexing for the same disks and processors. If merges ran at full speed all the time, they would steal resources and make searches sluggish. The automatic throttle keeps merges at a speed just fast enough to keep up with the incoming data. When a big merge is running but no backlog exists, it goes gently. When merges start piling up, the speed limit rises.
When indexing is throttled
If incoming data creates segments faster than merges can combine them, the number of pending merges grows. Left alone, this would end with thousands of segments and a broken shard. To prevent this, when the backlog passes a limit, Elasticsearch throttles indexing on that shard down to a single thread. The logs show a message that says indexing is being throttled, together with the number of merges in flight and the maximum. When the backlog clears, another message says that throttling has stopped.
stateDiagram-v2
[*] --> MergesKeepUp
MergesKeepUp --> MergesFallingBehind: Segments arrive faster than merges finish
MergesFallingBehind --> MergesKeepUp: Automatic throttle raises merge speed and backlog clears
MergesFallingBehind --> IndexingThrottled: Backlog passes the maximum merge count
IndexingThrottled --> MergesFallingBehind: Merges catch up
IndexingThrottled --> MergesKeepUp: Backlog cleared and throttling stops
Picture a restaurant dishwasher. When plates arrive slowly, the dishwasher works at a relaxed pace. When plates start to stack up, the dishwasher speeds up. If the stack becomes dangerously high, the manager tells the waiters to stop bringing new plates until the pile goes down. The third step is the indexing throttle, and it protects the kitchen from a collapse.
Spinning disks and solid-state disks
The defaults assume modern solid-state storage, which handles parallel reads and writes well. On old spinning disks, several merges in parallel force the disk head to jump around, and the total speed drops. For such disks, the traditional advice is to set the maximum thread count to one. Most current clusters use solid-state storage, where the default is appropriate.
Signs that the scheduler is the problem
- Log lines about throttled indexing appear during normal load.
- The number of running merges stays at the maximum for long periods.
- Segment counts grow steadily over hours while the policy settings are unchanged.
- Disk usage on the data path shows sustained saturation during merges.
What to do about a lagging scheduler
First reduce the incoming pressure on the shard: lengthen the refresh interval, reduce the number of shards that share one disk, and check bulk request sizes. Then check that storage is fast enough for the write rate. Only after these checks consider raising the number of merge threads, and only if disks and processors have spare capacity. Turning up merge parallelism on a saturated machine makes searches worse without solving the cause.
Indexing throttle messages tell you that the cluster is asking for more merging than the hardware can provide. The fix is rarely a setting. It is usually a change in load, in refresh interval, in shard layout, or in storage.
12A Shard’s Life: How Segments Evolve Over Time
Follow one shard from its first document to its last search. The merge policy shapes each stage, and knowing the stages helps you judge what is normal.
Birth: an empty shard
The shard has no segments. The first documents sit in the memory buffer and translog, and nothing is searchable yet.
The first hours: many tiny segments
Each refresh creates a small segment. The count rises quickly until the first tier is full, and the first merges begin, combining ten tiny segments into one small one.
Climbing the tiers
As data grows, merges combine segments of similar size into bigger ones. At any moment, the shard has a handful of segments in each active tier.
Steady state: churn at the bottom
New tiny segments keep appearing and disappearing as they are merged, while large segments stay untouched for long stretches.
Aging: deleted documents accumulate
If the shard receives updates and deletes, older segments collect dead bytes. When the share passes the allowed limit, the policy starts cleaning the largest offenders.
Retirement: read-only and stable
For time-based data, the shard stops receiving writes. Its segments no longer change, and it can be compacted once by a force merge if desired.
flowchart LR
A["Empty shard"] --> B["Many tiny segments from refreshes"]
B --> C["Tiered merges combine similar sizes"]
C --> D["Steady state: churn at the bottom, stable large segments"]
D --> E["Aging: deleted documents accumulate"]
E --> F["Cleaning merges rewrite the big segments"]
D --> G["Writes stop: read-only shard"]
G --> H["Optional one-time force merge"]
Think of a family photo collection. At first, you keep a few loose photos. Then you start a small album for each trip. Later you put several trip albums into a yearly volume. Old volumes sit on the shelf and are rarely opened. Now and then, you pull out a volume to remove blurry photos. And when a chapter of life is over, you may bind everything from that chapter into one final book. The stages of a shard follow the same pattern.
An illustrative growth example
The numbers below are invented to show the shape of the curve, not to predict your cluster. Imagine a shard that grows by about five gigabytes per day, with a one-second refresh interval and default merge settings.
| Point in time | Approximate live data | Approximate segment count | Comment |
|---|---|---|---|
| After 10 minutes | A few hundred MB | Around 20 to 40 | Small tiers are active and merge frequently |
| After 1 day | 5 GB | Around 25 to 45 | Segments of a few hundred MB have formed |
| After 1 week | 35 GB | Around 35 to 55 | Several segments of a couple of GB, plus the small tiers |
| After 1 month | 150 GB | Around 60 to 80 | Many segments near the ceiling that are no longer merged together |
Notice that the count does not grow linearly with size. Big segments stop merging, so the number rises slowly. If you see counts that are several times higher than this shape for your data size, investigate whether merges are lagging.
The importance of the small end
Almost all merge activity in a steady state involves the smallest segments, since they are created constantly. This is why the refresh interval has such a large effect: it decides how fast the smallest tier fills. A change that reduces the number of tiny segments has a much larger impact on total merge work than any change to the top tiers.
What “healthy” looks like
- A modest number of segments, in line with the size of the shard.
- A share of deleted documents below the allowed percentage on most segments.
- Few running merges at any moment, and none of them running for hours without progress.
- No indexing throttle messages in the logs.
- Search latency that does not drift upward as the shard grows.
Write down the typical segment count, deleted share, and merge time for a representative shard in your cluster. When something changes, you will spot it against your own normal, which is more reliable than any general number.
13Force Merge: Merging by Hand
The force merge operation lets you ask Elasticsearch to compact an index right now. It is a powerful tool with a sharp edge, and it belongs to indices that no longer receive writes.
The force merge operation asks every shard of an index to merge its segments down to a target number that you choose, using the parameter max_num_segments. A value of one asks for a single segment per shard. A separate option, only_expunge_deletes, asks the shards to merge only the segments that carry a large share of deleted documents, controlled by the expunge setting from Chapter 10.
Why force merge exists
For an index that has stopped receiving data, further natural merging will never happen, because the policy only acts when there is pressure. Such an index may carry dozens of segments and some dead bytes for the rest of its life. A one-time force merge tidies it, gives it its best possible compression, and lightens every future search. This is the ideal use.
Think of a big spring cleaning of a house that you are about to leave alone for a year. You sort everything, pack it neatly, and close the boxes. It is a great idea for a house that will sit quietly. It is a poor idea for a house where people are still moving in and out every day, because they will immediately make a mess again, and your neat packing will get in their way.
The danger on an active index
If you force merge an index that is still being written to, two bad things happen. First, the merge produces a very large segment, far above the normal ceiling. Because of the half-ceiling rule from Chapter 9, such a giant segment is not eligible for normal merging unless it accumulates a large share of deleted documents. New writes and updates keep marking parts of it as deleted, and the policy cannot clean it cheaply. Second, the force merge itself uses a lot of I/O and CPU, which can disturb live traffic.
Only force merge indices that are read-only, or that will not receive writes anymore. The documentation says the same. If an index is still being written to, leave merging to the policy.
When to use it
- After a time-based index has rolled over and stopped receiving writes, typically as part of a warm phase.
- Before taking a long-term snapshot or before mounting an index as a searchable snapshot, so that fewer, larger files are stored.
- After a one-time bulk load into an index that will then be used mostly for reading.
- After changing the compression codec, to rewrite old segments with the new choice.
How to do it safely
Confirm that writes have stopped
Make the index read-only, or check that its rollover happened, so that no new documents arrive.
Check free disk space
A merge to one segment needs room for the new segment beside the old ones. Make sure that the node has comfortable free space and is far from disk watermarks.
Pick a quiet time
Force merges are heavy on disks. Run them during off-peak hours or on dedicated warm nodes that do not serve latency-sensitive searches.
Run one index at a time
Merging many large indices in parallel can saturate I/O. Queue them, or let lifecycle management pace them.
Watch progress
Follow merge statistics and tasks to see that merges are running and that disk space behaves as expected.
Verify the result
Check the segment counts and the size of the index, and compare search timing before and after.
flowchart TD
A["Should I force merge this index?"] --> B{"Is the index still receiving writes or updates?"}
B -->|Yes| C["No. Let the merge policy work, or tune the policy instead"]
B -->|No| D{"Is there plenty of free disk space?"}
D -->|No| E["Free space first, or merge in smaller steps"]
D -->|Yes| F{"Is it off-peak or on a warm tier?"}
F -->|No| G["Wait for a quiet time"]
F -->|Yes| H["Force merge with a sensible segment target"]
H --> I["Verify segment count, size, and search timing"]
Choosing the target
Merging to one segment gives the smallest overhead and the best compression, and it is a good target for an index that will never change. Some teams choose a slightly higher target when the shards are very large, to avoid a single enormous segment and to keep the merge less heavy. There is no universal right answer. Test on a representative index.
Force merge and deleted documents
A force merge also removes deleted documents, except for those kept as soft-delete history. For indices with a large share of dead data that will still receive writes, a lighter option is to ask for expunging deletes only. Even that should be used sparingly, because it rewrites every segment that crosses the threshold.
Force merge is not a fix for slow searches on a busy index
Operators sometimes reach for force merge when searches on an active index feel slow. That rarely helps for long and can make things worse. Look at queries, shard sizes, caches, and resources first. If segment count really is the issue, improve the policy or the refresh interval, so that the solution is lasting.
14Merging and the Lifecycle of Time-Based Data
Logs, metrics, and events arrive in time order and age gracefully. A lifecycle plan uses merging at the right moment: gently while data is fresh, and once, decisively, when data is old.
Many clusters store data that only grows and is rarely changed: application logs, security events, sensor readings. These are usually kept in a data stream or in a series of indices that roll over by size or by age. The newest index receives all the writes, and older ones are read-only. Elasticsearch’s index lifecycle management, or ILM, automates the moves between phases.
flowchart LR
A["Hot phase: index takes writes, natural merges only"] -->|Rollover| B["Warm phase: index is read-only"]
B --> C["Force merge to a low segment count, optional better compression"]
C --> D["Cold or frozen phase: cheaper storage, searchable snapshot"]
D --> E["Delete phase: whole index is removed"]
What happens in each phase
| Phase | Writes? | Merging behavior | Typical action |
|---|---|---|---|
| Hot | Yes, constantly | Natural merges by the tiered policy; tiny segments created continuously | Use a sensible refresh interval, fast storage, and default merge settings |
| Warm | No | No new segments; old ones stay as they are unless forced | Make read-only, force merge to a small segment count, optionally shrink and use stronger compression |
| Cold | No | Stable segments on cheaper hardware | Keep as is, or use a snapshot-backed form |
| Frozen | No | Segments read from a snapshot repository on demand | Merge before mounting so that fewer, larger files are fetched |
| Delete | No | Not applicable | Delete the whole index; no per-document cleanup is needed |
Think of a newspaper archive. Today’s paper is still being edited and is kept loose on the desk. Yesterday’s paper is finalized and filed into a folder. At the end of each month, the folders are bound into one volume with better paper, and old volumes move to a storage warehouse. In the end, volumes past the retention date are thrown away all at once. The binding step is the force merge, and it makes sense exactly because the pages will never change again.
Why the warm phase is the right moment
After rollover, the index no longer receives writes. Its segments can never become worse, so a compaction pays off for the rest of its life. Lifecycle management offers a force merge action for the warm phase, where you can set the target segment count and even switch to the higher-compression codec, so the merge rewrites data with better compression in the same pass.
Keep hot indices simple
Resist the urge to tune the hot phase heavily. Its natural merging is designed for exactly this workload. The main levers are the refresh interval, the shard size, and the hardware. Avoid force merging hot indices, as Chapter 13 explained.
Why deleting whole indices helps
Because deletion happens at the level of whole indices, none of the per-document cleanup burden appears. There are no deleted documents to merge away and no slow reclamation. This is one of the strongest reasons for time-based designs: they replace expensive document-level deletion with cheap file-level deletion.
Shrinking and merging
Some lifecycles also shrink an index, which reduces the number of primary shards, and this too requires a read-only index. Shrinking and force merging complement each other: fewer, larger shards with fewer segments are cheaper to keep and faster to search. The lifecycle order matters, so follow the documented order of actions for your version.
Lifecycle management runs its actions with limited concurrency, so many old indices do not all compact at once. If you replace it with hand-made scripts, add the same pacing yourself to protect your disks.
15Merges and Search Performance
Fewer, larger segments make searches cheaper. But the benefit has limits, and merging itself can disturb searches while it runs.
Why fewer segments help
A search does its work segment by segment. For each segment, it looks up terms in that segment’s dictionary, reads postings, applies filters, and collects results, and then it combines the partial results. The steps for one segment have a fixed cost, no matter how small the segment is. With a hundred small segments, the fixed costs repeat a hundred times. With ten larger ones, they repeat ten times.
Other benefits of larger segments
- Better compression. Larger segments compress data better, so the same information takes fewer bytes to read from disk.
- More cache-friendly filters. The node query cache only considers segments that are big enough, above a minimum number of documents and a minimum share of the shard. Tiny segments do not qualify.
- Cheaper aggregations. Some structures used for grouping are built per segment, and fewer segments mean less repeated setup.
- Fewer open files. Less pressure on the operating system’s file handling.
| Situation | Effect on search | What to do |
|---|---|---|
| Very many tiny segments | Noticeable overhead per search, especially for cheap queries | Lengthen the refresh interval, check that merges are keeping up |
| A moderate number of mixed-size segments | Normal, healthy | Nothing |
| A few large segments on a read-only index | Best possible efficiency for reads | Consider a one-time force merge |
| Large segments with many deleted documents | Searches skip dead documents but still read the bytes | Lower the allowed deleted share, or reindex if the workload is update-heavy |
| A big merge just finished | Some cached data was replaced, so a brief slowdown is possible | Expect a short warm-up period |
Looking for a paper in a filing room is faster when it is organized into a few big cabinets than when it is scattered across a hundred small drawers, even if the total number of papers is the same. Every drawer you open costs a few seconds. The merge policy is the staff member who moves papers from many small drawers into a few big cabinets while you work.
The cost of merging to searches
Merges use disks and processors, so they take resources away from searches. A large merge reads and writes gigabytes, and this can add latency to searches that need to read from disk. New segments also start cold, meaning their data is not yet in the operating system’s file cache. The automatic throttle limits how hard merges push, so that searches stay responsive, and this is why it is best left on.
Diminishing returns
Going from two hundred segments to twenty gives a large improvement. Going from twenty to one gives a smaller one for most queries, and on an active index it is not sustainable. Measure before you invest effort in reducing segment counts further. On busy indices, the cost of rewriting data often outweighs the last few percent of search speed.
Effect on aggregations and sorting
Some grouping operations use structures called global ordinals, which map values from all segments into a single numbering. These are rebuilt whenever segments change, at refresh time. With frequent refreshes and many segments, rebuilding can be a noticeable cost for large grouping fields. A longer refresh interval, and fewer segments, both reduce this cost.
Vector fields
Indices that store dense vectors for similarity search keep a graph structure inside each segment. Merging these structures is more expensive than merging plain text data, because the graphs need to be combined. On such indices, merges take longer and use more CPU, so it is even more valuable to avoid creating many tiny segments and to watch merge times closely.
Benchmark your real queries on a shard before and after a change in segment count. The gain depends on the mix of queries, the size of the data, and the caches, and only your own test gives a trustworthy answer.
16Merges and Indexing Performance
Every document you write is copied several times by merges before it reaches its final home. Understanding this hidden cost is the key to fast, steady indexing.
The hidden second write
When you measure disk writes on a node that indexes data, you will notice that the disk writes far more bytes than your clients send. The extra writing comes from merges. As Chapter 8 explained, each document is rewritten roughly once per tier. So if a client sends one gigabyte of documents, the disk may see several gigabytes of writes, depending on tiers, replicas, and the translog. This multiplier is called write amplification, and it is the main reason why indexing speed depends so much on disk speed.
Consider a warehouse that receives goods in small boxes. Every so often, workers repack ten small boxes into one bigger box, then ten bigger boxes into a pallet, then several pallets into a container. The goods arrive once, but they are handled four or five times. Fast trucks at the door do not help if the repacking crew is the bottleneck.
Levers that reduce merge pressure
Lengthen the refresh interval
Fewer, larger initial segments mean fewer merges at the small end. Ten to thirty seconds is common for analytics and logging.
Give the indexing buffer room
The node-level indexing buffer defaults to ten percent of the heap. On heavily indexing nodes, a bigger buffer produces larger segments per flush.
Use fast storage
Solid-state drives handle the mixed read and write pattern of merges well and raise the speed at which merges can keep up.
Avoid too many busy shards per disk
Each shard runs its own merges. Many active shards on one disk compete for I/O, and merges fall behind.
A bulk load recipe
Loading a large amount of data into a new index is the situation where merge tuning pays off most. A common sequence follows.
Prepare the index
Create it with the mapping you want. Set the number of replicas to zero for the duration of the load, and lengthen the refresh interval, or turn scheduled refresh off if you do not need to search during the load.
Load with sensible bulk requests
Send batches of moderate size from several parallel workers, and watch for rejections and throttle messages. Slow down if they appear.
Let the merges settle
After the last batch, allow the natural merges to catch up. Watch the number of running merges and segment count fall.
Restore normal settings
Set the refresh interval back to its normal value, and add replicas. The replicas copy segment files from the primary, which is faster than re-indexing every document.
Consider a force merge
If the index will now be mostly read-only, a one-time force merge produces a tidy result. If it will keep receiving writes, skip this step.
Update and delete workloads
Workloads with many updates create dead documents as fast as they create new ones. The tiered policy handles this by tolerating up to the allowed percentage and cleaning beyond it. If such an index causes heavy background merging, consider these approaches: reduce how often documents are rewritten by batching changes, use partial updates that do not touch large fields when possible, keep segments smaller with a lower maximum merged size so that cleaning does not rewrite giants, and check that a document really needs to be updated rather than appended as a new event.
Watch for signs of trouble
- Bulk requests start to be rejected or slow down while merges are at their thread limit.
- The log reports that indexing is being throttled.
- Disk write rates stay at their ceiling even when the incoming rate drops.
- Segment counts rise during the load and do not fall afterward.
Loading recipes change safety settings such as replicas and refresh interval. Write down what you changed and restore it when you are done. An index left with no replicas and no refresh is a fragile and confusing surprise for the next person.
17Merges, Disk Space, I/O, and CPU
A merge needs room to breathe. Planning for temporary space, disk speed, and processor time keeps merges from causing trouble elsewhere.
Temporary disk space
Because a merge writes the new segment before deleting the old ones, the disk holds both at the same time. The peak extra space is roughly the size of the merged output. A merge of ten segments of five hundred megabytes each needs several gigabytes of extra room. A force merge of a whole shard to a single segment needs, at the worst moment, about as much free space as the shard itself. Several merges running in parallel add up.
| Moment | Disk use for one shard of 40 GB | Comment |
|---|---|---|
| Before a full force merge | 40 GB | Many segments, some dead bytes |
| During the merge | Up to about 80 GB | Old segments and the new merged segment exist together |
| Just after the switch | Still up to about 80 GB | Old segments stay until running searches release them |
| After cleanup | About 36 GB, for example | Dead bytes are gone and the compression is better |
Think of reorganizing a bookshelf by moving all the books to a new shelf in a new order. You need a second empty shelf for the new arrangement while the old one still holds the books. Only when everything is moved and checked do you clear the old shelf. If the room has no space for a second shelf, the reorganization simply cannot start.
Disk watermarks
Elasticsearch protects nodes from running out of disk with three levels called watermarks. At the low watermark, new shards are no longer allocated to the node. At the high watermark, shards are moved away. At the flood stage, indices on the node become read-only. Merges can push a node across these lines by creating temporary space use. Keep enough headroom that a heavy merge cannot trigger them. Leaving a healthy share of every data disk free is a good habit for this reason alone.
Disk speed
Merges read and write large amounts of data in long streams. They benefit from disks with high sustained throughput. In cloud environments, disks may have a burst allowance, which is fast for a while and then falls to a lower baseline. A steady merge workload can use up the burst credits, after which everything slows down, including searches. Choose storage whose baseline speed matches your steady merge load, not just its peak.
CPU and memory
- CPU. Merges compress, decompress, and rebuild structures. On heavy indexing nodes, merge threads may use a large share of the processors.
- Memory. Merges mostly use the operating system’s file cache rather than the Java heap. A large merge may push some useful data out of the cache, which briefly slows searches.
- Heap. Merges use a moderate amount of heap for buffers. Extremely wide indices with many fields can increase this.
File handles
Each segment is several files, and every open segment holds file handles. Elasticsearch packs segments that are small relative to the shard into compound files, which bundle several files into one, to reduce the number of handles. Still, a shard with thousands of segments can run into the operating system’s limits. Keeping segment counts reasonable, and configuring the file descriptor limit as the installation guide recommends, avoids this class of problems.
Planning capacity
As a planning rule, plan for the live data size, plus the deleted share you tolerate, plus the working room for merges and force merges, plus a margin under the watermarks. For a workload with frequent updates or planned force merges, this margin needs to be larger than for pure append-only logs.
Alert on free disk space at a level well above the watermarks, so that you have time to react before a merge turns an ordinary evening into an incident.
18Merges, Replicas, Recovery, and Snapshots
Every copy of a shard merges on its own. That simple fact explains surprising differences between replicas, the size of snapshots, and the speed of recovery.
Each shard copy merges independently
Elasticsearch replicates documents to replica shards, not segment files. A replica receives the same writes as the primary and builds its own segments. Because the timing of refreshes and merges differs slightly, the primary and its replicas contain the same live documents but usually have different segment layouts. A segment count of 42 on the primary and 38 on a replica is normal.
Two branches of a library receive the same list of new books every day, and each branch shelves and repacks them by its own schedule. At the end of the week, both have all the same books, but their shelves look different. Neither is wrong.
Consequences for caches
Caches that depend on segments, such as the node query cache, are per shard copy. A request served by a replica may find a cold cache even if the primary’s cache is warm. This is one reason why steering related requests to the same shard copies improves cache hit rates.
Peer recovery copies files
When a new replica is created or a lost one is rebuilt, Elasticsearch may copy segment files from the primary, followed by the recent operations from the translog. In that case, the new replica starts with the same segment layout as the primary at that moment, and afterward, they drift apart again. If history is kept long enough through retention leases, a returning replica can catch up by replaying operations instead of copying files, which is much faster.
Snapshots and segment churn
Snapshots to a repository are incremental at the segment file level. The first snapshot uploads all segment files. Later snapshots upload only files that did not exist in the earlier ones. Because segments are immutable, a file that survives untouched is not uploaded again. But a merge creates brand-new files. So an index with heavy merging produces a stream of new files that every snapshot must upload, while an index whose big segments stay untouched produces small incremental snapshots.
| Index behavior | Effect on snapshot size and time |
|---|---|
| Append-only, large segments stable | Small incremental snapshots |
| Heavy updates and cleaning merges | Many new files each time, larger incremental snapshots |
| Force merge just before a snapshot | One large upload of the new files, then little afterward if nothing changes |
| Force merge just after a snapshot | The old files stay in the repository until old snapshots are deleted, and new files must be uploaded next time |
Order of operations for long-term storage
For data that you plan to keep for a long time, the sensible order is: stop writes, force merge, then take the snapshot, or mount it as a searchable snapshot. That way the repository stores the final, compact form once, instead of several intermediate forms.
Cross-cluster replication
A follower index in another cluster receives operations and builds its own segments, which merge on the follower’s own schedule. The merge behavior of the leader and follower are independent, and settings on one do not apply to the other automatically.
Restores and merges
A restored index arrives with the segments that were snapshotted. It does not need an immediate merge unless it will receive writes again. If it does, natural merging works from the restored segments, and huge restored segments follow the same half-ceiling rule as any others.
Do not compare segment counts between primary and replica as a sign of trouble. Compare each copy with its own history and with the allowed count for its size.
19Advantages, Disadvantages, and Trade-offs
Merging is a bargain: you spend disk and processor time now to save search time and space later. Here is an honest scorecard so you can decide how much to spend.
Advantages
- Keeps the number of segments small, so searches waste less time on fixed overhead.
- Reclaims the space held by deleted and updated documents.
- Improves compression, so indices take less disk and less cache.
- Runs automatically in the background with no action from operators.
- Never disturbs running searches, because old segments stay until searches finish.
- Is safe against crashes: an interrupted merge leaves the old segments intact.
- Adapts its speed to the backlog through automatic throttling.
- Offers a tidy one-time compaction for read-only data through force merge.
Disadvantages
- Rewrites every document several times, which multiplies disk writes.
- Competes with searches and indexing for disk, processor, and cache.
- Needs temporary free space, and heavy merges can push nodes toward disk watermarks.
- Can lag behind under heavy writes, leading to throttled indexing.
- Leaves dead bytes on disk for a while, so disk use exceeds live data.
- Creates new files that snapshots must upload again.
- Is hard to tune well, and wrong tuning can make things worse.
- Offers less benefit on the biggest segments, which stop merging at the ceiling.
The central trade-off: write cost against read cost
Merging more eagerly gives fewer segments and faster reads, but every extra merge rewrites data and burns disk and CPU. Merging less eagerly saves that effort but leaves more segments to search. The default settings sit at a point that suits mixed workloads. Write-heavy systems slide toward less merging, and read-heavy systems toward more.
The second trade-off: freshness against efficiency
A short refresh interval gives near-instant visibility of new data but creates many tiny segments and much merging. A long interval gives less merging and higher indexing efficiency but delays visibility. The right value is a business decision about how fresh the data must be.
The third trade-off: space against effort
Tolerating more deleted documents saves rewriting effort but wastes disk. Being strict keeps disks lean but costs more merging of big segments. Cheap, plentiful disks favor tolerance. Tight or expensive storage favors strictness.
The fourth trade-off: many small segments against one giant one
A single giant segment is the most efficient to search, but it cannot be changed cheaply. Any deleted documents inside it stay until it is rewritten in full. A moderate number of medium segments is easier to maintain. This is why the ceiling exists and why the force merge is best kept for read-only data.
A household can keep the closet in perfect order by re-folding everything every evening, or it can tidy once a week. The daily routine gives a beautiful closet and costs an hour a day. The weekly routine costs less time and allows a little mess. Neither is wrong, and the right choice depends on how much the household values order and how much free time it has.
When merge tuning is the wrong tool
If your searches are slow because of complex queries, bad mappings, oversized results, or too few resources, merge tuning will not help much. If your cluster is unstable because of too many shards, more merging makes it worse. Fix the design first, and tune merging last.
20A Tuning Guide: Which Knob for Which Problem
Start from the symptom, not from the setting. This chapter maps common problems to the least risky fix.
flowchart TD
A["Symptom observed"] --> B{"Indexing slow or throttled?"}
B -->|Yes| C["Lengthen refresh interval, check disk speed, reduce busy shards per disk"]
B -->|No| D{"Searches slow with very many segments?"}
D -->|Yes| E["Check that merges keep up, then consider a lower segments per tier"]
D -->|No| F{"Disk larger than live data suggests?"}
F -->|Yes| G["Check deleted share, consider a lower deletes percent allowed or a lower max merged segment"]
F -->|No| H{"Old read-only index still heavy?"}
H -->|Yes| I["Plan a one-time force merge in the warm phase"]
H -->|No| J["Merging is probably not the problem: look at queries, mappings, and resources"]
Recommendations by workload
| Workload | Typical pain | First things to try |
|---|---|---|
| High-volume logging or metrics, append-only | Merges compete with heavy writes | Longer refresh interval, fast storage, defaults for merge settings, lifecycle with force merge in the warm phase |
| Product catalog with frequent updates | Many deleted documents, disk larger than expected | Reduce needless updates, lower the deleted share allowed, consider a lower maximum merged segment |
| Read-mostly reference data | Segments are more numerous than needed | One-time force merge after loading, a lower segments per tier if needed |
| Large one-time migration | Load is slow and merges lag | No replicas and long refresh during the load, restore afterward |
| Vector similarity search | Merges are slow and CPU-heavy | Fewer, larger initial segments, monitor merge time, give merges CPU headroom |
| Many small indices | Too many shards, each merging on its own | Consolidate into fewer indices and shards before tuning merges |
A car mechanic does not start by swapping parts. They listen to the symptom, check the simple things first, and change one component at a time. If the engine coughs, they check the fuel and the spark plugs before opening the gearbox. Merge tuning should follow the same order: first the refresh interval and hardware, then the policy settings, and last of all the expert options.
A safe experiment method
Choose a representative index
Pick one that has the same mapping, load, and hardware as the index you worry about, and preferably not a production-critical one.
Record the baseline
Capture merge statistics, segment counts, deleted share, indexing rate, and search timing under a normal load.
Change one setting
Apply a single change through the index settings. Keep the previous value written down.
Run a full business cycle
Merging effects show up over hours or days, not seconds. Wait long enough to see steady-state behavior.
Compare and decide
Compare the same measures with the baseline. Keep the change only if the gain is clear and the cost is acceptable.
Roll out through templates
If it works, place the setting in an index template and document the reason and the measured gain.
Forum posts and blog articles often give merge settings that worked for someone else’s hardware and workload, sometimes for an old version. Numbers copied without understanding can make a healthy cluster worse.
21Design Patterns for Healthy Merging
Good merging behavior is mostly the result of good design choices upstream. These seven habits keep merge work small and predictable.
Choose the refresh interval on purpose
Decide how fresh the data must be, and set the longest interval that meets the need. Do not leave one second everywhere by habit.
Time-based indices with lifecycle rules
Roll over by size or age, make old indices read-only, and compact them once. Delete whole indices at end of life.
Force merge only read-only data
Reserve manual and lifecycle force merges for indices that have stopped receiving writes.
Separate hot and warm hardware
Give the writing tier fast storage and spare CPU for merges, and let the warm tier run the heavy one-time compactions away from live traffic.
Append, do not update, when you can
Model changing data as new events or versions when the design allows it. Fewer updates mean fewer deleted documents and less cleaning.
Right-size shards
Use fewer, larger shards in a sensible range, instead of thousands of tiny ones. Each shard merges on its own, so fewer shards means less parallel merge competition.
Headroom and baselines
Keep free disk space above the watermarks by a wide margin, and record baselines of segment counts and merge times for comparison.
Pattern 2 in action
A platform team stores application logs in a data stream. Each backing index rolls over at fifty gigabytes per shard or one day, whichever comes first. The hot phase uses a ten-second refresh interval and default merge settings. After rollover, the index moves to warm nodes, is made read-only, and is force merged to one segment per shard, with stronger compression. After thirty days, the whole index is deleted. The team has not touched a single merge policy setting in two years, and the disks are lean.
Pattern 5 in action
A product team originally updated a stock counter inside a large product document every time an item sold. That produced thousands of rewrites per hour and a high share of deleted documents in large segments. They moved the counter to a small separate document and reduced the update rate by batching. The deleted share dropped, background merging calmed down, and the team reduced disk headroom accordingly.
A pattern for documentation
Keep a one-page description of your merge-related choices: refresh intervals per index family, lifecycle rules, any non-default merge settings with the reason and the evidence, and the baseline numbers. When somebody joins the team or a cluster is rebuilt, this page prevents the loss of hard-earned knowledge.
The best merge settings are the ones you never had to change. If defaults work, celebrate and move on. Put your effort into design decisions that make merging lighter instead of into clever numbers.
22Anti-Patterns and Common Mistakes
These are the traps behind most merge-related incidents. Each is common and easy to avoid once you know it.
What people do
They run a force merge to one segment on an index that is still receiving writes and updates.
Why it hurts
The result is a giant segment that the policy will not merge again cheaply, so dead bytes accumulate in it. The merge itself also burdens live traffic.
Better approach
Force merge only after writes have stopped, and leave active indices to the policy.
What people do
They set the segments per tier to a very low number on a write-heavy index to “keep the segment count tiny.”
Why it hurts
The policy now merges constantly and rewrites data many more times. Disk writes climb, merges lag, and indexing is throttled.
Better approach
Keep the defaults on write-heavy indices, and compact them later when they become read-only.
What people do
They raise the number of merge threads on a node whose disks are already saturated.
Why it hurts
More parallel merges fight for the same disk, so each runs slower. Searches and indexing suffer, and the backlog does not shrink.
Better approach
Reduce the incoming pressure, improve storage, or spread shards over more nodes first. Add threads only when spare capacity exists.
What people do
They ignore log messages about throttled indexing because “the cluster still works.”
Why it hurts
Throttling means merges cannot keep up. Writes are being slowed, and the next spike may cause rejections and lost data in upstream buffers.
Better approach
Treat throttle messages as an early warning. Investigate the refresh interval, storage speed, and shard layout.
What people do
They schedule a nightly force merge job over every index in the cluster.
Why it hurts
Active indices get giant segments, disks run near their limits, and old indices are rewritten again and again for no gain. Snapshots grow because new files appear each night.
Better approach
Compact each index once, at the right moment in its lifecycle, using lifecycle management.
What people do
They keep a one-second refresh interval on logging indices that nobody needs to see in real time.
Why it hurts
A new tiny segment is created every second on every shard, which multiplies merge work for no business benefit.
Better approach
Choose an interval that matches how fresh the data must be, often ten seconds or more for logs.
What people do
They run disks at ninety percent full and then start a large merge or force merge.
Why it hurts
The temporary space pushes the node over disk watermarks. Shards are moved, indices become read-only, or a merge fails for lack of space.
Better approach
Keep a generous free margin and check space before any heavy operation.
Other frequent mistakes
- Changing several merge settings at once and losing track of what worked.
- Expecting a single segment per shard on an active index.
- Comparing segment counts between primary and replica as if they must match.
- Copying merge settings from an old article written for a different version.
- Creating thousands of tiny indices, each of which merges on its own.
- Forgetting that a template only affects new indices and leaving old ones with old settings.
23Security and Compliance Considerations
Merging seems like a pure performance topic, but it touches security in two ways: who is allowed to trigger heavy operations, and when deleted data physically disappears.
Deleted data is not immediately gone
When a document is deleted or replaced, its old bytes remain in a segment until a merge rewrites that segment. If a privacy rule says that personal data must be erased on request, marking a document as deleted does not physically remove it at once. In addition, some deleted documents are kept as soft-delete history for a retention period, and copies of the data may exist in snapshots and on replicas until their own cycles complete.
| Place where deleted data may still exist | How long | How it is removed |
|---|---|---|
| Old segment on the shard | Until a merge rewrites the segment | Natural merging, or a targeted force merge for read-only indices |
| Soft-delete history | For the retention period, twelve hours by default | Expires automatically, then merges remove it |
| Replica copies | Until their own merges run | Independent merging on each copy |
| Snapshots in repositories | Until every snapshot containing the data is deleted | Snapshot retention policies |
| Backups outside Elasticsearch | Depends on your backup process | Backup retention rules |
Shredding a confidential letter is not the same as putting it in the recycling bin. The bin removes it from your desk, but the letter is still readable until the truck arrives and it is pulped. Deleting a document is the bin, and merging is the pulping. Copies in other rooms, such as archived snapshots, need their own shredding.
Design for erasure
If you must be able to erase data reliably and quickly, design for it. Separate data by tenant or by time so that whole indices can be deleted. Keep snapshot retention short enough for your obligations. For the rare case of deleting a single record from an active index, understand that removal from disk follows merging, and involve your compliance team in deciding what is acceptable.
Who may trigger heavy operations
Force merge and settings changes are administrative operations, and they require specific privileges on the index. A careless or malicious force merge on a big active index can consume disk and I/O and harm the cluster. Give these privileges to a small group of trusted operators and to lifecycle management, and audit their use. The same applies to changes of merge policy settings, which could deliberately or accidentally degrade performance.
Protecting the files
Segments are files on disk and contain your data in a searchable form, including deleted documents that have not yet been merged away. Protect them with disk or volume encryption and strict file permissions. Merges create new files with the same protections as the rest of the data directory, so no special configuration is needed, but the whole directory must be secured.
Resource abuse and availability
Availability is part of security. Uncontrolled merging can exhaust disk space, and disks that are full make nodes stop accepting writes. Alerts on disk space, limits on who can run heavy operations, and lifecycle policies that pace compaction all protect the cluster from accidents and abuse.
If your organization follows regulations that give people the right to have their data erased, confirm with your security and legal teams how deletion, merging, replicas, and snapshots together meet your obligations. A deletion request that only marks documents is not the whole story.
24Monitoring, Logging, and Metrics
A merge policy that works is invisible. A few numbers tell you when it stops working, usually long before users notice.
Where to look
| Question | Where to look | What healthy looks like |
|---|---|---|
| How many segments does a shard have, and how big are they? | The segments listing per index or shard | A moderate count with a spread of sizes, roughly ten per active tier |
| How much dead data is there? | The count of deleted documents compared with live documents in the index listing | Deleted share at or below the allowed percentage on most indices |
| Are merges running, and how heavy are they? | Merge statistics: current merges, current documents and size, total time | A few short merges at any time, none stuck for hours |
| Is indexing being throttled? | Indexing statistics for throttle time, and log lines about throttling | Zero or very little throttle time |
| Are merges slowing down over time? | Total merge time divided by total merged size, tracked as a trend | Stable or improving |
| Is the disk under pressure? | Free space, disk throughput, and I/O wait on data nodes | Comfortable free space and no sustained saturation |
| Is a force merge running? | The task listing filtered for force merge actions | Only when you started it or lifecycle management did |
Important log lines
| Log message idea | Meaning |
|---|---|
| Now throttling indexing, with the number of merges in flight and the maximum | Merges have fallen behind, and indexing on that shard is being slowed |
| Stop throttling indexing | The backlog has cleared |
| Merge failed, or an exception during a merge | A merge could not complete, for example because of disk problems. Read the cause carefully. |
| No space left on device | The disk is full. Merges and other writes cannot proceed. |
| Disk watermark exceeded | A node crossed a disk threshold, which may be partly due to temporary merge space |
The oil light and the temperature gauge in a car say little on most days, and that is the point. You glance at them now and then, and you respond when the needle moves. Merge statistics are the gauges of the indexing engine: quiet when the engine is happy, informative when it strains.
Metrics worth charting
- Segment count per shard, on average and at the maximum. Rising trends over days deserve a look.
- Deleted document share per index. Useful for update-heavy indices.
- Running merges and merge time. Show the effort behind the scenes.
- Merged bytes per hour. A direct measure of write amplification when compared with incoming bytes.
- Indexing throttle time. The clearest sign that merges cannot keep up.
- Disk free space and I/O wait. The resources merges depend on.
- Search latency percentiles. The customer-facing effect of everything above.
Alerts that help
Create a short list of alerts. First, an alert on indexing throttling lasting longer than a few minutes. Second, an alert when average segment count per shard rises far above its baseline. Third, an alert on the deleted document share for indices where you expect it to be low. Fourth, an alert when free disk space drops below a margin above the watermarks. Fifth, an alert when a merge or force merge has been running for an unusually long time. Each alert should link to a runbook.
Comparing before and after
When you change anything about merging, capture the same set of numbers before and after: segment counts, merged bytes per hour, throttle time, deleted share, indexing rate, and search latency. A change that improves one number and worsens others may not be a real improvement.
Merge numbers fluctuate constantly, because merges start and end all the time. A single reading means little. A chart over days shows the true pattern and makes real changes obvious.
25Failure Scenarios and Recovery
Merging is designed to be safe, so most failures come from the environment around it: disks, limits, and load. Each has a calm recovery.
flowchart TD
A["Merge-related trouble"] --> B{"Errors about disk space?"}
B -->|Yes| C["Free space, move shards, add capacity, then retry"]
B -->|No| D{"Indexing throttled or merges lagging?"}
D -->|Yes| E["Reduce write pressure, lengthen refresh interval, check disk speed"]
D -->|No| F{"Too many open files or huge segment counts?"}
F -->|Yes| G["Fix file limits, find why merges did not keep up"]
F -->|No| H{"Corruption or checksum errors in logs?"}
H -->|Yes| I["Let the shard recover from a healthy replica, investigate hardware"]
H -->|No| J["Compare with baseline and look at queries, mappings, and resources"]
Scenario: the disk fills up during a merge
A big merge or force merge needs temporary space. If the disk runs out, the merge fails with a “no space left” error, and the shard may fail as well. Elasticsearch discards the incomplete new segment, and the old segments remain intact, so no committed data is lost. Recovery is to free space, for example by deleting old indices, moving shards to other nodes, or adding capacity, and then allow the shard to recover. Afterward, review your free space margin and the size of merges you run.
Scenario: merges lag and indexing is throttled
Under heavy write load, merges may not keep up. The scheduler throttles indexing to protect the shard. Recovery means reducing the pressure: lengthen the refresh interval, slow the sources, spread shards across more nodes, or move to faster storage. Once merges catch up, the throttle lifts by itself. If it happens often, treat it as a capacity or design problem, not as an incident.
Scenario: too many open files
If a shard accumulates thousands of segments, the process may run into the operating system’s limit for open files. Errors mention “too many open files.” Recovery is to make sure that the file descriptor limit is configured as the documentation recommends, and to find out why merges did not keep up, since a healthy shard should never have such a high count.
Scenario: a node crashes during a merge
Because merges write new files and switch them in at the end, a crash in the middle leaves the old segments valid. On restart, Elasticsearch removes incomplete files and recovers from the last commit and the translog. No special action is needed.
Scenario: a force merge is interrupted
The force merge request may run for a long time. If the client disconnects, the merge normally continues in the background. If the node restarts, the merge is cancelled, and the index remains in its previous valid state. You can start it again later. Running it with the option that returns a task lets you track and, if needed, cancel it.
Scenario: corruption found during a merge
Merging reads whole segments and checks their checksums. If a segment on disk is damaged, the merge notices, and the shard is marked as failed. The cluster then rebuilds that shard copy from a healthy copy on another node. This is a good reason to keep at least one replica of important indices, and to investigate the hardware that produced the corruption.
When a moving crew packs a new box and the truck breaks down halfway, the old boxes are still in the old house, untouched. Nothing is lost, and the crew starts again. If the crew discovers that one old box was already damaged, they get a spare copy from the second house. Merging follows the same careful habits: write the new box first, keep the old ones until the end, and check everything while packing.
Scenario: burst credits run out
On cloud storage that has burst allowances, a long merge or a big force merge can use up the credits. After that, the disk slows to its baseline, and merges, searches, and indexing all suffer. Symptoms are a sudden drop in throughput without any change in load. Recovery is to reduce merge activity, wait for credits to return, or move to storage with a higher baseline.
Habits that make recovery easier
- At least one replica for indices that matter.
- Regular snapshots that you have practiced restoring.
- Alerts on disk space and throttle time.
- A runbook for disk full, merge lag, and file limit errors.
- A rule that heavy operations wait until free space and load are checked.
Never remove or edit files in a shard’s data directory yourself. The shard tracks its files precisely, and manual changes can turn a small problem into permanent data loss. Use the supported operations and let recovery do its work.
26Troubleshooting Common Merge Problems
When something looks wrong, match the symptom to its likely meaning. This table covers the situations people meet most often.
| What you see | Most likely meaning | First things to check |
|---|---|---|
| Log says indexing is being throttled | Merges cannot keep up with incoming segments | Refresh interval, disk speed, number of busy shards per disk, bulk pressure |
| Segment count keeps growing over days | Merges are lagging, or the count is normal for a growing shard | Compare with the allowed count for the shard size, and check merge thread limits and I/O |
| Disk usage far higher than live data | Many deleted documents, soft-delete history, or temporary merge space | Deleted share, update rate, ongoing merges, retention lease period |
| Deleted documents do not disappear after a force merge | They may be soft-delete history that has not expired | Wait for the retention period, and check the index settings for history retention |
| Searches slower after a big merge | The file cache is cold for the new segment | Wait for warm-up, and avoid running big merges at peak |
| Searches slow with hundreds of tiny segments | Per-segment overhead dominates | Lengthen refresh interval, verify merges run, consider consolidating tiny shards |
| A node crossed a disk watermark during a merge | Temporary space from the merge | Free space, reduce parallel merges, keep a larger margin |
| Force merge seems to run forever | A large index on slow storage, or several indices merging at once | Check task progress and disk throughput, run fewer indices at a time |
| One replica has very different segment counts | Independent merging on each copy | Usually nothing. Compare with its own baseline. |
| Snapshots grow larger than expected | Merges create new files that must be uploaded | Merge history of the index, force merge timing, snapshot schedule |
| Too many open files errors | Very high segment counts or low file limits | File descriptor limits and why merges lag |
A calm way to debug
Name the symptom
Is it slow indexing, slow searching, high disk use, or errors? Different symptoms lead to different parts of this guide.
Look at merge statistics
Check the running merges, total merge time, and throttle time for the affected index and node.
List the segments of a busy shard
Look at counts, sizes, and deleted documents. Compare them with the shape described in Chapter 8.
Check the environment
Disk space, disk speed, CPU, and file limits. Many merge problems are really resource problems.
Change one thing
Adjust one setting or one input, wait through a full cycle, and measure again.
Record the finding
Write down the symptom and the fix so that the next incident is solved in minutes.
On a test index, index a batch of documents with a one-second refresh, list the segments, then wait a while and list them again. Watching small segments appear and disappear teaches the whole policy in a few minutes.
27Real-World Scenarios
Here are four common situations, with rough numbers, showing merge policy at work. The companies are imaginary, but the patterns are the ones teams meet every day.
Scenario 1: The logging cluster that could not keep up
The imaginary company LogLantern indexes application logs on hot nodes. At peak, the logs show “now throttling indexing” every few minutes. Every index uses the default one-second refresh interval. The team raises the interval to fifteen seconds for log indices, since nobody watches them in real time. The number of tiny segments falls by more than ninety percent, merged bytes per hour drop by about half, and the throttle messages disappear. They did not touch a single merge policy setting.
Scenario 2: The catalog with a fat disk
The imaginary retailer CartCrest stores its catalog in an index of forty gigabytes of live data, updated heavily during the day. The disk shows sixty gigabytes used, and about a third of documents in the large segments are deleted. The team reduces needless updates by batching stock changes and moves a frequently changing counter to a separate small document. They also lower the maximum merged segment size, so cleaning rewrites mid-sized segments instead of giants. Disk use falls to about forty-five gigabytes, and they reduce their capacity margin.
Scenario 3: The force merge that backfired
At the imaginary firm ArchiveArc, an engineer runs a force merge to one segment on an index that is still receiving updates, hoping to speed up searches. Each shard ends up with a segment of sixty gigabytes. Over the following weeks, updates mark large parts of it as deleted, but the policy cannot cheaply merge it, so it stays bloated with dead data. The team eventually reindexes into a fresh index with normal settings and adds a lifecycle rule that only force merges after rollover.
Scenario 4: The warm phase that paid for itself
The imaginary company MetricMint keeps thirty days of metrics. Its lifecycle policy rolls indices over daily, moves them to warm nodes, makes them read-only, and force merges each shard to one segment with stronger compression. Warm indices shrink by roughly a third compared with their hot form. Dashboards over the last month become noticeably faster because each index has far fewer segments. The team has never run a manual force merge.
A worked example with numbers
Set the scene
A shard receives about 20 MB of data per second, which is roughly 72 GB per hour. The default merge settings apply, and the refresh interval is one second.
The one-second case
Each refresh creates a segment of about 20 MB. These climb tiers of about 20 MB, 200 MB, and 2 GB before reaching the large end. Each byte is rewritten roughly three times, so the shard merges about 216 GB per hour, on top of the 72 GB of first writes.
The thirty-second case
Each refresh creates a segment of about 600 MB, which skips the first tiers. Each byte is rewritten roughly one and a half times, so the shard merges about 108 GB per hour. The number of new segments per hour drops from 3,600 to 120.
The cost of the change
New documents become searchable after up to thirty seconds instead of one. For logs that nobody reads live, this is invisible to users.
The result
Merge I/O is cut in half, throttle risk falls, and searches over the shard visit fewer segments. The figures are approximations to show the shape of the effect, and real numbers depend on your data and settings.
28Frequently Asked Questions
29Summary and Key Takeaways
A merge policy is a simple idea with a big effect: combine small immutable pieces into fewer big ones, at a pace the hardware can sustain. Here is everything to remember.
Key Takeaways
- What it is: the rule set that decides which segments of a shard are merged and when, with the tiered merge policy as the default and the concurrent merge scheduler running the merges.
- Why it exists: segments never change, so new data creates new segments and deletes only mark documents as dead, and merging is how the count and the waste come back down.
- How the tiered policy thinks: it groups segments into size tiers about ten times apart, merges a tier when it holds more than about ten segments, and stops combining near a five gigabyte ceiling.
- What it costs: every document is rewritten several times, merges need temporary disk space, and they compete with searches and indexing for I/O and CPU.
- How to reduce the load: lengthen the refresh interval, use fast storage, keep shard counts sensible, and avoid needless updates.
- How to use force merge: only on read-only indices, once, with free disk space and off-peak timing, ideally through lifecycle management after rollover.
- How to watch it: chart segment counts, deleted share, merge time, throttle time, and free disk space, and change one setting at a time.
Keep in mind that setting names, defaults, and available policies can change between Elasticsearch versions, so confirm exact details against the documentation of the release you run. With that habit, and the ideas in this guide, you can keep your indices tidy, your disks lean, and your searches quick without ever making merging a daily worry.