Adaptive Query Execution: Beginner
Here is the job in code, reading 2 tables and joining on title_id:
The views files hold 800GB. The titles files hold 2GB, and the filter keeps 40 of their 300,000 rows. You know those last numbers because you know the catalog. The driver knows only what storage and the code tell it.
What the driver knows when it plans
| Decision | Input the driver uses | At plan time | Once data flows |
|---|---|---|---|
| Join strategy | Estimated size of `new_titles` against the 10MB broadcast threshold | About 2GB: sort-merge join, both sides shuffled | 48KB: small enough to broadcast |
| Reduce partitions | `spark.sql.shuffle.partitions` | 200 for every shuffle in the job | One side holds 800GB, the other 48KB |
| Rows per key | Nothing: the plan treats keys as evenly spread | Unknown | A hit title can hold far more views than the rest |
The first row decides most of the cost. Spark's default estimate for a filter's output is the estimate for its input: with no statistics collected on the table, the driver cannot know how many rows match without reading them. So new_titles is planned as a 2GB table, far over the threshold, and Spark picks a sort-merge join. That means hashing all 800GB of views across the network by title_id, sorting both sides, and merging them, to match against 40 rows that could have been copied to every executor.
The optimizer did its part well: the filter runs right after the scan of titles, where it belongs. What it lacks is information, because every rewrite and strategy choice happens on the driver before that scan has returned a row.
joined.explain() with adaptive execution off and the physical plan shows SortMergeJoin with an Exchange beneath each side. That text is every decision the job will run with.The plan, played on small data
spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1)new_titles = titles.filter(titles.is_new == 1)joined = views.join(new_titles, "title_id")joined.collect()
All 10 view rows are hashed by title_id and moved, and 3 of them find a match. Scale that to 800GB and the shuffle moves every view of every title to serve a join against 40 titles.
- ▸Counting the rows a filter keeps means running the filter, and running it is the job.
- ▸File sizes come free from storage, so they become the estimate.
- ▸Map tasks split their output by the reduce partition count, so the count is set before they write.
The countries files are 3GB on disk, the filter keeps 27 rows, no table statistics have been collected, and adaptive execution is off. Which join does Spark plan, and why?
Each piece runs until its shuffle output is written; the measured sizes go to the driver, which re-plans the remaining work and launches the next piece. The piece with no shuffle left returns the result.
The running job, re-planned
| Moment | What the driver knows | What it decides |
|---|---|---|
| Action called | File sizes, with `new_titles` estimated at about 2GB | Sort-merge join over 200 reduce partitions |
| Titles shuffle written | `new_titles` measured at 48KB | Re-plan: broadcast those 48KB to every executor |
| Views shuffle written | 800GB, and the size of each of its 200 blocks | Read each views block where it was written and join it to the broadcast copy, with no sort |
| Join finishes | Rows written to the output | Nothing is left to re-plan |
What a re-plan can change
All 4 changes rework the reduce side of a shuffle. None alters what the map tasks before it read or computed.
- Join strategy for a join fed by a shuffle
- How many partitions each shuffle is read as
- How an oversized join partition is divided
- How input files are read and split into partitions
- Filters and column choices from Catalyst's rewrite
- Any shuffle write that has already started
With AQE on, at which point can Spark first use a measured size to change how this job runs?
| Version | First released | Default of spark.sql.adaptive.enabled |
|---|---|---|
| 3.0 | June 2020 | `false` |
| 3.1 | March 2021 | `false` |
| 3.2 | October 2021 | `true` |
| 3.3 and later | June 2022 onward | `true` |
3 checks, from broadest to most specific
spark.conf.get returns the value in force for your session after every config file and launch option has been applied, so its answer is the one that counts. Code can also change the flag mid-session, and the next query Spark plans picks up the new value:
The third check reads a plan. Call explain() on a DataFrame whose query contains a shuffle, and with AQE on, the line under the physical plan header is AdaptiveSparkPlan isFinalPlan=false. The false marks the starting plan, built from estimates and open to change once the job runs.
One case catches people out. A query with no shuffle and no subquery, such as a filter followed by a write, prints no AdaptiveSparkPlan line even with the flag on. Spark leaves AQE out of such a plan because no measurement could ever arrive while there was work left to change. On a query like that, the missing node says nothing about the flag.
Set the flag to false in the same session and run that explain() again: the AdaptiveSparkPlan line is gone, and what remains is a static plan that will run exactly as printed.
- ▸
spark.version: which default applies when nobody set the flag - ▸
spark.conf.get: the value this session uses for its next query - ▸
explain(): whether this particular query was planned adaptively
What the flip changed for existing jobs
When a cluster moves from 3.1 to 3.2 or later, jobs nobody edited start running adaptively. The difference often shows up in output files. A job that wrote right after a groupBy used to write up to 200 files, a file for each reduce partition, with default settings. After the upgrade it can write far fewer, because AQE merged small partitions before the write. Anything downstream that counted on the old file count sees a change it never asked for.
A cluster runs Spark 3.1, nobody has set any adaptive setting, and your job groups a large table by customer. What happens to the job's reduce partition count?
print lines before anything else. Knowing the version and the flag up front explains plan differences that would otherwise look like changes in the data.explain() before the action shows the plan Spark starts with. With AQE on, the plan that ran can differ, and the place to see it is the Spark UI: a web page the driver serves while the application runs, on port 4040 by default. Its SQL tab, labeled SQL / DataFrame in newer releases, lists a row for each query the application has run.
Click a query's description and its page opens on a graph of the physical plan: a box for each plan node, each showing metrics its tasks reported, such as rows output and data size. Below the graph, a Details link expands the same plan as text. For an adaptive query that text starts with the AdaptiveSparkPlan node, and its flag tells you which version you are reading.
| isFinalPlan | When you see it | What the graph shows |
|---|---|---|
| `false` | While the query runs | The plan as it stands: the starting plan plus any re-plans so far |
| `true` | After the query finishes | The plan that produced the result |
Open the page while a long query runs and reload it after a shuffle finishes: the graph is redrawn with the re-planned nodes, while the header reads false until the last piece completes.
The nodes AQE leaves behind
| Node in the final plan | What happened while the query ran |
|---|---|
| `ShuffleQueryStage` | A shuffle ran and was measured; every re-plan after it used its sizes |
| `AQEShuffleRead coalesced` | Small reduce partitions were merged; its number of partitions metric is the count of tasks that read the shuffle |
| `AQEShuffleRead skewed` | An oversized join partition was split across several tasks |
| `AQEShuffleRead local` | Shuffle output was read on the executor that wrote it, usually after a join switched to broadcast |
| `BroadcastHashJoin` above a `ShuffleQueryStage` | A join planned as sort-merge became a broadcast once a shuffle measured one side small |
On Spark 3.0 and 3.1 the read node is named CustomShuffleReader; Spark 3.2 renamed it AQEShuffleRead.
The Exchange beneath a coalesced read still says 200 in its plan text, because every map task wrote 200 blocks. The number of partitions on the AQEShuffleRead box is the count of reduce tasks that actually ran. When those 2 numbers differ, AQE merged partitions at runtime.
The running job, before and after
| Node | Under it |
|---|---|
| SortMergeJoin | a Sort on each side |
| Sort | views Exchange |
| Exchange hashpartitioning(title_id, 200) | views scan |
| Sort | titles Exchange |
| Exchange hashpartitioning(title_id, 200) | titles scan and filter |
| Node | Under it |
|---|---|
| BroadcastHashJoin | views read locally, titles broadcast |
| AQEShuffleRead local | views ShuffleQueryStage |
| ShuffleQueryStage | views Exchange, 800GB written |
| BroadcastQueryStage | titles BroadcastExchange |
| ShuffleQueryStage | titles Exchange, 48KB written |
Read both tables from the top. The join node changed name, both Sort nodes are gone, and each Exchange now sits inside a ShuffleQueryStage. The header's flag moving from false to true confirms that the right-hand table is the plan that ran. The views Exchange survives because its 800GB write happened anyway.
- Open the SQL tab and click the query whose duration matches the slow job.
- Expand Details and check that the header reads AdaptiveSparkPlan isFinalPlan=true.
- In the graph, find each AQEShuffleRead box and read its number of partitions.
- Compare join nodes with explain() output from before the run; a new join name is a runtime switch.
- ▸The query had no shuffle and no subquery, so no
AdaptiveSparkPlannode appears at all. - ▸The flag was off for that session, which
spark.conf.getconfirms. - ▸AQE ran and measured, and every measurement agreed with the starting plan.
collect() returns, calling explain() on the same DataFrame prints isFinalPlan=true, with the final plan above the initial one, so you can compare them without opening the UI.A finished query's plan text contains AdaptiveSparkPlan, HashAggregate, AQEShuffleRead coalesced and Exchange hashpartitioning(customer_id, 200). Which node records a decision Spark made while the query ran?
- Exists before any task runs
- Built from file sizes, default rules and collected statistics
- Blind to what a filter keeps and how keys are spread
- Can keep a table from being shuffled at all, because it decides first
- Exists only once a shuffle has written
- Measured bytes for every reduce partition, and rows for the whole shuffle
- Close to exact for the data this run produced, far closer than any estimate
- Can change only the work that has not yet started
Giving the estimate better information
| Decision | Who has authority | Why |
|---|---|---|
| How input files split into partitions | File sizes from storage | Known before the read, and exact |
| Whether a large table gets shuffled at all | The estimate, or your hint | It is decided before anything can be measured |
| Reduce partition count after a shuffle | Measurement | Exact bytes per partition exist by then |
| Join strategy once the small side has shuffled | Measurement | The measured size replaces the estimate |
| Splitting a hot key's join partition | Measurement | Only the written sizes reveal which partition is huge |
Measure it yourself
Spark's default estimate for orders.filter(orders.status == 'Completed') is every row in orders. Run the cell to see how many rows each status actually holds. The planner works from the full table, so it never sees the gap between those counts and the total.
orders = spark.table("orders")
by_status = (
orders.filter(orders.status.isNotNull())
.groupBy("status")
.count()
.orderBy("count", ascending=False)
)
by_status.collect()The groupBy moves rows by status, and its shuffle write reports the real split. The orderBy adds a second shuffle, over only the handful of grouped rows. Those written sizes are the numbers AQE works from on a real job: exact, and available only after the work that produced them.
- Leave AQE on, and confirm it with spark.conf.get on each new cluster
- Read the final plan in the SQL tab before tuning a slow query
- Hint a broadcast only for a side that stays small on every run
- Treat explain() output from before the run as the plan that ran
- Expect AQE to take back a shuffle write that already started
- Tune spark.sql.shuffle.partitions for a job before checking its coalesced read
A filter keeps 5MB of a 50GB table, which is then joined to a 2TB table. There is no hint and no table statistics, and AQE is on. What is the best outcome Spark can reach?
Capstone: reading a plan that did not change
A colleague's Spark 3.4 job joins clicks to a filtered campaigns table. explain() before the run showed SortMergeJoin under AdaptiveSparkPlan, and the finished plan in the SQL tab still shows SortMergeJoin. The filtered side's shuffle wrote 900MB. What explains the final plan?
> A streaming service's nightly report joins every play event from the last day to the titles released that week, then groups minutes watched by title and writes the result. After the cluster is upgraded from Spark 3.1 to 3.4, the job finishes faster and writes far fewer files, and an engineer has to explain both changes to the team that reads the output.
isFinalPlan=true, a BroadcastHashJoin above a ShuffleQueryStage, and an AQEShuffleRead coalesced box whose partition count is close to the new file count.spark.conf.get("spark.sql.adaptive.enabled") gives the value your session uses.isFinalPlan=true marks the plan that ran, and an AQEShuffleRead node or a changed join name marks a runtime change.Spark plans a query before it sees the data; adaptive execution re-plans with real numbers mid-run.
- Category
- Spark
- Difficulty
- beginner
- Duration
- 12 minutes
- Challenges
- 11 hands-on challenges
Topics covered: The Static-Plan Problem, Re-Optimizing Mid-Run, On by Default Since Spark 3.2, Seeing AQE in the Spark UI, Measurements over Estimates
Lesson Sections
- The Static-Plan Problem
When an action runs, the driver turns your DataFrame code into a physical plan: which join strategy to use, where each shuffle goes, and how many partitions each shuffle produces. Without adaptive execution that plan is final. It is fixed in full before the first task starts, so every choice in it rests on what the driver can learn without reading any data. What the driver knows when it plans The second row is quieter. One setting fixes the reduce partition count for every shuffle in the job, an
- Re-Optimizing Mid-Run (concepts: Adaptive Query Execution)
Adaptive Query Execution, AQE for short, changes when the plan becomes final. Spark still builds a full plan from estimates when the action runs, then executes it in pieces cut at the shuffles. Once the tasks before a shuffle finish writing their output, Spark holds exact sizes for that output. It feeds those sizes back to the optimizer and re-plans everything downstream that has not started. The sizes come from the shuffle write itself. Each map task splits its output into a block for each redu
- On by Default Since Spark 3.2 (concepts: Adaptive Query Execution)
AQE shipped in Spark 3.0 behind a flag that defaulted to off, and Spark 3.2 flipped that default to on. Every release since, including the 4.x line, has kept it. On any cluster running 3.2 or later, queries are adaptive unless someone has turned the flag off. That default is where the value starts. A cluster's config files, the command that launched the job, or code in the session can each set the flag, and a platform team that once hit an AQE problem may have switched it off for every job. The
- Seeing AQE in the Spark UI (concepts: Adaptive Query Execution)
The nodes AQE leaves behind On Spark 3.0 and 3.1 the read node is named CustomShuffleReader; Spark 3.2 renamed it AQEShuffleRead. The running job, before and after
- Measurements over Estimates (concepts: Adaptive Query Execution)
An estimate and a measurement answer the same question, how much data is here, from opposite ends of the run. The estimate is computed on the driver before any task starts, from file sizes, default rules such as a filter keeping every row, and table statistics if someone collected them. The measurement is counted by the tasks that wrote the data, after they wrote it. The last line in each column is where the 2 differ most. A measurement comes from the data this run wrote, so for every decision d