BeginnerSpark · 12 min · 11 challenges

Adaptive Query Execution: Beginner

A new season lands on Netflix on Friday, and by Monday an analyst wants minutes watched for that week's releases alone. The Spark job joins an enormous table of viewing sessions to a catalog cut down to a handful of titles. Spark chose the join before reading a row, assuming the catalog was still big. What it does once the real size shows up is this lesson.

The Static-Plan Problem

Daily Life
Interviews
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 the input files take on disk. The byte count is a real number, and for a plain scan it is a good one. The trouble starts one step later. Once a filter, a join or an aggregation sits between the files and the decision, Spark needs the size of a result that does not exist yet.
Decision in the planSize it depends onWhat Spark has before the run
Broadcast or shuffle a joinEach side after its filtersFile size before the filters
Partitions after a shuffleBytes the shuffle will writeA fixed setting, 200 by default
Whether one key overloads a taskRows per keyNothing

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()
views10 rows
view_id
title_id
minutes
1
1
42
2
2
55
3
3
12
4
5
30
5
1
61
6
4
48
7
6
20
8
3
35
9
2
50
10
5
15
titles6 rows
title_id
name
is_new
1
Night Shift
0
2
Orbit
1
3
Low Tide
0
4
Glass House
1
5
Red Line
0
6
Paper Moon
0
Preparing the animation

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()
views10 rows
view_id
title_id
minutes
1
1
42
2
2
55
3
3
12
4
5
30
5
1
61
6
4
48
7
6
20
8
3
35
9
2
50
10
5
15
titles6 rows
title_id
name
is_new
1
Night Shift
0
2
Orbit
1
3
Low Tide
0
4
Glass House
1
5
Red Line
0
6
Paper Moon
0
Preparing the animation

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.

Collecting statistics ahead of time narrows the gap for scans, but it costs a pass over the data and goes stale as soon as the table changes. It also describes stored tables only: the output of a filter joined to an aggregate has no statistics, because that result has never existed before this run.

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.

Multiple Choice

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 plan was reasonable given what Spark knew, and what Spark knew was one filter away from the truth. A more careful optimizer would not have helped, because the missing fact is created by the run itself. The next section is about using that fact once it exists.

Re-Optimizing Mid-Run

Daily Life
Interviews
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 hands those numbers to the same optimizer that wrote the original plan and asks it to plan the remaining work again. If the answer differs from the original, Spark runs the new version.
optimizer
Plan from estimates
executors
Run up to a shuffle
driver
Measure shuffle output
optimizer
Re-plan the remainder
executors
Run the remainder

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.

MomentWhat Spark doesSize it holds for the new titles
Action is calledPlans a shuffle join from the estimate2GB, predicted
Shuffle writes finishReads the sizes the tasks reported3MB, measured
Re-planRewrites the join as a broadcast of the new titles3MB, under the 10MB threshold
Remaining tasksRun the rewritten join3MB, 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.

A corrected plan therefore costs more than a plan that was right from its first line. AQE turns a badly wrong run into an acceptable one, and the estimate still decides how the run begins. The last section of this lesson comes back to that boundary.

The sizes behind 3 problems you know

The join is one of 3 problems from earlier lessons that share a cause, a size the plan had to predict: a shuffle join where a broadcast would have served, a shuffle that leaves many tiny partitions, and one partition far larger than its neighbours because of a hot key. AQE can act on each once the shuffle output has been measured. A later lesson covers how each adjustment works; this one is about where the numbers come from.

A re-plan leaves the results and your code alone

A re-plan changes how the remaining work is done and leaves the answer alone. The rewritten join returns the same rows as the original would have, for the same reason that a broadcast join and a shuffle join always agree on their output. Your code is untouched as well: the DataFrame you wrote is the same object, and the re-planning happens inside the action.
TIP
A driver who chose a route from a map the night before can still check the traffic at each junction and re-route the stretch ahead, but the stretch already driven stays driven. AQE works the same way, which is why a wrong first leg still costs you.
Multiple Choice

With AQE on, at which moment does Spark first hold a measured size for one side of a shuffle join?

Spark runs to a shuffle, counts what the shuffle produced, and plans the remainder again with the count.

On by Default Since Spark 3.2

Daily Life
Interviews
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.
Spark versionAdaptive executionDefault
Before 3.0A narrower predecessorOff
3.0 and 3.1AQE as taught hereOff
3.2 and laterAQE as taught hereOn

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.

print(spark.version)
print(spark.conf.get("spark.sql.adaptive.enabled"))

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.

aqe_on = spark.conf.get("spark.sql.adaptive.enabled") == "true"
print(aqe_on)

Queries the default covers

Is this query adaptive on a default 3.2+ cluster?
  • 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.

