perf: hybrid sort-shuffle buffering: split rows by partition on arrival when memory allows
Is your feature request related to a problem or challenge? Please describe what you are trying to do.
SortShuffleWriterExec buffers whole input batches plus a (batch_idx, row_idx)
pair per row, and only builds output batches when it spills or finishes, by
gathering each partition's rows with interleave_record_batch (#1598). This
keeps memory flat however many partitions there are.
On large shuffles the gather is slow. By the time it runs, the buffered batches have left the CPU cache, and each output batch takes a few rows from each of many input batches, so nearly every row is a cache miss.
For example, on TPC-H SF10 (one executor), shuffling 60M lineitem rows
(l_orderkey, l_quantity) into 12 partitions takes 1.75 s against 0.31 s for
the scan. The gather is the largest part of the write (~0.48 s per input
partition), ahead of IPC encoding (~0.44 s) and recording the row indices
(~0.23 s).
Describe the solution you'd like
Give each input partition two buffer layouts and choose between them by memory, not by partition count:
| Deferred (today) | Split on arrival (new) | |
|---|---|---|
| As a batch arrives | Keep it, and record an 8-byte index per row | Copy each partition's rows into that partition's BatchCoalescer, then drop the batch |
| At spill or end | Gather every output batch from cold memory | Write the batches already built |
| Extra memory | The row indices | One partly filled batch per partition |
Splitting is faster because each row is copied while its batch is still in cache. Its cost is the partly filled batches, which grow with the partition count:
partitions × batch_size × row bytes + partitions × long-string columns × 1 MiB
So every input starts deferred. Once it has buffered partitions × batch_size
rows, enough to fill a batch per partition and to measure the row width, it
decides once: split if that cost fits a budget, otherwise stay deferred for
good. The budget is the smallest of:
ballista.shuffle.sort_based.split_on_arrival_max_bytes, a new setting (default 64 MiB; 0 never splits);- ¼ of the per-task spill budget;
- ¼ of the input's share of the pool's free memory when the input starts, so memory other tasks already hold is left out.
The quarters leave most of the memory for full batches, so spills write full batches. Without the pool term, a 2-column shuffle into 200 partitions in a 256 MB pool spilled 7,390 times instead of 88 and ran 1.9× slower. If a split input later spills more partly filled bytes than full ones, a sign of memory pressure, it goes back to deferred for good.
Because the decision is about memory, large partition counts stay deferred on their own. At the default 64 MiB, a shuffle of 16-byte rows can split up to 512 partitions, and one with a long-string column fewer than 64. At 40,000 partitions even one byte a row is over budget, so it runs exactly as today.
Shuffle statistics (num_bytes) should count the bytes rows use rather than
allocated capacity, or each partly filled batch reports the size of a full
one to AQE.
Prototype results, single node, TPC-H SF10:
- 12 partitions: −8.5% total; shuffle-heavy queries (q3, q4, q12, q17, q21, q22) −10 to −23%.
- 200 partitions: −22% on q1–q8.
benches/sort_shuffle.rs(#1598's wide, 200-partition case): no change, since it stays deferred.- Peak executor RSS at 12 partitions: 3.44 → 3.18 GB on q3, q9, q17, q18 and q21.
- Same AQE join decisions on all 22 queries; all pass
--verify.
Describe alternatives you've considered
- Always split, as before #1598, using DataFusion's
BatchPartitioner. At 200 partitions an 8192-row batch became ~41-row pieces, each written as its own IPC batch (#1432). Splitting into a coalescer fixes the batch size, but memory still grows with the partition count, so it cannot be the only layout. - A partition-count threshold. Comet's "immediate mode" (apache/datafusion-comet#3845, #3855) split on arrival behind an opt-in setting and planned an automatic mode based on partition count. It was set aside because per-partition builders reserve memory up front, which does not scale to thousands of partitions (Comet #887). Gluten ships both layouts and switches on partition count (see below). A count ignores row width and memory: 200 partitions of 16-byte rows fit easily, 200 of wide string rows do not. A memory budget covers both, and nothing is reserved until the input has shown it fits.
Prior art: Gluten
Gluten (Spark on Velox) ships both layouts as separate shuffle writers and
picks one per shuffle. Source links are to
e681b63.
Hash writer, the default
(VeloxHashShuffleWriter): split on arrival.
- Each partition has preallocated Arrow buffers for every column (validity and values; lengths and values for strings). Each input batch is scattered into them column by column as it arrives.
- A buffer's size in rows is recomputed for every batch as
min(4096, memLimit / bytesPerRow / partitions / 4), withmemLimitat least 128 MiB andbytesPerRowthe fixed widths plus a running average of string lengths (calculatePartitionBufferSize). - A full buffer is compressed into an in-memory payload, which is spilled
under memory pressure. Payloads of up to 1,024 rows (
merge.threshold0.25 × 4,096) are merged with the next ones until they reach 4,096 rows. - So memory stays bounded, but batches shrink as partitions grow. At 40,000 partitions with a 1 GiB limit and 100-byte rows, a buffer holds 67 rows, and the writer relies on merging to rebuild batches. That is the small-batch problem Ballista hit before #1598 (#1432).
Sort writer
(VeloxSortShuffleWriter,
apache/gluten#6475, after Spark's UnsafeShuffleWriter): buffer, then
order by partition.
- Each input row is converted to Velox's
CompactRowformat and appended to pages ofmin(memLimit / 4, 64 MiB)(acquireNewBuffer). An 8-byte id per row packs its partition (24 bits), page (13) and offset (27). - At spill or end, the ids are radix-sorted on their partition bytes, and
each partition's rows are copied in order into a 1 MiB buffer that is
compressed and written
(
evictAllPartitions). - Memory does not depend on the partition count. The gather still reads rows in random order, but each row is one contiguous copy rather than one per column.
Choosing between them. Gluten uses the hash writer unless the shuffle has
more than 4,000 partitions (spark.gluten.sql.columnar.shuffle.sort.partitions.threshold)
or more than 100,000 columns (...sort.columns.threshold). #6475 measured
TPC-H SF1000 at 40,000 partitions: 1,342 s with the sort writer against
1,790 s with the hash writer (1.33×) and 2,097 s with Spark's own shuffle
(1.56×). Every query but q1 and q6 was faster, up to 2.2× on q10. Below the
threshold Gluten keeps the hash writer, so it treats splitting on arrival as
the faster choice at ordinary partition counts.
What carries over.
- The same split: scatter on arrival for few partitions, buffer and order by partition for many. Gluten also sizes its buffers at ¼ of the memory limit and caps pages at 64 MiB, like the budget proposed here.
- Gluten decides once per shuffle from its partition and column counts. This proposal decides per input partition, from the measured row width against the memory budget, and can go back if memory gets tight.
- Gluten's hash writer shrinks its buffers as partitions grow and merges the
small payloads afterwards. Here the coalescers always build full
batch_sizebatches, and an input that cannot afford them stays deferred. - Gluten's sort gather copies one contiguous row per entry, while Ballista's
deferred gather (
interleave_record_batch) makes a random access per column for every row. That makes Ballista's deferred layout costlier per row than Gluten's, which is part of why splitting pays off here.
Additional context
Two PRs:
- Refactor with no behaviour change:
BufferedBatchesowns the drain and its memory accounting (#2579, merged). - Split on arrival: the second layout, the switching rules, the new setting
and the
num_bytesfix (#2774).
All numbers are single-node SF10. Whether an input splits depends on partition count and row width, not data size, so larger runs with more partitions will split less often under the default. Where they do split, the gain should hold or grow, since a bigger buffer makes the gather colder. Open question: should the default cap scale with executor memory?
Hey @andygrove I know you're busy, but if you have time, could you eyeball / smell-test this proposal? I know you have prior experience investigating this exact solution on Comet (see above), and would appreciate your input.
I've spent alot of time thinking about this solution. The TPCH - SF10 benchmark seems to indicate a 8.5 -> 10% increase in performance, and I think this hybrid approach addresses scalability concerns you previously ran into (copying Gluten). Maybe this will be easier if I just opened a PR, so you have the code to read through?
I'll split out two other PR's while working on the branch, which includes an minor refactor /perf improvement + shuffle statistic fix that can land separately regardless of the resolution.
Sorry it's a wall of text, but it does read coherently to me.
Thanks for writing this up @NoahKusaba. I kept chasing the same design in Comet and it was faster for a tiny number of partitions, but not practical for scale. If we buffer one batch in each output partition's coalescer - let's take a hypothetical 8MB per batch and 40,000 output partitions, we now have > 300 GB cached in memory.
We could consider choosing the strategy based on number of partitions as long as we can override behavior with configs.
If you want to create a PR with the implementation, I'd be happy to test with TPC-H @ SF1k and 200 partitions, which is the default benchmark that I use for now.
5. We could consider choosing the strategy based on number of partitions as long as we can override behavior with configs. If you want to create a PR with the implementation, I'd be happy to test with TPC-H @ SF1k and 200 partitions, which is the default benchmark that I use for now.
Thanks for taking the time to read the proposal! I would greatly appreciate if you had the time to benchmark the PR, but want to take some more time to refine it and will open when the refactor is merged in.
I understand the concern about memory growing with partition count, the hope is by having both paths: SplitBuffered -> Fast path, buffers the batch to each output partitions coalescer (memory overhead scales with partition count) DeferredBuffer -> Old path, no memory concerns
This is the logic I'm thinking about:
Worst case memory for splitting (cost) = partitions * batch_size * avg row bytes + partitions * view columns * 1MB
With budget being configurable it would start Deferred: cost ≤ budget → switch to split cost > budget → stay deferred for good
This way at best we can get the speed benefit from split path on low partition counts, and not regress speed at higher partition counts by switching back to deferred under memory pressure (with small overhead).