Adaptive query execution
Part of the free LogicWiz Data Engineering course, Module 12: How Spark runs. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 7:40 on a quiet Tuesday. SwiftKart's refund report is set up for month-end, with spark.sql.shuffle.partitions at 2,000, so today it should run 2,000 tasks of a few KB each. The Spark UI shows 31 tasks in the last stage. A join that explain() called SortMergeJoin ran as a BroadcastHashJoin. One stage reads AQEShuffleRead coalesced and skewed. Nora scrolls through the job: "Nobody touched the code. So who changed the plan?"
You'll learn to
- Explain how AQE re-plans a query from real sizes
- Work out the size AQE merges partitions to
- Tell which join partitions AQE splits, and what that costs
- Say what AQE cannot fix
Learn
Who changed the plan?
Nobody changed the code, and Spark did not ignore it. Spark changed its own plan while the job was running.
Think back to how a plan is made (Lesson 12.7). The planner guesses sizes before anything runs: file sizes, a filter that shrinks nothing, 200 shuffle partitions whatever the data. A plan built on guesses is sometimes wrong.
Adaptive query execution, AQE for short, checks the guesses against real numbers. It is on by default since Spark 3.2 (spark.sql.adaptive.enabled). The idea is small.
- Cut the plan into pieces at every shuffle. A piece is called a query stage.
- Run the pieces whose inputs are ready.
- Read how many bytes each one really wrote, partition by partition.
- Plan the rest again with those numbers, and repeat.
AQE only changes what has not started. A running stage is never re-planned.
The refund report, re-planned as it runs
A query with two shuffle stages, a join and a final aggregate: the shuffles run first, the customers side turns out to be 1.6 MB so the sort-merge join is re-planned as a broadcast join, and the 2,000 partitions of the last shuffle are merged into 31 tasks.
Before the run. This is what
explain()printed: two shuffles, a sort-merge join, and 2,000 partitions after every shuffle. All of it comes from guesses.Run what is ready. The two shuffle stages need nothing before them, so they run. Every map task writes its shuffle files and reports their sizes to the driver.
Read the real sizes. The customers side was estimated at 48 MB. Its shuffle wrote 1.6 MB. That is under the 10 MB broadcast threshold.
Plan the join again. A side of 1.6 MB can be broadcast, so the sort-merge join becomes a broadcast hash join. Its two sorts never run.
Run the join, measure again. The join shuffles its output into 2,000 partitions for the totals: 1.2 GB in all. Most of the partitions are under 1 MB.
Plan the last stage again. AQE merges small neighbouring partitions until a task holds about 37.5 MB: 31 tasks, not 2,000. Only now does
explain()sayisFinalPlan=true.
Read each step top to bottom, in the order the stages run. Made-up sizes for the scene, on a 32-core cluster. A teal box is a decision AQE took after it saw real numbers. The next three sections take those decisions one at a time.
Clue 1: 2,000 partitions, 31 tasks
After a shuffle stage, AQE looks at the real size of every partition and merges neighbours into one task. This is called coalescing. It walks the partitions in order and starts a new task when the next partition would push the current one past a target size. Empty partitions get no task.
The target is the smaller of two numbers, and never less than 1 MB:
- the advisory size, 64 MB by default
- the total shuffle size divided by the number of cores
The second number surprises people. By default Spark would rather keep about one task per core than reach 64 MB. The setting is called parallelismFirst. Take 343 MB on 8 cores:
- 343 / 8 = 42.9 MB
- 42.9 is under 64, so the target is 42.9 MB
Switch parallelismFirst off and the target is the full 64 MB.
Coalescing 20 shuffle partitions
A groupBy whose 20 shuffle partitions have uneven real sizes, from empty to 71 MB; AQE packs neighbours into tasks up to the target size, which depends on the advisory size and on parallelismFirst.
Twenty partitions, 343 MB, 8 cores: the sum from the text. Slide the advisory size and switch parallelismFirst off. The target moves from 343 / 8 = 42.9 MB to 64 MB, and the task count from 10 to 7.
The coalescing rule in Python
def coalesce_target(total_mb, advisory_mb=64, cores=8, parallelism_first=True, min_mb=1):
"""The size AQE aims for when it merges shuffle partitions."""
per_core = total_mb / (cores if parallelism_first else 1)
return max(min_mb, min(advisory_mb, per_core))
def coalesce(sizes, target):
"""Pack neighbouring partitions while they fit in the target; skip empty ones."""
groups, current, start = [], 0, 0
for i, size in enumerate(sizes):
if i > start and current + size > target:
if current > 0:
groups.append((start, i, round(current, 1)))
start, current = i, size
else:
current += size
if current > 0:
groups.append((start, len(sizes), round(current, 1)))
return groups
sizes = [3.2, 0, 41, 12, 8.5, 0.4, 27, 64, 5, 0, 18, 2.6, 33, 9, 0.8, 22, 71, 4, 15, 6.5]
total = sum(sizes)
for first in (True, False):
target = coalesce_target(total, parallelism_first=first)
groups = coalesce(sizes, target)
print(f'parallelismFirst={first}: target {target:.1f} MB, {len(groups)} tasks')
print(' ', [g[2] for g in groups])
The same 20 sizes as the simulator. coalesce_target is the sum from the text, and coalesce is the walk along the neighbours. Spark's own ShufflePartitionsUtil.coalescePartitions works on bytes and also folds a group under minPartitionSize into a neighbour. None is that small here.
Before and after coalescing, 8 cores, 343 MB
| Target | Tasks | Task sizes (MB) | |
|---|---|---|---|
| No AQE | - | 20 | From 0 to 71: three empty tasks, five under 5 MB |
| AQE, parallelismFirst true | 343 / 8 = 42.9 MB | 10 | 3.2, 41, 20.9, 27, 64, 25.6, 42.8, 22, 71, 25.5 |
| AQE, parallelismFirst false | 64 MB | 7 | 56.2, 35.9, 64, 58.6, 31.8, 71, 25.5 |
Partitions that are already over the target (64 and 71 MB) stay as they are: coalescing never splits. At real scale, 2,000 partitions of a 1.2 GB shuffle on 32 cores aim at 1,200 / 32 = 37.5 MB, about 32 tasks, or at 64 MB, about 19. That is where the 31 tasks of the refund report came from.
Clue 2: one partition was cut into pieces
The second clue was AQEShuffleRead coalesced and skewed. Lesson 12.4 fixed a skewed join by hand, with salt. For a sort-merge join or a shuffled hash join, AQE can do the cutting itself.
After the shuffle, a partition counts as skewed when it passes two tests:
- it is more than 5 times the median partition, and
- it is more than 256 MB.
A skewed partition is cut into pieces of about a target size: the advisory size, or the average of the normal partitions when that is larger. The cuts follow the map tasks. A piece is the blocks that a run of neighbouring map tasks wrote for this partition, so no piece is smaller than one map task's block.
There is a price. Every piece must still meet all its matches, so the other side's partition is read again for every piece.
Splitting the guest-checkout partition
A sort-merge join of orders and customers over 12 shuffle partitions: partition 2 holds 2,600 MB of guest checkouts, far over five times the 197.5 MB median, so AQE splits it along its 8 map-task blocks and replicates the customers partition for each piece.
Partition 2 holds the guest checkouts of Lesson 12.4: 2,600 MB against a median of 197.5 MB. Watch it split along its 8 map-task blocks. Then lower the skew factor to 4, and partition 5 (900 MB) crosses the 790 MB line too.
Which partitions are skewed, and into how many pieces
import statistics
left = [180, 210, 2600, 195, 170, 900, 190, 220, 185, 175, 200, 215] # MB per partition
blocks = {2: [310, 355, 290, 340, 330, 305, 345, 325], # MB per map task
5: [110, 115, 105, 120, 110, 115, 115, 110]}
def skew_plan(sizes, factor=5, threshold_mb=256, advisory_mb=64):
median = statistics.median(sizes)
limit = max(threshold_mb, factor * median)
normal = [s for s in sizes if s <= limit]
target = max(advisory_mb, sum(normal) / len(normal)) if normal else advisory_mb
return median, limit, [i for i, s in enumerate(sizes) if s > limit], target
def split(blocks, target):
"""Cut along map-task blocks, then merge two neighbours that are small together."""
pieces, current = [], 0
for b in blocks:
if current and current + b > target:
pieces.append(current)
current = 0
current += b
pieces.append(current)
merged = [pieces[0]]
for p in pieces[1:]:
if merged[-1] + p < 1.2 * target or min(merged[-1], p) < 0.2 * target:
merged[-1] += p
else:
merged.append(p)
return merged
for factor in (5, 4):
median, limit, skewed, target = skew_plan(left, factor)
print(f'factor {factor}: median {median}, limit {limit}, target {target:.1f} MB')
for i in skewed:
print(f' partition {i}: {left[i]} MB -> {split(blocks[i], target)}')
The simulator as Python. At factor 5 only partition 2 is skewed. Each of its map blocks is already above the 258.2 MB target, so it becomes 8 pieces, one per map task. At factor 4 partition 5 joins it. Its eight small blocks are merged in pairs into 4 pieces of 225 MB, because two neighbouring pieces that are small together (under 1.2 x the target) become one.
Task sizes before and after the skew split (factor 5)
Bars comparing the slowest task before AQE at 2,620 MB, the median task at 217 MB, the largest piece of the split partition at 375 MB, and the new slowest task, partition 5, at 922 MB.
Each bar is the bytes one task reads from both sides. The split turned 12 tasks into 19 and cut the slowest from 2,620 MB to 922 MB. Lowering the factor to 4 would split partition 5 too.
Clue 3: the join changed its mind
The third clue: explain() promised a SortMergeJoin, and a BroadcastHashJoin ran.
When the shuffle of one join side turns out to be 10 MB or less, AQE plans the join again as a broadcast hash join. The limit is spark.sql.adaptive.autoBroadcastJoinThreshold, by default the same as the static threshold of Lesson 12.4. The classic case is a dimension that a filter cut down to a few MB while the estimate still said 48 MB.
The switch comes late. Both sides have already been shuffled, so it is less efficient than a broadcast planned up front. It still saves both sorts. And each task of the big side reads the shuffle files on its own executor, with no network fetch. In the plan that shows as AQEShuffleRead local.
A sort-merge join becomes a broadcast join
Orders joined to customers filtered to Japan: planned as a sort-merge join because the static estimate was 48 MB, but the customers shuffle wrote only 1.6 MB, so AQE switches to a broadcast hash join and reads the orders shuffle locally.
Press Next step. The plan starts as a sort-merge join because the customers side was estimated at 48 MB. Its shuffle writes 1.6 MB, and AQE switches the join.
The final plan after the switch
Runs on Databricks:
japan = customers.filter("country = 'Japan'")
result = orders.join(japan, "customer_id")
result.write.mode("overwrite").parquet("/Volumes/swiftkart/tmp/japan_orders")
result.explain()
== Physical Plan ==
AdaptiveSparkPlan isFinalPlan=true
+- == Final Plan ==
*(3) Project [...]
+- *(3) BroadcastHashJoin [customer_id#1L], [customer_id#20L], Inner, BuildRight, false
:- AQEShuffleRead local
: +- ShuffleQueryStage 0
: +- Exchange hashpartitioning(customer_id#1L, 200), ENSURE_REQUIREMENTS, [plan_id=310]
: +- *(1) Filter isnotnull(customer_id#1L)
: +- *(1) ColumnarToRow
: +- FileScan parquet swiftkart.orders[...]
+- BroadcastQueryStage 2
+- BroadcastExchange HashedRelationBroadcastMode(List(input[0, bigint, false]),false), [plan_id=345]
+- AQEShuffleRead local
+- ShuffleQueryStage 1
+- Exchange hashpartitioning(customer_id#20L, 200), ENSURE_REQUIREMENTS, [plan_id=321]
+- *(2) Filter (isnotnull(country#24) AND (country#24 = Japan) AND isnotnull(customer_id#20L))
+- ...
+- == Initial Plan ==
SortMergeJoin [customer_id#1L], [customer_id#20L], Inner
...
Shortened Spark 3.5 output, read after the job ran. Compare the top line of the Final Plan with the Initial Plan at the bottom. Query stages 0 and 1 are the two shuffles that had already run. Stage 2 is the broadcast AQE added. On a skewed join the final plan shows SortMergeJoin(skew=true) above AQEShuffleRead coalesced and skewed, and the SQL tab counts "number of skewed partitions" and "number of skewed partition splits".
Remember: AQE measures after each shuffle and plans the rest again. It merges small partitions, splits skewed join partitions and switches small joins to broadcast. It never adds partitions.
A cousin: pruning partitions at runtime
One more runtime trick looks like AQE and is not part of it: dynamic partition pruning, or DPP, on since Spark 3.0.
Picture order lines stored in one folder per order_date, joined to the holiday rows of dim_date. Only the folders of the holiday dates matter. But which dates are holidays is written in the data, so the planner cannot know it while it plans.
So Spark runs the small side first and feeds its result into the scan of the big table as a partition filter. The order lines of every other date are never read.
By default Spark does this only when it can reuse the small side's broadcast, so the pruning is nearly free. It needs a real partition column. A plain data column gets no DPP.
DPP in a plan
Runs on Databricks:
lines = spark.table("swiftkart.order_lines") # partitioned by order_date
holidays = spark.table("swiftkart.dim_date").filter("is_holiday")
lines.join(holidays, lines.order_date == holidays.date).groupBy("date").sum("amount").explain()
...
:- FileScan parquet swiftkart.order_lines[amount#9,order_date#12] ..., PartitionFilters: [isnotnull(order_date#12), dynamicpruningexpression(order_date#12 IN dynamicpruning#88)], ...
: +- SubqueryBroadcast dynamicpruning#88, 0, [date#40], [plan_id=120]
: +- BroadcastExchange HashedRelationBroadcastMode(List(input[0, date, true]),false), [plan_id=119]
...
Shortened. Look inside PartitionFilters: the dynamicpruningexpression is the filter Spark added. dynamicpruning#88 is filled at runtime from the broadcast of the filtered dates. In the SQL tab, the scan's "number of partitions read" drops from every date to the dozen holidays.
Date folders read by the holiday query
Two bars: without dynamic partition pruning the scan reads all 365 date folders of a year, with it only the 12 folders of the holiday dates.
Made-up numbers: one year of date folders and a dozen holidays. The join returns the same rows either way. DPP only changes how many folders are opened to find them.
The trap: "AQE will sort it out". AQE cannot fix what it cannot see or reach. It only merges partitions, so a spark.sql.shuffle.partitions set too low stays too low: give it a generous starting number. Its skew handling is for joins, not for a skewed groupBy or window (salt those, Lesson 12.4), and not for the side of an outer join that must be kept whole. It does nothing inside the first stage, such as one gzip file. And it can only switch a join after both shuffles have run.
Numbers to remember
| Setting or rule | Default | What it does |
|---|---|---|
| spark.sql.adaptive.enabled | true (since 3.2) | The umbrella switch |
| ...coalescePartitions.enabled | true | Merge small neighbouring shuffle partitions |
| ...coalescePartitions.parallelismFirst | true | Keep about one task per core and ignore the advisory size. The docs recommend false on a busy cluster |
| ...advisoryPartitionSizeInBytes | 64 MB | Target for coalescing and for skew splits |
| ...coalescePartitions.minPartitionSize | 1 MB | No coalesced task smaller than this. The full target: max(minPartitionSize, min(advisory size, total / minPartitions)) |
| ...coalescePartitions.initialPartitionNum | spark.sql.shuffle.partitions | Partitions before coalescing: set it high |
| ...skewJoin.enabled | true | Split skewed partitions of sort-merge and shuffled hash joins |
| ...skewJoin.skewedPartitionFactor | 5 | Skewed if over 5 x the median ... |
| ...skewJoin.skewedPartitionThresholdInBytes | 256 MB | ... and over 256 MB |
| Which side may be split | depends on the join type | The left side for inner, cross, left semi, left anti and left outer joins. The right side only for inner, cross and right outer joins |
| ...autoBroadcastJoinThreshold | same as the static 10 MB | Switch a join to broadcast on real sizes. Not used for a side whose partitions are mostly empty (under 20% non-empty, internal) |
| ...localShuffleReader.enabled | true | Read shuffle files locally after a switch |
| ...maxShuffledHashJoinLocalMapThreshold | 0 (off) | When set, AQE can pick a shuffled hash join if every partition is under it |
| spark.sql.optimizer.dynamicPartitionPruning.enabled | true (since 3.0) | Dynamic partition pruning: an optimiser rule, not part of AQE |
| What AQE reads | MapOutputStatistics | The bytes each map task wrote for each reduce partition, from the driver's MapOutputTracker. In a plan: AdaptiveSparkPlan, ShuffleQueryStage, BroadcastQueryStage |
... stands for spark.sql.adaptive..
What changed at SwiftKart
Nothing was broken on that quiet Tuesday. AQE had measured each shuffle and planned the rest again: 31 tasks in place of 2,000, a broadcast where the guess said sort-merge, and one skewed partition cut into pieces.
You still make three small changes, the usual ones on Databricks. You keep a high starting partition count, because AQE can merge partitions and never add them. You switch parallelismFirst off on the shared cluster, so tasks reach a sensible size. And you put a broadcast hint on the small side: a broadcast planned up front avoids the shuffle that an AQE switch has already paid for.
Nora changes one habit for the team: read the plan after the run, in the SQL tab, where it says isFinalPlan=true.
One part of Spark is still closed. Your Python code does not run inside this engine at all. Lesson 12.11 opens that door: Python and the JVM.
In one line
AQE measures every shuffle after it runs and plans the rest again: it merges small partitions, splits skewed join partitions and switches small joins to broadcast, but it never adds partitions and never fixes a skewed groupBy.
Interview corner
How does adaptive query execution work?
AQE wraps the physical plan in AdaptiveSparkPlan and cuts it into query stages at every shuffle and broadcast. It runs the stages whose inputs are ready, reads their map output statistics (bytes per reduce partition) and re-optimises the remaining plan, logically and physically, then submits the next stages. It repeats until the final stage, so the plan you see after the run (isFinalPlan=true) can differ from explain() before it. It is on by default since Spark 3.2.
How does AQE decide how many partitions to coalesce into?
It computes a target of max(minPartitionSize, min(advisoryPartitionSizeInBytes, total / minPartitions)), with 1 MB and 64 MB by default. With parallelismFirst true, the default, minPartitions is the default parallelism, so it keeps about one task per core and ignores 64 MB; with it false the 64 MB target holds. Then it packs contiguous partitions until the next one would pass the target, skips empty ones and never splits a big one. 1.2 GB on 32 cores gives about 32 tasks of 37.5 MB, or about 19 of 64 MB.
Explain AQE's skew join handling and its limits.
After the shuffle, a sort-merge or shuffled hash join partition is skewed if it is over 5 x the median and over 256 MB. AQE splits it into pieces of about max(64 MB, the mean of the non-skewed partitions), along map-task boundaries, and reads the other side's matching partition once per piece; the plan shows SortMergeJoin(skew=true). Limits: only joins, not aggregations or windows; the left side only for inner, semi, anti and left outer joins and the right side only for inner and right outer; and a piece cannot be smaller than one map task's block.
What is the difference between AQE's join switching and dynamic partition pruning?
AQE's switch happens after both join inputs have been shuffled: if one side's real size is under the adaptive broadcast threshold (10 MB by default), it becomes a broadcast hash join, saving the sorts and reading the big side's shuffle files locally. Dynamic partition pruning is an optimiser rule: when a table partitioned on the join key meets a filtered dimension, the dimension's result becomes a runtime partition filter on the fact scan, so whole folders are never read. DPP saves I/O at the source; the AQE switch saves sort and network after the fact.