Adaptive Query Execution: Beginner
What the planner can see before a run
| Decision in the plan | Size it depends on | What Spark has before the run |
|---|---|---|
| Broadcast or shuffle a join | Each side after its filters | File size before the filters |
| Partitions after a shuffle | Bytes the shuffle will write | A fixed setting, 200 by default |
| Whether one key overloads a task | Rows per key | Nothing |
One filter, a 700x error
Take a streaming service with 2 tables. views holds one row per viewing session and takes 400GB. titles holds the full metadata record for every title and takes 2GB. The request is total watch time for new releases only, so the job filters titles to is_new == 1 and joins what is left to views. The new releases come to 3MB.
Spark has no access to that 3MB figure while planning. By default, its estimate for a filter's output is the size of the filter's input, so it carries 2GB forward, roughly 700x the real figure. A broadcast needs the small side under spark.sql.autoBroadcastJoinThreshold, which is 10MB unless someone has changed it. 2GB fails that test by a wide margin. The plan shuffles both sides, and all 400GB of views crosses the network to meet 3MB of titles.
The animation below runs a miniature of that job: 10 views rows and 6 titles rows, of which 2 are new. Tables this small would be broadcast automatically, so the first line switches automatic broadcasting off to reproduce the plan that the wrong estimate produces at full size. Watch the shuffle. Every views row moves, and 7 of the 10 belong to titles the filter had already removed.
spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1)new_titles = titles.filter(titles.is_new == 1)joined = views.join(new_titles, "title_id")joined.collect()
The result is 3 rows. A plan holding the right size would have sent the 2 new titles to every task and left views where it was. The next animation is that plan, written the way engineers patched this problem by hand for years: a broadcast hint on the side they knew was small.
new_titles = titles.filter(titles.is_new == 1)joined = views.join(F.broadcast(new_titles), "title_id")joined.collect()
A hand-written hint ages badly
The hint works: no views row changes task, and the same 3 rows come back. It is also frozen at what its author knew on the day they wrote it. Suppose a catalog import next quarter marks 40,000 titles as new. The hinted side has stopped being small, yet the hint still forces a broadcast, and a broadcast that large can exhaust executor memory. A partition count tuned by hand for last year's volume ages the same way.
Measure one yourself
The practice data makes the point at small scale. Before you run the cell, guess what share of orders has the status Completed. Then run it, and change the last line to orders.count() to see the total. Your guess is what a planner has. The number on screen is what only a run can give.
completed = orders.filter(orders.status == "Completed")
completed.count()Whatever count came back, the planner never had it. Planning that filter, Spark carried forward the size of all of orders, because a filter's estimated output equals its input.
A job joins a 300GB clicks table to campaigns, which takes 5GB on disk. Before the join, campaigns is filtered to one advertiser, which leaves 1MB. Spark has file sizes and no other statistics. What does the plan written before the run do with the join?
The middle 3 steps repeat at every shuffle in the query, so a job with 3 shuffles can be measured and re-planned up to 3 times.
The new-releases join, run adaptively
Run the streaming job again with AQE on. The opening plan is unchanged, since the estimate is unchanged: Spark still believes the filtered titles side is 2GB and still plans to shuffle both tables. The difference appears at the first pause.
| Moment | What Spark does | Size it holds for the new titles |
|---|---|---|
| Action is called | Plans a shuffle join from the estimate | 2GB, predicted |
| Shuffle writes finish | Reads the sizes the tasks reported | 3MB, measured |
| Re-plan | Rewrites the join as a broadcast of the new titles | 3MB, under the 10MB threshold |
| Remaining tasks | Run the rewritten join | 3MB, held in memory on each executor |
The repair is partial, because AQE can re-plan only the work that has not run. The shuffle writes that produced the measurement are already paid for, including the pass that wrote the views rows out. What the rewrite saves is the work the shuffle join still had ahead of it: sorting 400GB by title_id and merging it against the other side. A broadcast join needs neither.
The sizes behind 3 problems you know
A re-plan leaves the results and your code alone
With AQE on, at which moment does Spark first hold a measured size for one side of a shuffle join?
| Spark version | Adaptive execution | Default |
|---|---|---|
| Before 3.0 | A narrower predecessor | Off |
| 3.0 and 3.1 | AQE as taught here | Off |
| 3.2 and later | AQE as taught here | On |
One flag, and how to read it
The switch is a single setting, spark.sql.adaptive.enabled. The default describes a fresh cluster. It says nothing certain about the cluster in front of you, where a platform team, a launch script or a line in an old notebook may have set the flag either way. The reliable habit is to ask the running session.
spark.conf.get reports the value in effect for this session after every layer of configuration has been applied: the cluster's defaults, the settings passed when the application was launched, and anything the session's own code has set. That makes it the one check that behaves the same on a laptop, in a shared notebook and on a production cluster.
The answer comes back as text
The call returns the text true or false, as a Python string. Python treats every non-empty string as truthy, so a bare if on the result passes even when AQE is off. Compare against the string when a script needs to branch on it.
Queries the default covers
- DataFrame and SQL queries with a shuffleAdaptiveThey pass through the optimizer, which is where the re-planning happens.
- RDD codeNot coveredAn RDD pipeline bypasses the optimizer, so Spark holds no plan it could rewrite.
- Queries built only from narrow transformationsNothing to adaptWith no shuffle there is no pause, and nothing gets measured.
- The same code on Spark 3.0 or 3.1Off until setThe feature is present and waits for someone to set the flag to true.
The flag is a session setting, so it can change while an application runs. spark.conf.set("spark.sql.adaptive.enabled", "false") turns it off for the queries that follow in that session, and setting it to "true" turns it back on. At this stage the one good use for the off position is comparison: run a query both ways and see what the measurements changed. Otherwise leave it on.
When the 5-second check is worth running
2 situations make the check worth doing every time. One is inheriting a job. A pipeline written for Spark 2.4 and migrated forward may carry an explicit false that someone added during the move, and nobody has revisited it since. The other is benchmarking. A timing comparison between 2 clusters means little if one runs adaptively and the other follows a fixed plan.
A notebook on a Spark 3.4 cluster runs this cell, and it prints AQE is on. A teammate says the output proves AQE is enabled. Is the teammate right?
| Step | Where to click | What to read |
|---|---|---|
| 1 | The SQL / DataFrame tab | The row for your query, found by its description and duration |
| 2 | The query's description link | The plan drawn as a graph of boxes |
| 3 | Details, below the graph | The same plan as text, root node first |
| 4 | The first line of that text | `AdaptiveSparkPlan` and its `isFinalPlan` value |
The root node says whether the plan is settled
When AQE handles a query, the root of its plan is a node named AdaptiveSparkPlan, and that node carries one field, isFinalPlan. While the query is running the field reads false: Spark may still rewrite what has not run, and the page updates as it does. Once the query finishes it reads true, and the text under Details splits into 2 labelled parts, == Final Plan == and == Initial Plan ==.
| What to compare | Initial Plan | Final Plan |
|---|---|---|
| Join node | `SortMergeJoin` | `BroadcastHashJoin` |
| Sort nodes under the join | 2, one per side | None |
| Nodes ending in `QueryStage` | None | One at each measured pause |
| Nodes starting with `AQE` | None | `AQEShuffleRead` |
SortMergeJoin is the plan's name for the shuffle join Spark chose from its 2GB estimate. BroadcastHashJoin is the broadcast it switched to once the new titles measured 3MB. A different operator at the same position in the tree is how a runtime change shows up in the plan.
- A changed operatorA decision reversedThe node at one position has a different name in each plan, as the join does above.
- A node starting with AQEAdded during the runIt never appears in an Initial Plan. It marks a place where Spark adjusted how shuffle output is read.
- A node ending in QueryStageA measurement, with or without a changeA shuffle or broadcast where Spark paused and measured. Every adaptive Final Plan has these, so on their own they say nothing about a change.
On Spark 3.0 and 3.1 the AQEShuffleRead node is printed as CustomShuffleReader.
The same check from code
explain() prints the same plan that the UI draws. Called before the action, it shows the Initial Plan under isFinalPlan=false, a draft that can mislead you about what will run. Called on the same DataFrame after collect(), it shows both plans. count() and show() build a separate plan of their own and run that, so they leave this DataFrame's plan marked as a draft.
A plan with no AdaptiveSparkPlan root
2 situations produce a plan without that root node. In one, the flag is false. In the other, the query is built only from narrow transformations, a filter followed by a select for example, so it has no shuffle to pause at. Either way, the plan on the page is the only plan there was.
A finished query's Details begin with AdaptiveSparkPlan isFinalPlan=true. The join node is SortMergeJoin in the Initial Plan and in the Final Plan. What does that tell you?
The routine has 3 moves: find the root, read isFinalPlan, then put the join node of each plan next to the other. Do it on a few of your own queries while nothing is wrong, so the layout is familiar on the day a run is slow.
An estimate drifts with each operation
| Point in the query | What the estimate assumes | How far off it can be |
|---|---|---|
| Scan of a table | The bytes of its files | Usually close |
| After a filter | The filter keeps every row | About 700x in the new-releases job |
| After a join | A formula over the input sizes | Any amount, when keys repeat |
| After another join | The previous guess, fed forward | The earlier errors, multiplied |
The decisions each one makes
- Everything up to the first finished shuffle, including how each table is scanned
- Whether the first join starts out as a broadcast or as a shuffle
- The entire plan of a query that has no shuffle
- The entire plan whenever the AQE flag is false
- The strategy of any join fed by a shuffle that has finished
- How a finished shuffle's output is divided among the tasks reading it
- Each later re-plan, which uses the newest sizes available
- Only the work downstream of a shuffle, never the work before it
A good estimate still saves a shuffle
In the new-releases job, the correction arrived after views and titles had each written their shuffle output. Had the first plan been right, views would never have been shuffled. A hint keeps that value on an adaptive cluster for a side that is small by construction yet estimated large: a 3GB stores table filtered to the 5 stores one team owns always leaves a few rows, while the estimate stays at 3GB. Only the hint spares the big side its shuffle. A 50-row lookup needs no hint, since its files already sit under 10MB. A table that is small only on today's data is better left to the measurement.
- Leave AQE on, so measured sizes can correct join and partition choices after each shuffle
- Hint a broadcast for a side always small after its filter yet estimated large before the run
- Compare the Initial Plan with the Final Plan when a run is slow
- Treat the plan printed before a run as the plan that ran
- Expect AQE to change a query with no shuffle, where nothing is ever measured
- Count a corrected plan as free: the shuffle that supplied the sizes was still paid for
Predict, run, compare
The cell below is the measuring half of that habit on the practice data. Guess the row count of the join before you run it. Nothing in the file sizes of orders or order_items would have told you the answer.
completed = orders.filter(orders.status == "Completed")
joined = completed.join(order_items, "order_id")
joined.count()A query filters a 50GB table, selects 3 columns and writes the result to storage. AQE is on. Which statement about its plan is right?
> A grocery delivery company runs a nightly Spark job that joins 600GB of order lines to a 4GB promotions table, filtered to the promotions active that day. On a normal night the filter leaves 2MB. In the week of a holiday sale it leaves 1.5GB. The team once hard-coded a broadcast hint, which failed in sale week, and now wants one job that is right on both kinds of night.
promotions side every night, because a filter's predicted output equals its input, so the opening plan is always a shuffle join.spark.conf.get("spark.sql.adaptive.enabled") returns true, so removing the hint was the only code change.BroadcastHashJoin where the Initial Plan shows SortMergeJoin. In sale week both plans show SortMergeJoin, which means the measurement confirmed the shuffle join.spark.sql.adaptive.enabled is true by default from Spark 3.2. spark.conf.get returns the value in effect for the session, as a string.AdaptiveSparkPlan isFinalPlan=true marks a settled plan. The operator that differs between the Initial Plan and the Final Plan is the runtime change.How Spark checks its size guesses against real shuffle output and rewrites the rest of a running query.
- 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
Spark writes the whole plan for a query at the moment you call an action. At that moment no task has run and no row has been read. Every choice in the plan that depends on how big something is has to be made from a prediction of that size, and 2 of the most expensive choices are of exactly that kind: the join strategy and the number of partitions after a shuffle. What the planner can see before a run Before a run, Spark can look at metadata: the names and types of the columns, and how many bytes
- Re-Optimizing Mid-Run (concepts: Adaptive Query Execution)
A shuffle forces a pause into every job that contains one. Each task that writes rows into the shuffle has to finish before any downstream task can read them, because a downstream task needs every row for its keys. During that pause the shuffle's output sits on the executors' disks as files, and a file has an exact size. Adaptive Query Execution, AQE for short, puts the pause to work. When the writing tasks finish, the executors report how many bytes landed in each shuffle partition. The driver
- On by Default Since Spark 3.2 (concepts: Adaptive Query Execution)
AQE in its current form shipped in Spark 3.0, released in June 2020, and it shipped switched off. It stayed off by default through 3.1. Spark 3.2.0, released in October 2021, changed the default to on. From that release forward, DataFrame and SQL queries on a cluster with default settings run adaptively, with no change to the code that defines them. One flag, and how to read it The answer comes back as text Queries the default covers When the 5-second check is worth running On by default means y
- Seeing AQE in the Spark UI (concepts: Adaptive Query Execution)
Knowing the flag is on tells you a plan may have changed. The Spark UI tells you whether it did, and at which node. The UI is a set of web pages that the driver serves while an application runs, on port 4040 by default. The page for this job is the tab labelled SQL / DataFrame (plain SQL on older releases), which lists one entry for each query the application has run. The root node says whether the plan is settled The Initial Plan is what the optimizer wrote from estimates. The Final Plan is wha
- Measurements over Estimates (concepts: Adaptive Query Execution)
An estimate and a measurement answer one question, how big is this, from opposite ends. An estimate starts at file metadata and reasons forward through each operation, applying an assumption at every step. A measurement waits until the bytes exist and counts them. The estimate can be wrong in ways that multiply. The measurement is exact about the past and silent about everything that has not run. An estimate drifts with each operation Each row's error feeds the next one. The duplicate-key blowup