How Lucene Merges Segments While You Keep Searching
Follow one delete through a Lucene 10.6.0 segment merge. How TieredMergePolicy picks the inputs, how doc IDs get remapped, how a delete that lands mid-merge still reaches the output, and why disk usage rises before it falls.
Part 3 of the Lucene internals series. Part 1 follows documents into immutable segments. Part 2 follows a query across those segments.
Part 2 left the two-million-review index sitting in twelve segments, with quick OR dog visiting every one of them. This part is about where those twelve came from and what happens when Lucene turns some of them into one.
Here is the awkward moment. A merge has been running for four seconds. It has already copied review 103 into the new segment. Now a delete for review 103 arrives. Seconds later the merge finishes and the new segment goes live. Does review 103 come back?
It does not, and the reason is not luck. Lucene snapshots which documents were live when the merge started, keeps a map from every input doc ID to its slot in the output, and replays anything that changed in between before the new segment is ever visible. This article follows that one delete through the machinery, with every claim checked against the Lucene 10.6.0 source.
Every line number in this article refers to the
releases/lucene/10.6.0tag. Two of the figures and the whole results table come from running code, not from reading it.
Why there is anything to merge
A flush turns the in-memory buffer into a segment on disk. One flush adds at least one segment, one per indexing thread’s buffer, so a busy writer produces them in bursts. Nothing rewrites an existing segment, because segments are immutable.
That immutability is also why a delete does not free anything. IndexWriter records the doc ID in a live-docs bitset beside the segment and leaves the bytes alone. The document stops matching queries immediately. Its postings, stored fields, norms and doc values stay on disk until something copies the segment’s survivors somewhere else.
So two costs grow on their own. Query work grows with the segment count, because a term query does one term-dictionary seek and builds one scorer per segment (TermStates.java:103, TermQuery.java:141). Dead bytes grow with the delete rate. A merge is the one operation that pays both down.
Which segments Lucene picks
TieredMergePolicy is the default. Three ideas carry most of its behaviour, and the third one is the one people are usually missing.
It ranks segments by size, not by position. getSortedBySegmentSize sorts every eligible segment by byte size descending, ties broken by segment name (TieredMergePolicy.java:341). The size it sorts on is not the size on disk. MergePolicy.size prorates the byte size by the fraction of deleted documents (MergePolicy.java:761), so a segment that is 40% deleted counts as 60% of its bytes. Candidates are then taken as a run through that size-sorted list, which is why a merge set can be scattered all over the index. Non-adjacency is not a feature bolted on, it falls out of ranking by size.
It scores every window and keeps the best. The outer loop tries every start index in the sorted list (:574) and scores each candidate with three factors (:739-765). Lower is better.
1
2
3
double mergeScore = skew; // largest input / total, floored
mergeScore *= Math.pow((double) totAfterMergeBytes, 0.05); // "gently favor smaller merges"
mergeScore *= Math.pow(nonDelRatio, 2); // "strongly favor merges that reclaim deletes"
The exponents are the whole story. Skew is the base, deletes are squared, and output size is raised to 0.05, which is almost flat. The code comments say so in as many words, “Strongly favor merges with less skew”, “Gently favor smaller merges over bigger ones”, “Strongly favor merges that reclaim deletes”. A candidate that is half deletes gets its score multiplied by 0.25, which is a far bigger lever than any plausible size difference.
It refuses merges that barely grow. A natural merge whose output would not be at least 50% larger than its biggest input is skipped outright (:623-636). The comment in the source names the failure it prevents, “pathological O(N^2) merging where merges keep rewriting again and again the biggest input segment into a segment that is barely bigger”. This is the rule that stops each new 20 MB flush from being folded into your 4 GB segment. The one exception is when that big segment has more than deletesPctAllowed deletes to reclaim, in which case rewriting it is the point.
Those three ideas sit on top of a budget. TieredMergePolicy walks geometrically growing tiers, granting segmentsPerTier segments at each level and multiplying the level size by the merge factor as it goes (:441-460). It merges when the index is over that segment budget, or when deleted documents exceed deletesPctAllowed of maxDoc (:562-566).
The defaults matter here, and two of them moved recently enough that older write-ups have them wrong.
| Setting | 10.6.0 default | Note |
|---|---|---|
segmentsPerTier |
8.0 | Was 10 before 10.3.0 |
floorSegmentMB |
16 | Was 2 before 10.2.0, an 8x jump |
maxMergeAtOnce |
10 | Effective merge factor is min(10, 8) = 8, so this knob rarely binds |
maxMergedSegmentMB |
5120 | 5 GB ceiling on natural merges |
deletesPctAllowed |
20.0 | Floor of the valid range was relaxed from 5 in 10.3.0 |
forceMergeDeletesPctAllowed |
10.0 | Only forceMergeDeletes uses it |
targetSearchConcurrency |
1 | Off by default, caps docs per segment when raised |
floorSegmentMB does double duty. It is the starting level size for the budget, which keeps a tail of tiny segments from inflating the allowed count, and it is the floor applied inside the skew term, so segments under 16 MB all look the same size and a merge of many tiny ones does not look lopsided. Below the floor Lucene will also merge more than the merge factor at once (:583-587), so “at most 8 inputs” is not true at the small end.
One review gets a new doc ID
Zoom all the way in. Five reviews, two segments, one of them already deleted.
Segment _0 holds reviews 101, 102 and 103 at local doc IDs 0, 1 and 2. Review 102 was deleted before the merge started. Segment _1 holds reviews 104 and 105. The application knows these documents by the indexed field id. Lucene knows them by doc ID, which is nothing more than a slot number inside one specific segment. A merge writes new slots, so every surviving document gets a new doc ID.
The order the inputs are concatenated in decides who gets the low slots, and it is worth being exact about it, because it surprised me. For an index with no index sort, the output is the inputs concatenated in the order the merge policy listed them, with each input’s deleted docs squeezed out. Nothing in IndexWriter or MergeState reorders that list. And TieredMergePolicy lists them largest-first by live bytes, so the delete on review 102 shrinks _0 below _1 and _1 goes first. Take the delete away and _0 leads instead. I verified both directions by running it.
That last point is the part worth internalising. MergeState.docMaps is documented as mapping “document IDs from old segments to document IDs in the new segment” (MergeState.java:46), and for an unsorted index each map is a doc base plus a packed table of “how many live docs came before me”, returning -1 for anything deleted (:190-207). The codecs do not read those maps directly. They wrap each input in a DocIDMerger, which asks the map for a mapped ID, skips the -1s, and yields documents in output order (DocIDMerger.java:58-69). SegmentMerger then drives every per-segment structure off the same merge state, stored fields first, then norms, postings, doc values, points, vectors, term vectors and field infos (SegmentMerger.java:117-179).
If the index has an index sort, the concatenation story goes away. MergeState routes to MultiSorter, which runs a real merge sort across all the inputs so their documents interleave by sort key (MergeState.java:214-240).
How the late delete gets in
Now the awkward moment from the opening. The merge has copied review 103 into _2 at slot 3. The delete arrives. Three facts make this safe.
The merge takes a snapshot. Before any reader is opened, mergeInit waits for every buffered delete packet that applies to these segments to finish resolving (IndexWriter.java:5375). Then each merge reader records the input’s hard live docs as they stood at that instant (ReadersAndUpdates.java:1166). That is what gives the merge a clean “before”.
Live docs are copy-on-write. A delete arriving later cannot mutate the snapshot. PendingDeletes drops its writeable bitset once the live docs are handed out, so the next delete has to clone first (PendingDeletes.java:108). That is why Lucene can test “did anything change?” with a single reference comparison.
The carry-over happens under the writer lock, before publication. commitMerge is synchronized and calls commitMergedDeletesAndUpdates before segmentInfos.applyMergeChanges splices the new segment in (IndexWriter.java:5049, install at :5102). For each input it compares the snapshot against the current hard live docs and, for every document deleted in between, marks the mapped output slot deleted (:4947-5004).
1
2
3
4
5
6
7
8
9
if (currentHardLiveDocs != prevHardLiveDocs) { // copy-on-write, so identity is enough
for (int j = 0; j < maxDoc; j++) {
if (prevHardLiveDocs.get(j) == false) {
assert currentHardLiveDocs.get(j) == false; // a deleted doc can never come back
} else if (carryOverDelete.test(j)) {
mergedReadersAndUpdates.delete(segDocMap.get(j));
}
}
}
The same pass remaps the doc-values updates that landed during the merge and survived it (:4576-4676). And if every document in the output ends up deleted this way, commitMerge throws the whole segment away instead of installing it (:5059).
That timing is why the output has four physical slots and three live reviews. Review 103’s bytes were already written, so they stay. maxDoc is fixed at merge time from the inputs’ live counts (MergeState.java:170) and a later delete never shrinks it. Search skips the slot, MergePolicy.size discounts the segment so it becomes a merge candidate sooner, and the next merge is what finally reclaims the space.
Which reader sees the result
A merge changes what the index looks like, but not for everyone at once. Five views of the same instant disagree, and each disagreement has a cause.
The writer installs the new segment in its in-memory SegmentInfos and checkpoints without writing a segments_N (IndexWriter.java:2927). A near-real-time reader opened or reopened from that writer reads straight off it, so it sees the merge with no durable commit (:609). An NRT reader that is already open sees nothing new until you reopen it. A reader opened from the directory resolves the highest segments_N it can find (StandardDirectoryReader.java:83), so it stays on the last commit.
I checked all five against Lucene 10.6.0 rather than reasoning about them. The example pauses a forced merge inside its merged-segment warmer, which is the window after the output is written and before commitMerge runs, applies the delete there, lets the merge finish, and then runs a term query for id=103 against each view. Every row below is an assertion in that program, so the program fails loudly if Lucene ever disagrees.
| View queried | Review 103 | Live docs / physical slots |
|---|---|---|
| New segment, inside the warmer, before install | Found at doc ID 3 | 4 / 4 |
| Original reader, still open | Found at doc ID 2 | 4 / 5 |
| Reader reopened from the writer | Absent | 3 / 4 |
| Directory reader opened before the next commit | Found at doc ID 2 | 4 / 5 |
| Directory reader opened after the next commit | Absent | 3 / 4 |
Run the Java example with JDK 21 or later and the Lucene 10.6.0 core JAR in the same directory.
1
java -cp lucene-core-10.6.0.jar LateDelete.java
One caveat on reading this as a model of hard deletes in general. carryOverHardDeletes only handles hard deletes. A soft delete is a doc-values write, so it travels on the doc-values carry-over path instead, and the merge wraps its readers to keep soft-deleted documents alive while still dropping hard-deleted ones (IndexWriter.java:5622-5661).
Why disk usage rises before it falls
Lucene writes the output while the inputs are still there, so peak usage is roughly inputs plus output. The interesting question is what happens after the swap, and the answer is reference counting, not garbage collection.
IndexFileDeleter keeps a reference count per filename and deletes a file the instant its count reaches zero (FileDeleter.java:77-130). Three things hold references, and it is worth knowing which is which:
- The writer’s own in-memory
SegmentInfos, through the non-commit checkpoint (IndexFileDeleter.java:552-586). - NRT readers, which call
incRefDeleteron the segments they opened (StandardDirectoryReader.java:149). - Retained commits, if you replace the default deletion policy.
KeepOnlyLastCommitDeletionPolicydrops every earlier commit as soon as a new one lands, so by default this holds nothing.
A plain directory reader is the one that surprises people. It holds no reference count at all. Its files get unlinked out from under it, and it keeps working only because of POSIX delete-on-last-close semantics, which the IndexWriter javadoc calls out explicitly. So on POSIX the unlink succeeds immediately and the blocks come back when the last reader closes its descriptors. Space is reclaimed when readers close, not when some background sweep notices.
Windows works differently, and “the operating system releases the file” is the wrong model there. The delete itself fails while a handle is open, so FSDirectory parks the filename in a pending-deletes set and retries later (FSDirectory.java:358-372). Until a retry succeeds the bytes are still on disk, hidden from listAll and rejected by openInput. On Windows, a long-lived reader really can keep disk usage at the peak.
What a merge costs while traffic is live
Once a merge is installed, every reader opened after it visits one segment where there were several. Readers already open, and queries already running, keep the old segment count until they reopen. Meanwhile the merge itself was reading and rewriting index data on the same machine that was serving queries.
Four mechanisms decide how much that hurts, and three of their defaults are not what the folklore says.
Merges run on background threads, and can stall the indexer. ConcurrentMergeScheduler stalls the calling thread while mergeSource.hasPendingMerges() && mergeThreadCount() >= maxMergeCount (ConcurrentMergeScheduler.java:619). The thread it stalls is your application thread inside addDocument or commit. Merge threads are explicitly exempt, since stalling one would deadlock progress. Each wait is 250 ms and the condition is rechecked, so the total stall is unbounded. The trigger is maxMergeCount, not maxThreadCount.
The defaults are derived from core count, with no disk probe. maxThreadCount = max(1, coreCount / 2) and maxMergeCount = maxThreadCount + 5 (:192). The old SSD-versus-spinning-disk detection is gone. The class now assumes an SSD and leaves the conservative spinning-disk numbers as a manual opt-in. The class javadoc still advertises a min(4, cores/2) cap that the code does not implement, so do not trust that line.
Auto IO throttle exists but is off. doAutoIOThrottle = false by default (:112), so every non-forced merge runs at Double.POSITIVE_INFINITY MB/s unless you call enableAutoIOThrottle(). What the scheduler does do unconditionally is pause the largest merges to zero when more than maxThreadCount merges over 50 MB are running (:373), which is how small merges get to jump the queue. Note also that rate limiting, when enabled, limits merge writes only. Reads are untouched.
Sequential read advice for merges is opt-in. This one is easy to get wrong, and I had it wrong. A merge does get its own memory mapping, because every MMapDirectory.openInput call builds a fresh one, so the advice on a merge’s mapping is independent of the search readers’ mappings. And MMapDirectory.ADVISE_BY_CONTEXT does turn Context.MERGE into ReadAdvice.SEQUENTIAL (MMapDirectory.java:156-169). But ADVISE_BY_CONTEXT is not installed by default. The field is an empty-returning function, so every mapping falls back to Constants.DEFAULT_READADVICE, which is ReadAdvice.NORMAL (:171). Nothing in released core calls setReadAdvice. To get the behaviour you have to ask for it:
1
2
var dir = new MMapDirectory(path);
dir.setReadAdvice(MMapDirectory.ADVISE_BY_CONTEXT);
Even then madvise is best effort. It is issued on platforms like Linux and macOS, and only when native access is permitted, which on a modern JDK means --enable-native-access=org.apache.lucene.core.
Two more costs the segment-count story hides. Some codecs parallelise inside one merge through MergeScheduler.getIntraMergeExecutor, but in released core only the HNSW vector writers use it, so this matters for vector indexes and not for a text-only one. And opening an NRT reader can itself run a merge on your calling thread, bounded by maxFullFlushMergeWaitMillis, which defaults to 500 ms (IndexWriterConfig.java:108). A refresh is not free.
How to see it in your own workload
Chart p99 query latency, indexing throughput, segment count and disk usage on one time axis. Mark when each merge starts and ends, and when the searcher refreshes. Hold the offered query rate, update rate and refresh interval steady, because changing any of them changes the merge schedule too.
Then read the three marks separately. Merge end is when the rewrite finished. Refresh is when queries start using the replacement. The old files can outlive both, for exactly the reference-count reasons above. An indexing slowdown and a latency spike from the same merge backlog will not line up, because one comes from maybeStall on the write path and the other from cache and IO contention on the read path.
Reference
Everything above is from the releases/lucene/10.6.0 tag.
| Topic | Source |
|---|---|
| Candidate selection, scoring, growth rule | TieredMergePolicy |
Live-size prorating, OneMerge, merge readers |
MergePolicy |
Doc maps, index-sort routing, output maxDoc |
MergeState |
| Writing the merged structures | SegmentMerger |
Warmer, commitMerge, late-delete carry-over |
IndexWriter |
| Snapshotting live docs for a merge | ReadersAndUpdates |
| Reference counting and file lifetime | IndexFileDeleter |
| NRT versus committed views | StandardDirectoryReader |
| Stalls, pausing, IO throttle, intra-merge executor | ConcurrentMergeScheduler |
| Read advice per mapping | MMapDirectory |
Also useful: the Lucene 10.6.0 release notes and Mike McCandless’s near-real-time benchmarks.