Multiple Choice

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?

if spark.conf.get("spark.sql.adaptive.enabled"):
print("AQE is on")
On by default means you will rarely switch AQE on yourself. It also means the plan a query finishes with can differ from the plan it started with, on any modern cluster, without anyone asking for it. Seeing that difference is the next skill.

Seeing AQE in the Spark UI

Daily Life
Interviews
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.
StepWhere to clickWhat to read
1The SQL / DataFrame tabThe row for your query, found by its description and duration
2The query's description linkThe plan drawn as a graph of boxes
3Details, below the graphThe same plan as text, root node first
4The 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 ==.

The Initial Plan is what the optimizer wrote from estimates. The Final Plan is what ran. Spotting a runtime change is a comparison of the 2, and for the new-releases join it comes out as follows.
What to compareInitial PlanFinal Plan
Join node`SortMergeJoin``BroadcastHashJoin`
Sort nodes under the join2, one per sideNone
Nodes ending in `QueryStage`NoneOne 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.

3 kinds of difference, and what each one means
  • 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.

new_titles = titles.filter(titles.is_new == 1)
minutes = (
views.join(new_titles, "title_id")
.groupBy("name")
.sum("minutes")
)
minutes.explain()
minutes.collect()
minutes.explain()

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.

Multiple Choice

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.

Measurements over Estimates

Daily Life
Interviews
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

Point in the queryWhat the estimate assumesHow far off it can be
Scan of a tableThe bytes of its filesUsually close
After a filterThe filter keeps every rowAbout 700x in the new-releases job
After a joinA formula over the input sizesAny amount, when keys repeat
After another joinThe previous guess, fed forwardThe earlier errors, multiplied
Each row's error feeds the next one. The duplicate-key blowup from the joins lesson is the sharpest case: the size of a join's output depends on how often each key repeats on both sides, and no file size reveals that. A few operations into a long query, the number the optimizer is working with is a guess built on a guess.

The decisions each one makes

✓Estimates decide
  • 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
✗Measurements decide
  • 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
The boundary is the first shuffle to finish. Before it, a prediction is all Spark has, so the prediction rules. After it, a counted size exists for that part of the data, and Spark trusts the count over the prediction it replaces.

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.

✓Do
  • 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
✗Don't
  • 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

Before running a query, write down 2 numbers for each side of a join: the size the optimizer will assume, which is the file size, and the size you believe that side really has after its filters. Run the query, then open the Final Plan. Expect a changed join node only where the assumed size is above the broadcast threshold, 10MB by default, your size is below it, and that side comes out of a shuffle. Where both numbers sit on the same side of the threshold, expect matching join nodes even though they disagree.

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()
That count is a measurement in AQE's sense: Spark ran the work and counted the output. The drill below is that habit at its shortest, a narrowing step followed by the action that returns the count.
Loading the challenge
AQE's counts need a finished shuffle. A query that never shuffles gives it nothing to measure.
Multiple Choice

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?

The estimate opens every query and owns it until a shuffle finishes. From there the measurement owns the remainder, and each new shuffle hands it fresher numbers.
PUTTING IT ALL TOGETHER

> 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.

The static-plan problem: the optimizer sees 4GB for the filtered promotions side every night, because a filter's predicted output equals its input, so the opening plan is always a shuffle join.
Re-optimizing mid-run: once the shuffle writes finish, the measured size is 2MB on a normal night and 1.5GB in sale week, and the join is planned again from whichever number the night produced.
On by default: the cluster runs Spark 3.5 and spark.conf.get("spark.sql.adaptive.enabled") returns true, so removing the hint was the only code change.
Seeing it in the Spark UI: a normal night's Final Plan shows BroadcastHashJoin where the Initial Plan shows SortMergeJoin. In sale week both plans show SortMergeJoin, which means the measurement confirmed the shuffle join.
Measurements over estimates: the order lines are shuffled every night, because the estimate owns the plan until that first shuffle finishes. The measurement decides only what happens after it.
KEY TAKEAWAYS
Spark writes a query's plan before any task runs, so every size in that plan is a prediction. By default a filter's output is predicted to be as large as its input.
A shuffle is a pause with exact numbers: once its writing tasks finish, Spark knows how many bytes each shuffle partition holds.
AQE re-plans the work that has not run, using those measured sizes. Work already done stays paid for, and the result rows never change.
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.
In the Spark UI's SQL / DataFrame tab, AdaptiveSparkPlan isFinalPlan=true marks a settled plan. The operator that differs between the Initial Plan and the Final Plan is the runtime change.
Estimates own a query until its first shuffle finishes. Measurements own everything downstream of that point.

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

  1. 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

  2. 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

  3. 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

  4. 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

  5. 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