IntermediateSpark · 14 min · 11 challenges

Adaptive Query Execution: Intermediate

On the morning after New Year's Eve at Uber, the nightly Spark job joining trips to pricing events and rider accounts ran on the same code as every other night, but one corporate account had booked a tenth of all trips and a filter shrank the pricing side to a few megabytes. Whether the job finished by breakfast came down to what Spark measured between its stages.

Materialization Points

Daily Life
Interviews
AQE can change a plan only at a materialization point: a moment when a stage has finished and its output is complete, with its size known. Those moments are the exchanges: a shuffle exchange's output is its shuffle files, a broadcast exchange's is a table collected to the driver. Between 2 exchanges the plan is fixed, because nothing finished exists there to measure.

Query stages and the AQE loop

With AQE on, the physical plan sits under an AdaptiveSparkPlan node. Spark cuts that plan at every Exchange into query stages. A query stage below a shuffle exchange is the map side of that shuffle: it reads its input, runs every narrow operation pipelined into a task per partition, and writes shuffle files. A broadcast exchange forms a query stage too, one that collects a small table and sends it to every executor.

The loop the driver runs, once per finished stage
  • Submit every query stage whose inputs are complete.
  • Wait until a running stage finishes.
  • Swap the estimates for that stage for its measured output.
  • Re-run logical and physical planning over the stages not yet started, then apply AQE's own rules: coalescing, the local read, skew splitting.
  • Repeat until the stage that produces the result has run.
TIP
Spark submits the scan stages of both join sides together, and the smaller side usually finishes first. AQE re-plans the moment it does, using measured numbers for the finished side and estimates for the side still running.

The board below plays a sort-merge join followed by a count per country, with broadcasting switched off so both sides shuffle. Count the stages as it runs. The 2 scans each write shuffle files keyed on customer_id. The join stage reads them, counts per country inside each task, and writes a second shuffle keyed on country. A last stage finishes the count. That makes 4 stages and 3 exchanges: 3 moments where output is complete on disk before anything downstream reads it.

spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1)
by_country = orders.join(customers, "customer_id").groupBy("country").count()
by_country.collect()
orders8 rows
order_id
customer_id
amount
1
1
30
2
2
15.5
3
3
42
4
1
8.25
5
4
19.99
6
2
60
7
3
12
8
4
25
customers4 rows
customer_id
country
1
US
2
DE
3
US
4
JP
Preparing the animation

The board draws the plan Spark builds before the job starts. AQE's rewrites are what the rest of this lesson covers, and the board does not show them.

The sizes a finished stage reports

When a map task finishes, it reports to the driver the size of every block it wrote, a block per shuffle partition. When the whole stage finishes, the exchange also holds its totals: the bytes and rows it wrote. Those numbers replace the planner's guesses for that branch of the plan.
StatisticWhere it comes fromWhich rewrite uses it
Bytes per shuffle partitionBlock sizes reported by each map task, summed per partitionCoalescing, skew splitting
Total data sizeThe exchange's data size metricSwitching a join to broadcast
Row countRecords written by the map tasksRe-planning, such as dropping a join whose input came back with 0 rows

Where AQE cannot re-plan

Inside a stage: narrow operations are pipelined into a single task, so nothing finishes between them.
Inside a stage: narrow operations are pipelined into a single task, so nothing finishes between them.
Scan stages before the first exchange: they run on the static plan, since nothing has been measured yet.
Scan stages before the first exchange: they run on the static plan, since nothing has been measured yet.
A stage that has started: its tasks keep the plan they were handed.
A stage that has started: its tasks keep the plan they were handed.
A query with no exchange: a filter and a select over one table form a single stage and give AQE nothing to measure.
A query with no exchange: a filter and a select over one table form a single stage and give AQE nothing to measure.

Call explain() before the action and the top node of the plan reads AdaptiveSparkPlan isFinalPlan=false: that is the starting plan. Call it on the same DataFrame after the action and the node reads isFinalPlan=true, with the final plan printed above the initial one.

Multiple Choice

A job filters events, joins the result to users with a sort-merge join, and writes the output. When can AQE first replace the sort-merge join with a different strategy?

