Adaptive Query Execution: Intermediate
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.
- 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.
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()
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
| Statistic | Where it comes from | Which rewrite uses it |
|---|---|---|
| Bytes per shuffle partition | Block sizes reported by each map task, summed per partition | Coalescing, skew splitting |
| Total data size | The exchange's data size metric | Switching a join to broadcast |
| Row count | Records written by the map tasks | Re-planning, such as dropping a join whose input came back with 0 rows |
Where AQE cannot re-plan
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.
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?
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
| Partition | MB |
|---|---|
| 0 | 20 |
| 1 | 30 |
| 2 | 10 |
| 3 | 50 |
| 4 | 5 |
| 5 | 5 |
| 6 | 40 |
| 7 | 30 |
| 8 | 60 |
| 9 | 8 |
| 10 | 6 |
| 11 | 12 |
| Task | Reads partitions | MB |
|---|---|---|
| 0 | 0 to 2 | 60 |
| 1 | 3 to 5 | 60 |
| 2 | 6 | 40 |
| 3 | 7 | 30 |
| 4 | 8 | 60 |
| 5 | 9 to 11 | 26 |
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.
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.
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.
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.
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?
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.
| Operator | Input |
|---|---|
| SortMergeJoin | both sides |
| Sort | page_views side |
| Exchange | page_views, 800GB |
| Sort | campaigns side |
| Exchange | campaigns, 4GB estimated |
| Operator | Input |
|---|---|
| BroadcastHashJoin | both sides |
| AQEShuffleRead local | page_views shuffle files |
| ShuffleQueryStage | page_views, 800GB |
| BroadcastQueryStage | campaigns, sent to every executor |
| ShuffleQueryStage | campaigns, 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 threshold | Adaptive threshold | Planning-time broadcast | Runtime switch |
|---|---|---|---|
| 10MB | unset | under 10MB estimated | under 10MB measured |
| -1 | unset | never | never |
| -1 | 10MB | never | under 10MB measured |
| 10MB | -1 | under 10MB estimated | never |
- ▸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.
campaigns is 4GB on disk and the filter keeps 3MB of it. With these settings, which join does this program run?
- 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.
- 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
| Task | Regular read fetches | Local read fetches |
|---|---|---|
| 0 | block 0 from M0, M1 (A) and M2, M3 (B) | blocks 0 to 3 from M0, on A |
| 1 | block 1 from M0, M1 (A) and M2, M3 (B) | blocks 0 to 3 from M1, on A |
| 2 | block 2 from M0, M1 (A) and M2, M3 (B) | blocks 0 to 3 from M2, on B |
| 3 | block 3 from M0, M1 (A) and M2, M3 (B) | blocks 0 to 3 from M3, on B |
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.
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?
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.
| Partition | Side's median | 5 x median | Above 256MB? | Skewed? |
|---|---|---|---|---|
| 3.2GB | 40MB | 200MB | yes | yes |
| 180MB | 20MB | 100MB | no | no |
| 300MB | 80MB | 400MB | yes | no |
Splitting a skewed partition by map task
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()
The cost of copying the other side
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 type | Split the left side | Split the right side |
|---|---|---|
| Inner, cross | yes | yes |
| Left outer, left semi, left anti | yes | no |
| Right outer | no | yes |
| Full outer | no | no |
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
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?
> 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.
spark.sql.adaptive.autoBroadcastJoinThreshold, 10MB unless set, is broadcast mid-run: the sorts are saved, the large side's shuffle write is not.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
- 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
- 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
- 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
- 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
- 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