Why AQE Coalesces Shuffle Partitions (and When It Can't Help)
How Adaptive Query Execution merges small shuffle partitions at runtime, the settings that control it, and the cases where you still have to tune.
TL;DR
spark.sql.shuffle.partitions(default 200) is a guess made before Spark knows how much data the shuffle will produce. It's wrong for most queries.- Adaptive Query Execution (AQE) waits for the shuffle's map side to finish, reads the real size of every output partition, and merges adjacent small partitions until each is close to a target (
advisoryPartitionSizeInBytes, 64 MB by default). - Fewer, fuller tasks mean less scheduling overhead and fewer tiny output files. It's on by default since Spark 3.2 and on Databricks.
- Coalescing can only merge. If the shuffle needs more partitions than you started with, AQE can't split them. Start high, let AQE bring it down.
- In open-source Spark,
parallelismFirst=true(the default) quietly ignores the 64 MB target. Set it tofalseon shared clusters.
The problem
NorthBridge's analytics team ran two nightly jobs on the same cluster, with the same default config.
The first aggregated a day of store returns: a 300 MB shuffle split into 200 partitions of 1.5 MB. Each task did about 40 ms of work and spent more time being scheduled than computing. The job wrote 200 tiny files to the gold table.
The second joined 18 months of sales lines to promotions: an 800 GB shuffle split into the same 200 partitions, 4 GB each. Every task spilled to disk and three executors died.
Same setting, opposite problems. A single static number can't be right for both. AQE fixes the first job automatically. The second needs you.
Key concepts
| Concept | What it means | Why it matters here |
|---|---|---|
| Shuffle | Redistributing rows across the cluster by key (joins, groupBy, windows, repartition) |
The point where partition count is chosen |
| Map side / reduce side | Tasks that write shuffle files / tasks that read them | AQE acts between the two |
| Shuffle partition | One bucket of the shuffle output; one reduce task reads it | Too many: overhead. Too few: spill, OOM |
| Query stage | A piece of the plan that ends at a shuffle or broadcast | AQE re-plans at stage boundaries |
AQEShuffleRead |
The plan node that reads coalesced or split partitions | Its metrics show what AQE did |
| Advisory partition size | AQE's target bytes per coalesced partition | 64 MB by default |
The bytes don't change. The number of tasks does.
How coalescing works
Without AQE, Spark builds the whole physical plan up front and sticks with it. With AQE, it executes the plan stage by stage and re-optimizes at each boundary:
- Run the map stage. Each map task writes its output split into N shuffle partitions, where N is
spark.sql.shuffle.partitions(orinitialPartitionNum, below). - Collect statistics. When the stage finishes, the driver knows the exact size of each of the N partitions.
- Merge neighbours. Walking partitions in order, AQE groups contiguous partitions until adding the next one would exceed the target size. Partition 0–7 might become one read, 8–15 the next.
- Read ranges. The reduce stage gets an
AQEShuffleReadnode. Each reduce task reads a range of original partitions instead of exactly one.
A few properties fall out of this:
- Only adjacent partitions merge, so hash partitioning is preserved: rows with the same key still land in the same task.
- Both sides of a join are coalesced the same way, so partition 7 on the left still meets partition 7 on the right.
- Nothing is re-shuffled. Coalescing just changes which files each reducer reads. It's close to free.
- It never splits. A 4 GB partition stays 4 GB. (Splitting is a separate AQE feature for skewed joins; see Data Skew in Spark.)
AQE needs a shuffle or broadcast exchange to act on. A map-only job (read, filter, write) has nothing to coalesce, and AQE doesn't apply to Structured Streaming queries at all.
The settings
# Spark 3.5 / 4.0, or Databricks Runtime 16.4 LTS+. Defaults shown.
spark.conf.get("spark.sql.adaptive.enabled") # true
spark.conf.get("spark.sql.adaptive.coalescePartitions.enabled") # true
spark.conf.get("spark.sql.adaptive.advisoryPartitionSizeInBytes") # 64MB
spark.conf.get("spark.sql.adaptive.coalescePartitions.minPartitionSize") # 1MB
spark.conf.get("spark.sql.adaptive.coalescePartitions.parallelismFirst") # true (OSS Spark)
spark.conf.get("spark.sql.shuffle.partitions") # 200| Setting | Default | What it does |
|---|---|---|
spark.sql.adaptive.enabled |
true |
Master switch for AQE |
spark.sql.adaptive.coalescePartitions.enabled |
true |
Turns coalescing on |
spark.sql.adaptive.advisoryPartitionSizeInBytes |
64 MB | Target size after merging |
spark.sql.adaptive.coalescePartitions.minPartitionSize |
1 MB | Merged partitions won't be smaller than this |
spark.sql.adaptive.coalescePartitions.initialPartitionNum |
unset | Starting partition count before coalescing; falls back to spark.sql.shuffle.partitions |
spark.sql.adaptive.coalescePartitions.parallelismFirst |
true |
OSS Spark only: favour parallelism over the target size (see below) |
spark.sql.shuffle.partitions |
200 | Starting count. On Databricks, auto enables auto-optimized shuffle |
The parallelismFirst catch
In open-source Spark, parallelismFirst=true tells AQE to ignore the advisory size and only respect minPartitionSize, so it keeps at least as many partitions as there are cores. It exists to avoid a regression for jobs that ran on idle clusters. The effect: on a 64-core cluster, that 300 MB shuffle still becomes ~64 tasks of ~5 MB, not 5 tasks of 64 MB.
The Spark docs recommend setting it to false on busy clusters, so resources go to other work instead of tiny tasks:
spark.conf.set("spark.sql.adaptive.coalescePartitions.parallelismFirst", "false")Databricks controls this differently: it uses a minimum partition count of twice the cluster's cores (minPartitionNum) and documents not setting that override. If you're on Databricks, leave it and tune the advisory size and starting count instead.
Step 1 — See what AQE did
explain() before running a query only shows the initial plan:
# Databricks Runtime 16.4 LTS+, PySpark
returns = spark.table("northbridge.silver.returns")
daily = (returns
.where("return_date = '2026-11-12'")
.groupBy("store_id", "reason_code")
.agg({"refund_amount": "sum"}))
daily.explain(mode="formatted")
# AdaptiveSparkPlan (isFinalPlan=false)
# +- HashAggregate ... +- Exchange hashpartitioning(store_id, reason_code, 200)Run an action, then open Spark UI → SQL / DataFrame → the query. The graph now shows the final plan with an AQEShuffleRead node:
AQEShuffleRead
number of partitions: 6
number of coalesced partitions: 6
partition data size: 312.4 MiB
Exchange
shuffle records written: 4,812,330
data size: 312.4 MiB200 planned partitions became 6. If you see AQEShuffleRead missing, AQE didn't coalesce: either there was nothing to merge, coalescing is off, or the shuffle was a repartition(n) with an explicit number (AQE respects a number you asked for).
On serverless compute and SQL warehouses there's no Spark UI; the query profile shows the same shuffle and partition metrics.
Step 2 — Start high, let AQE bring it down
Because AQE can merge but not split, the starting count should be big enough for your largest shuffle. Small shuffles get coalesced down; large ones get enough partitions not to spill.
A rough sizing rule for the starting count:
starting partitions ≈ largest shuffle size / 128 MB (rounded up to a multiple of total cores)For NorthBridge's 800 GB join: 800 GB / 128 MB ≈ 6,400. On a cluster with 160 cores, 6,400 is already a multiple.
# Either set the starting count for coalescing only...
spark.conf.set("spark.sql.adaptive.coalescePartitions.initialPartitionNum", "6400")
# ...or raise shuffle.partitions for the session/job
spark.conf.set("spark.sql.shuffle.partitions", "6400")The 300 MB returns job, running in the same session, still gets coalesced to a handful of partitions. That's the point: one high starting value serves both.
On Databricks, auto-optimized shuffle picks the starting count from the plan and input size:
spark.conf.set("spark.sql.shuffle.partitions", "auto")Set it at the job or cluster level. Structured Streaming is the exception: a stream's shuffle partition count is fixed by its checkpoint and can't change between restarts.
Step 3 — Tune the target, carefully
The 64 MB advisory size is a balance. Bigger partitions mean fewer tasks and fewer output files, but more memory per task.
| Workload | Advisory size to try |
|---|---|
| Default, mixed jobs | 64 MB |
| Wide aggregations writing to Delta, few output files wanted | 128 MB |
Memory-heavy stages (big sorts, wide rows, collect_list) |
32–64 MB |
spark.conf.set("spark.sql.adaptive.advisoryPartitionSizeInBytes", "128MB")Measure spill before and after. If Spill (Disk) appears in the stage summary metrics, the target is too big for your executor memory. See Reading the Spark UI.
Step 4 — Use it to control output files
The last shuffle before a write decides how many files you write. Coalescing therefore reduces small files for free, as long as there is a shuffle before the write.
For map-only writes (no shuffle), file count equals input partitions. Two options that keep AQE in charge:
# Ask for a shuffle AQE is allowed to size: REBALANCE
(df.hint("rebalance")
.write.mode("append")
.saveAsTable("northbridge.gold.daily_returns"))INSERT INTO northbridge.gold.daily_returns
SELECT /*+ REBALANCE */ * FROM staged_returns;REBALANCE adds a shuffle that AQE coalesces to the advisory size (and splits if skewed, controlled by spark.sql.adaptive.optimizeSkewsInRebalancePartitions.enabled). On Delta tables, optimized writes do the same job and are often already on; see The Small Files Problem.
The result
For NorthBridge: parallelismFirst=false and a starting count of 6,400 for the shared job cluster.
- Returns job: 200 tasks → 5 tasks, 200 files → 5 files, runtime 2.4 min → 1.1 min.
- Sales-promotions join: 200 partitions of 4 GB → 6,400 partitions of ~125 MB. AQE left those alone (they were already above the 64 MB target) and only coalesced the small shuffles elsewhere in the job. No spill, no lost executors, 48 min → 19 min.
No query code changed.
From production: gotchas and lessons
-
Symptom: After a Spark 3 upgrade, a job ran thousands of tasks of a few MB each. Cause:
parallelismFirst=trueignored the 64 MB target to match core count, and the starting count had been raised to 2,000. Fix:parallelismFirst=false. The starting count stayed high; AQE now actually coalesced. -
Symptom: A big join still spilled heavily even with AQE on. Cause: 200 starting partitions for a 600 GB shuffle. Coalescing can't split. Fix: Raise
initialPartitionNum(orshuffle.partitions, orautoon Databricks) so the starting point is above what the biggest shuffle needs. -
Symptom:
df.repartition(400)produced exactly 400 tiny partitions; AQE did nothing. Cause: An explicit number is treated as a requirement. Fix: Userepartition("col")without a number, or theREBALANCEhint, when you want AQE to choose. See repartition vs coalesce. -
Symptom: A Structured Streaming aggregation used 200 partitions and changing the config had no effect. Cause: AQE doesn't apply to streaming queries, and the partition count is stored in the checkpoint. Fix: Choose
spark.sql.shuffle.partitionsbefore the stream's first run. Changing it means a new checkpoint. -
Symptom: The plan in
EXPLAINdidn't match what ran. Cause:EXPLAINdoesn't run the query, so it showsisFinalPlan=false. Fix: Read the final plan in the Spark UI SQL tab or the query profile.
Performance and cost notes
Every task carries fixed overhead: scheduling, deserializing the task, opening shuffle files, committing output. With tasks of a few MB, that overhead can be most of the runtime. Coalescing turns it back into useful work, which shows up directly as fewer DBUs for the same output.
The opposite failure is more expensive. Too few partitions for a big shuffle means spill (slow disk I/O) or OOM (retries, lost executors, sometimes a failed job). That's why "start high" is the safer default: AQE fixes too many for you, not too few.
When not to use this
Keep AQE on. There are very few good reasons to disable it on Spark 3.2+.
Don't rely on coalescing to fix a stage with no shuffle, a streaming query, or a single giant partition caused by a hot key. Those need a writer fix, a checkpoint-time decision, or skew handling respectively.
Checklist
- AQE and coalescing on (the default; confirm in the Environment tab)
- OSS Spark:
parallelismFirst=falseon shared clusters - Starting partition count sized for the largest shuffle, or
autoon Databricks - Final plan checked in the SQL tab for
AQEShuffleRead - No explicit
repartition(n)where you want AQE to decide - Streaming jobs: shuffle partitions chosen before the first run
Practice
- Try: PySpark Interview Questions: 50 Coding and Scenario Problems
- Build it yourself: run the same
groupByon 100 MB and on 50 GB with AQE off, then on, then withparallelismFirst=false. Record task count, files written and runtime for each.
Further reading
Keep going
Data Skew in Spark: Detect It and Fix It
Find the hot key behind a stage that never finishes, then fix it with AQE skew joins, key cleanup, hot-key isolation or salting, in that order.
Reading the Spark UI: Stages, Tasks, Spill and Skew
A practical route through the Spark UI: map a slow query to its stage, read the summary metrics, and recognise skew, spill, tiny files and GC pressure.
repartition vs coalesce: When Each Is Right
repartition shuffles to any count with even sizes; coalesce merges without a shuffle but only downwards. When to use each, and the coalesce(1) trap.
One practical note a week
Get new articles, problems and guides in your inbox.
Thanks! You're on the list. (Local demo — no email provider is wired up yet.)