Coalescing Small Partitions

Daily Life
Interviews

Every shuffle in an application starts with the same number of reducers, spark.sql.shuffle.partitions, whether it moves 2TB or 300MB. On the small shuffle that means hundreds of tasks that each spend longer being scheduled than working, and a tiny file per partition if the stage writes its output. Sizing Shuffle Partitions had you pick that count per job. Coalescing picks it per shuffle, from sizes measured after the map stage.

Once the map stage has finished, Spark knows the bytes headed to every reducer. It merges neighbouring partitions until each merged one is near a target size, and the plan records the step as an AQEShuffleRead node labelled coalesced. The switch for it, spark.sql.adaptive.coalescePartitions.enabled, is on by default.

Merging neighbours toward a target

Take a shuffle of 12 partitions holding 276MB on a 4-core cluster, with a target of 64MB. Spark walks the partitions in ID order. It adds the next partition to the current group while the group stays at or under the target, and starts a new group when the next partition would push it over.
Before: 12 shuffle partitions
PartitionMB
020
130
210
350
45
55
640
730
860
98
106
1112
After: 6 coalesced partitions
TaskReads partitionsMB
00 to 260
13 to 560
2640
3730
4860
59 to 1126
Partitions 6 and 7 stay apart because together they would reach 70MB. The task reading partition 7 (30MB) and the task reading partitions 9 to 11 (26MB) would fit in a single 56MB task, but Spark merges only neighbours, so they stay separate.

The merge moves no rows

No row moves to make a coalesced partition. Each map task already wrote a data file with its blocks laid out in partition order, plus an index of where each block starts. A task that reads partitions 0 to 2 asks every map output for blocks 0, 1 and 2, which sit side by side in the file. With spark.sql.adaptive.fetchShuffleBlocksInBatch on, its default, Spark fetches such a run in a single request when the codec allows it. The whole cost of coalescing is the driver adding up block sizes.

Keeping to neighbours is what keeps it cheap: merging partitions 7 and 10 would mean 2 separate reads from every map file. It also keeps joins correct. When a stage reads 2 shuffles, as a sort-merge join does, Spark adds partition i's size across both sides and applies one set of ranges to both, so partition i on the left still meets partition i on the right.

The settings behind the target

The target comes from 3 settings under spark.sql.adaptive.. advisoryPartitionSizeInBytes is the size Spark aims for, coalescePartitions.minPartitionSize is the smallest merged partition it will plan, and coalescePartitions.parallelismFirst decides whether the cluster's core count can lower the target.

