fix: Optimizes SpillingGrouper for high cardinality dimension(s) GroupBy with large memory footprint aggregators #19357
All Vouch review confidence checks passed
Residual risk 0.22 = Change Risk (0.52) × (1 − Review Confidence (0.57)).
Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.52 · 650 lines diff across 8 files
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.17 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size
diff_size
0.388
Shallow Review Depth
shallow_review_depth
0.289
Real PR Conversation Timeline
1 comments
"Review active on #19357"
general
weight: 0.35
maytasm
Optimizes SpillingGrouper for high cardinality dimension(s) GroupBy with large memory footprint aggregators
Description
tldr; Batch small spill files in SpillingGrouper to reduce file count
Problem
When aggregators like HLL sketches (or ThetaSketch) are used in groupBy queries, the BufferHashGrouper pre-allocates a large fixed-size buffer per group slot (e.g. ~64KB per slot for HLL with lgK=16). This causes the in-memory grouper to fill up quickly and spill frequently (as the number of unique grouping the BufferHashGrouper can store in memory is low). However, when each key has only been seen a few times (i.e. high cardinality dimension(s) GroupBy), the sketch serializes to a compact form of just a handful of bytes (HLL in List mode). The result is thousands of tiny spill files on disk — each one only a few KB despite the grouper buffer being full.
Large number of spill files can cause OOM when GroupBy merges spill files by opening all of them simultaneously. We previously prevent this by adding guardrail in https://github.com/apache/druid/pull/19141 which would fail the query. This PR fix the issue and will allow the query to succeed.
Fix
Instead of writing every grouper flush directly to its own spill file, small flushes (serialized size < 1MB) are batched in heap memory. When the accumulated pending bytes reach the 1MB threshold, all pending runs are merge-sorted and written as a single consolidated file. Large flushes (>= 1MB) bypass batching and go directly to disk as before.
The approach avoids holding the full serialized data in heap during the spill by streaming directly to a temp file first, then reading back only small files (< 1MB) into memory for batching. This prevents OOM risk when the serialized size happens to be close to the buffer size.
##### Key changed/added classes in this PR
All changes are in SpillingGrouper.java:
- spill(): Streams grouper contents to a temp file first. If the file is small (< MIN_SPILL_FILE_BYTES), reads it back into pendingSpillRuns and deletes the temp file. If large, keeps it on disk. Triggers flushPendingRunsToDisk() when accumulated pending bytes reach the threshold.
- flushPendingRunsToDisk() (new): Deserializes all pending in-memory runs, merge-sorts them (each run is individually sorted from grouper.iterator(true)), and writes the merged result as a single sorted spill file. Also writes a dictionary file for the accumulated dictionary entries.
- deserializeIterator() (new / refactor): Extracted the deserialization transform (deserialize aggregator values, Integer→Long coercion) that was previously inlined in iterator(). Now shared between iterator() and flushPendingRunsToDisk().
- reset() / close(): Clear pending state (pendingSpillRuns, pendingSpillBytes, pendingDictionaryEntries).
- iterator(): Calls flushPendingRunsToDisk() before iteration to flush any runs that didn't reach the threshold during the spill phase.
Memory overhead
Peak additional heap usage is bounded by ~2 × MIN_SPILL_FILE_BYTES (2MB): up to 1MB of accumulated pending byte arrays plus one file being read back. The grouper buffer itself is an off-heap direct ByteBuffer and is reset before the read-back.
Optimizations considered but not pursued
Combine duplicate keys during flush (
combineByKey)During
flushPendingRunsToDisk(), we tried deserializing all pending runs, combining entries with duplicate keys by merging their aggregator values (usingAggregatorFactory.combine()), then serializing the deduplicated result. The idea was to reduce the output file size and the final merge fan-in.Flame graph analysis showed
combineByKeyitself consumed only 28 CPU samples — negligible overhead. However, wall-clock time regressed from 180s to 190s (+5.5%). The cause: even though the CPU cost ofcombine()itself was small, the synchronous deserialize-combine-reserialize pipeline added latency to the processing thread's critical path. The processing thread cannot ingest new rows while flushing, so any additional work during the flush directly extends the stall. In this workload, the keys had low duplication across the small runs, socombineByKeyeliminated very few entries while paying the full deserialization cost for every entry.Reducing merge fan-in with cascaded intermediate merges
Instead of writing all pending runs as a single merged file, we considered a cascaded merge approach — progressively merging spill files on disk (similar to an external merge sort with bounded fan-in) to keep the final
iterator()merge across a small number of large files. This was not pursued because the batching approach already achieves the same goal more simply: by accumulating small runs in memory and writing them as one file, the number of files atiterator()time is naturally reduced by orders of magnitude (e.g., from ~2,000 to ~dozens). Cascaded disk merges would add I/O amplification (each entry written to disk multiple times) for marginal additional fan-in reduction.Potential future improvements
Reducing sketch initialization cost
Flame graph profiling shows that
HllSketchMergeBufferAggregatorHelper.createNewUnion()accounts for 50.7% of the processing thread's CPU time — the dominant bottleneck. Every time a new group slot is initialized in theBufferHashGrouper,init()callscreateNewUnion()which copies a pre-built empty Union image (~65KB for lgK=16) into the buffer viainitializeEmptyUnion(), then wraps it withUnion.writableWrap(). During hash table growth (adjustTableWhenFull()), every existing slot is relocated viarelocate(), which callscreateNewUnion()again. With frequent spills, the grouper repeatedly fills, spills, resets, and re-initializes — multiplying the init cost.Possible approaches:
1. Variable-size buffer slots in
BufferHashGrouper: Currently,ByteBufferHashTableuses fixed-width buckets (bucketSizeWithHash = HASH_SIZE + keySize + aggregators.spaceNeeded()), wherespaceNeeded()is the maximum intermediate size. For HLL with lgK=16, this pre-allocates ~65KB per slot even when the sketch is in List mode (few distinct values, only a handful of bytes). If the hash table supported variable-width slots — starting small and growing on demand as sketches transition from List → Set → HLL mode — far more groups would fit in the buffer before spilling. This would dramatically reduce the number of spills and proportionally reducecreateNewUnion()calls. However, this is a fundamental architectural change toByteBufferHashTable, which relies on fixed-width contiguous buckets for O(1) offset calculation and linear probing.2. Lazy sketch initialization: Instead of initializing a full Union object when a new bucket is created, defer the expensive
createNewUnion()call until the first aggregation value is actually merged. For groups that are spilled before receiving many values, this could avoid the full initialization cost entirely. TheBufferAggregatorinterface would need to support deferred init — e.g., storing a sentinel in the buffer and lazily initializing on firstaggregate()call.Benchmarks result
Before this PR:
After this PR:
The existing queryMultiQueryableIndexWithSpilling/queryMultiQueryableIndexWithSpillingTTFR uses bufferGrouperMaxSize=4000 which produce reasonable spills of ~200kb. I have also added new benchmarks with similar idea but producing spill files on extremes ends for size. queryMultiQueryableIndexWithSmallSpilling/queryMultiQueryableIndexWithSmallSpillingTTFR sets bufferGrouperMaxSize=100, producing spill size ~6 KB. This would result in more batching. queryMultiQueryableIndexWithLargeSpilling/queryMultiQueryableIndexWithLargeSpillingTTFR sets bufferGrouperMaxSize=70000, producing spill size ~4 MB. This would skip batching. These new benchmarks are not added to the PR since they are really the same as queryMultiQueryableIndexWithSpilling/queryMultiQueryableIndexWithSpillingTTFR just with different config values.
This PR has:
- [ ] using the concurrency checklist (Remove this item if the PR doesn't have any relation to concurrency.)