64MB
advisoryPartitionSizeInBytes default
1MB
minPartitionSize default
def coalesce_target(total_bytes, cores, parallelism_first=True):
advisory = 64 * 1024 * 1024
minimum = 1024 * 1024
floor_count = cores if parallelism_first else 1
return max(minimum, min(advisory, total_bytes // floor_count))

With parallelismFirst at its default, true, Spark will not plan fewer coalesced partitions than the cluster's default parallelism, normally its total core count, unless that pushes them under the minimum. The 12-partition shuffle holds 276MB on 4 cores: 276 / 4 is 69MB, so the advisory 64MB is smaller and wins. Put a 2,048MB shuffle on 40 cores and 2,048 / 40 is roughly 51MB, so Spark aims at 51MB and plans at least 40 tasks instead of at least 32. Setting parallelismFirst to false makes the advisory size the target, which the Spark configuration docs recommend on a busy shared cluster.

TIP
AQE leaves alone a shuffle whose partition count you gave as a number: repartition(400) keeps 400 partitions. repartition("customer_id") with no number is coalesced like any other shuffle.

Run the cell. Each row is one event_type value, and every row with the same key hashes to the same shuffle partition. Work out how many of the default 200 reducers receive any data, then how many tasks AQE plans for this aggregation.

events = spark.table("user_events")
typed = events.filter(events.event_type.isNotNull())
typed.groupBy("event_type").count().orderBy("count", ascending=False).collect()

Answer: no more reducers than there are rows in the result receive data, and the rest are empty. The whole shuffle is far below the 1MB minimum, so the target is 1MB and every partition merges into a single task.

Multiple Choice

A 200-partition shuffle writes 1,200MB on a 12-core cluster with every AQE setting at its default. What target size does coalescing use?

Switching to Broadcast Mid-Run

Daily Life
Interviews
Joins: Intermediate showed the 10MB threshold deciding a join's strategy at planning time, from Catalyst's estimate. With AQE on, Spark checks a threshold a second time, after a join side's map stage finishes, against the bytes that side actually produced. A side that looked large on paper and measured small is broadcast for the rest of the join.

Why the estimate misses

Without column statistics, Catalyst estimates a filter's output at the full size of its input, and a groupBy from the size of its input, scaled only for the columns it keeps. Both guesses can be off by orders of magnitude. Take a 4GB campaigns table filtered to the active campaigns of one advertiser: the planner sees 4GB, far above 10MB, and plans a sort-merge join against an 800GB page_views table. At runtime the filtered side writes 6MB of shuffle output.

Initial plan, from estimates
OperatorInput
SortMergeJoinboth sides
Sortpage_views side
Exchangepage_views, 800GB
Sortcampaigns side
Exchangecampaigns, 4GB estimated
Final plan, from measurements
OperatorInput
BroadcastHashJoinboth sides
AQEShuffleRead localpage_views shuffle files
ShuffleQueryStagepage_views, 800GB
BroadcastQueryStagecampaigns, sent to every executor
ShuffleQueryStagecampaigns, 6MB measured

Both Sort operators are gone, the small side now goes to every executor, and the large side arrives through a local read, the subject of the next section. The page_views exchange stays. Spark submitted both map stages together, the 6MB side finished first and triggered the re-plan, and the final plan reads the shuffle files the 800GB stage goes on to write.

The threshold that governs the switch

The runtime check reads spark.sql.adaptive.autoBroadcastJoinThreshold, added in Spark 3.2. Left unset, it takes the value of spark.sql.autoBroadcastJoinThreshold, so both checks use 10MB out of the box. The number it compares is the measured data size of that side's shuffle output.

Static thresholdAdaptive thresholdPlanning-time broadcastRuntime switch
10MBunsetunder 10MB estimatedunder 10MB measured
-1unsetnevernever
-110MBneverunder 10MB measured
10MB-1under 10MB estimatednever
The third row suits a team burned by bad estimates: Spark never broadcasts on a guess, yet still broadcasts a side it has measured. The fourth row keeps planning-time broadcasts and stops AQE from adding new ones.
Saved and still paid after a runtime switch
  • ▸Saved: the sort on both sides, which a broadcast hash join does not need.
  • ▸Saved: fetching the large side's blocks over the network, through the local read.
  • ▸Still paid: writing the large side's shuffle files, since the final plan reads them.
  • ▸Still paid: the small side's shuffle, followed by collecting it to the driver and broadcasting it.

That is why a planned broadcast beats a runtime one when you can get it: with good statistics or a broadcast() hint, the large side is never shuffled at all. The runtime switch covers the joins where the estimate was wrong.

Seeing the switch

In the SQL tab, a switched join shows BroadcastHashJoin in the final graph, where explain() before the run showed SortMergeJoin. The Exchange node under the small side shows its data size: compare it with 10MB to see why the switch happened, or why it did not.

Catalyst plans orders.filter(orders.status == "Completed") as if every row survived. Run the cell and work out the share of rows that carry Completed. Then suppose orders is 30MB, so Catalyst estimates the filtered side at 30MB: would the static plan broadcast it, and would AQE?

orders = spark.table("orders")
known = orders.filter(orders.status.isNotNull())
known.groupBy("status").count().collect()

Answer: the static plan sees 30MB and never broadcasts. If under a third of the rows are Completed, the filtered side measures under 10MB and AQE switches the join.

Multiple Choice

campaigns is 4GB on disk and the filter keeps 3MB of it. With these settings, which join does this program run?

spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1)
spark.conf.set("spark.sql.adaptive.autoBroadcastJoinThreshold", "10MB")
active = campaigns.filter(campaigns.status == "active")
result = page_views.join(active, "campaign_id")
result.write.parquet("/out/active_views")

The Local Shuffle Read

Daily Life
Interviews
After a runtime switch, the large side of the join sits in shuffle files, split by hash of the join key across its map tasks' output. A broadcast hash join has no use for that split: every task holds the whole small side, so any slice of the large side can be joined on any executor. The local shuffle read uses that freedom to keep the large side off the network.
✓Regular shuffle read
  • Task i fetches block i from every map output in the cluster.
  • Most of those blocks were written on other executors, so most bytes cross the network.
  • The sort-merge join then sorts each task's input on the join key.
✗Local shuffle read
  • Each task reads blocks written by a single map task.
  • Spark prefers to run the task on the executor that wrote them, so the bytes come off local disk.
  • The task streams its rows past the broadcast hash table, with no sort.

Which blocks each task reads

Take 4 map tasks and 4 reducers on 2 executors: map tasks M0 and M1 ran on executor A, M2 and M3 on executor B. Each map task wrote 4 blocks, a block per reducer partition.
TaskRegular read fetchesLocal read fetches
0block 0 from M0, M1 (A) and M2, M3 (B)blocks 0 to 3 from M0, on A
1block 1 from M0, M1 (A) and M2, M3 (B)blocks 0 to 3 from M1, on A
2block 2 from M0, M1 (A) and M2, M3 (B)blocks 0 to 3 from M2, on B
3block 3 from M0, M1 (A) and M2, M3 (B)blocks 0 to 3 from M3, on B
In the regular read, whichever executor a task runs on, half its blocks live on the other one: 8 of the 16 fetches cross the network. In the local read, each task takes all 4 blocks of a map output from the disk of the executor that wrote them, so 0 of the 16 cross the network, as long as each task runs there. On a cluster of 50 executors, a regular read pulls about 49 of every 50 bytes from another machine.
Real shuffles have more partitions than this. Spark keeps roughly the parallelism the join would have had: if 20 map tasks wrote a 200-partition shuffle, each map output is cut into 10 contiguous ranges of 20 partitions, giving 200 local-read tasks of 20 blocks each.
Multiple Choice

After a runtime switch, 25 map tasks wrote the join's large side into a 200-partition shuffle. How does the local read lay out its tasks?

When Spark keeps the regular read

A local read gives up the hash partitioning of the large side, and sometimes a later step depends on it. Take a join on customer_id followed by groupBy("customer_id"). Under the sort-merge plan, the join's output is already partitioned by customer_id, so the aggregation reuses it with no exchange, as Reusing Shuffle Output showed. A local read would scatter those keys and force a new shuffle. AQE checks for this: when a rewrite would add an exchange the plan did not have, Spark keeps the broadcast join but reads the large side the regular way.

In the SQL tab, a probe side read the local way shows an AQEShuffleRead node labelled local. On the join stage's page, the shuffle read metrics separate remote bytes from the total, and after a local read the remote figure should sit close to 0. The behaviour is controlled by spark.sql.adaptive.localShuffleReader.enabled, which is on by default.

Multiple Choice

The final plan shows a BroadcastHashJoin whose probe side reads straight from a ShuffleQueryStage, with no AQEShuffleRead local node between them, and the join stage's remote shuffle bytes are close to its total shuffle read. What best explains this?

Splitting Skewed Partitions

Daily Life
Interviews
Data Skew: Intermediate fixed hot keys by salting and isolating them in your own code. AQE does a version of the same work inside the join: once both sides' map stages have finished, it knows every join partition's size before a single join task starts, and it can break the straggler into pieces.

The 2 skew tests

A partition on one side of the join counts as skewed when it passes both tests. It must be larger than skewedPartitionFactor times the median partition size on that side, 5 times by default. And it must be larger than skewedPartitionThresholdInBytes, 256MB by default. Both settings sit under spark.sql.adaptive.skewJoin., and spark.sql.adaptive.skewJoin.enabled turns the rule on, as it is by default.

PartitionSide's median5 x medianAbove 256MB?Skewed?
3.2GB40MB200MByesyes
180MB20MB100MBnono
300MB80MB400MByesno
The factor alone would flag a 3MB partition beside a 0.5MB median in a tiny job, where splitting saves nothing. The byte threshold alone would flag every partition of a job that is large everywhere. Requiring both catches partitions that are big in absolute terms and out of line with their neighbours.

Splitting a skewed partition by map task

Partition 17 on the left side is made of blocks, a block from each left-side map task. AQE groups those blocks into contiguous runs of map tasks, each run close to a target size, and gives each run its own task. The target is the larger of the advisory partition size and the average size of that side's non-skewed partitions.
Because the split follows map tasks, a single hot key gets divided too: its rows reached partition 17 from many map tasks, so each run holds a share of them. The smallest piece AQE can make is a single map task's block, so a block that is huge on its own stays whole.

The board plays a sort-merge join in which customer 1 owns 9 of the 12 orders. Watch the task that receives customer 1 after the shuffle: that is the partition AQE would split. The customers block that lands beside it is the one each piece would need a copy of.

spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1)
orders.join(customers, "customer_id").count()
orders12 rows
order_id
customer_id
amount
101
1
20
102
1
35
103
2
12.5
104
1
8
105
1
41
106
3
17
107
1
9.5
108
1
22
109
4
30
110
1
14
111
1
27.5
112
1
11
customers4 rows
customer_id
country
1
US
2
DE
3
FR
4
JP
Preparing the animation

The cost of copying the other side

Each piece of left partition 17 still has to meet every right-side row with the same keys, so every piece reads all of right partition 17. Take a left side of 200 partitions with a 40MB median and a non-skewed average of 40MB, partition 17 at 3.2GB, and a right partition 17 of 30MB. The target is the larger of 64MB and 40MB.
about 50
split tasks for partition 17
about 1.5GB
right-side bytes read for the copies
The slowest task drops from a 3.2GB read to about 64MB plus its copy of the right side. The price is paid in reads of the side that was not split, and it multiplies when both sides are skewed on the same partition: a left split into 4 and a right split into 3 run as 12 tasks, one for every pairing.
Multiple Choice

A sort-merge join's left side has 200 partitions with a 30MB median and a 30MB average outside one partition of 900MB. The matching right partition is 20MB, and every setting is at its default. What does AQE do with the 900MB partition?

Which joins can be split

Join typeSplit the left sideSplit the right side
Inner, crossyesyes
Left outer, left semi, left antiyesno
Right outernoyes
Full outernono

A left outer join emits a null-filled row for each left row with no match. If the right side were split, a left row would find its match in one piece and miss it in the others, producing null rows that should not exist. A groupBy on a hot key gets no help from this rule at all: it splits join partitions only. In the SQL tab, a split join shows as SortMergeJoin(skew=true), and the AQEShuffleRead above it reports the number of skewed partitions and the splits made from them.

Run the cell for the heaviest user_id values in user_events, with row counts standing in for bytes. The skew test compares partitions, and each of 200 partitions holds every key hashed into it. Change the last line to known.count() for the total: the hot key's partition holds its rows plus about total / 200, the median partition about total / 200. Is the first over 5 times the second? A real partition would also need to clear 256MB.

events = spark.table("user_events")
known = events.filter(events.user_id.isNotNull())
known.groupBy("user_id").count().orderBy("count", ascending=False).limit(5).collect()

Capstone: reading a whole run

This question draws on every section: what each finished stage measured, and which rewrite that triggered.
Multiple Choice

A nightly job's final plan contains an AQEShuffleRead labelled coalesced above one exchange, a BroadcastHashJoin whose probe side reads through AQEShuffleRead local, and a SortMergeJoin(skew=true). Which statement about this run holds?

PUTTING IT ALL TOGETHER

> Back to the morning after New Year's Eve at Uber. The nightly job joins trips to pricing events on city_id, joins trips to a large rider accounts table on account_id, then aggregates fares per rider. The pricing side, filtered to the night's surge windows, measures 4MB after its map stage, under 10MB, so AQE swaps the planned sort-merge join for a broadcast and reads the trip shuffle files locally. In the accounts join, the corporate account's partition on the trips side comes back at 2.4GB against a 35MB median: over 5 times the median and over 256MB, so AQE splits it into pieces near 64MB, each reading its own copy of the matching accounts partition. The per-rider aggregation then shuffles 900MB across 200 partitions on a 30-core cluster: 900 / 30 is 30MB, under 64MB, so coalescing aims at 30MB and plans at least 30 tasks.

Every decision waited for a materialization point: the broadcast switch for the pricing side's map stage, the skew split and the coalescing for the map stages feeding their join and aggregation.
The broadcast switch and the local read are one move in 2 parts: the switch frees the trips side from its hash partitioning, and the read layout turns that into local disk reads.
Coalescing and skew splitting are opposite answers to one measurement, bytes per shuffle partition: too small merges neighbours, too large splits by map task.
Each rewrite works on shuffle files already written, which is why AQE costs so little and why it cannot take back a shuffle write the static plan already paid for.
KEY TAKEAWAYS
AQE re-plans only at exchanges, after a query stage has written its full output. Inside a stage and before the first exchange, the static plan runs.
A finished stage hands AQE the bytes in each shuffle partition, plus the total data size and row count of its output.
Coalescing merges neighbouring shuffle partitions toward max(1MB, min(64MB, total bytes / cores)), and costs only the driver's arithmetic because no row moves.
A join side measuring under spark.sql.adaptive.autoBroadcastJoinThreshold, 10MB unless set, is broadcast mid-run: the sorts are saved, the large side's shuffle write is not.
The local shuffle read lets each task read a single map output from local disk, unless losing the hash partitioning would add a shuffle.
A join partition is split when it is over 5 times its side's median and over 256MB, and the other side's matching partition is read once per piece.

Where AQE re-plans a running job, and the 3 rewrites it makes there: coalesce, switch to broadcast, split skew.

Category
Spark
Difficulty
intermediate
Duration
14 minutes
Challenges
11 hands-on challenges

Topics covered: Materialization Points, Coalescing Small Partitions, Switching to Broadcast Mid-Run, The Local Shuffle Read, Splitting Skewed Partitions

Lesson Sections

  1. Materialization Points

    AQE can change a plan only at a materialization point: a moment when a stage has finished and its output is complete, with its size known. Those moments are the exchanges: a shuffle exchange's output is its shuffle files, a broadcast exchange's is a table collected to the driver. Between 2 exchanges the plan is fixed, because nothing finished exists there to measure. Query stages and the AQE loop The board draws the plan Spark builds before the job starts. AQE's rewrites are what the rest of thi

  2. Coalescing Small Partitions

    Merging neighbours toward a target Take a shuffle of 12 partitions holding 276MB on a 4-core cluster, with a target of 64MB. Spark walks the partitions in ID order. It adds the next partition to the current group while the group stays at or under the target, and starts a new group when the next partition would push it over. Partitions 6 and 7 stay apart because together they would reach 70MB. The task reading partition 7 (30MB) and the task reading partitions 9 to 11 (26MB) would fit in a single

  3. Switching to Broadcast Mid-Run

    Joins: Intermediate showed the 10MB threshold deciding a join's strategy at planning time, from Catalyst's estimate. With AQE on, Spark checks a threshold a second time, after a join side's map stage finishes, against the bytes that side actually produced. A side that looked large on paper and measured small is broadcast for the rest of the join. Why the estimate misses The threshold that governs the switch The third row suits a team burned by bad estimates: Spark never broadcasts on a guess, ye

  4. The Local Shuffle Read

    After a runtime switch, the large side of the join sits in shuffle files, split by hash of the join key across its map tasks' output. A broadcast hash join has no use for that split: every task holds the whole small side, so any slice of the large side can be joined on any executor. The local shuffle read uses that freedom to keep the large side off the network. Which blocks each task reads Take 4 map tasks and 4 reducers on 2 executors: map tasks M0 and M1 ran on executor A, M2 and M3 on execut

  5. Splitting Skewed Partitions

    Data Skew: Intermediate fixed hot keys by salting and isolating them in your own code. AQE does a version of the same work inside the join: once both sides' map stages have finished, it knows every join partition's size before a single join task starts, and it can break the straggler into pieces. The 2 skew tests The factor alone would flag a 3MB partition beside a 0.5MB median in a tiny job, where splitting saves nothing. The byte threshold alone would flag every partition of a job that is larg