Adaptive Query Execution
Spark plans a query before it has seen your data. AQE lets it change that plan halfway through, using statistics from the stages that already ran.
Step 2 · Spark internals · Silver · Self-tuning and file layout, lesson 1 of 2
On this page
Show code in
Every code block on the page follows this.
Read first: Jobs, stages and tasks · Shuffle partitions · Broadcast joins (skip if you know them)
In plain words first
A satnav plans a route before you set off, but adjusts it when it sees the traffic. Spark's optimizer plans a query from estimates; adaptive query execution (AQE) adjusts the plan while the query runs, using the real sizes it has just measured.
The problem it solves
The optimizer picks join strategies and partitionpartition: A chunk of a DataFrame's rows. Spark processes each partition as one task, so partitions decide how much work runs in parallel. Learn more → counts from estimates. Estimates are often wrong: a filter removes 99% of rows, or one key holds half the data. A plan fixed up front then shufflesshuffle: Moving rows between machines so that all rows with the same key end up together. Needed by joins, groupBy and sorting, and usually the most expensive step of a job. Learn more → into 200 nearly empty partitions, or sends one giant partition to a single tasktask: The work for one partition in one stage, run on one CPU core. Learn more →.
How it works
At every shuffle boundary, Spark pauses, measures the shuffle output, and re-optimizes the rest of the plan.
-
Step 1
A stagestage: A group of steps Spark can run without moving data between machines. A new stage starts at every shuffle. Learn more → runs and writes its shuffle
-
Step 2
Spark reads the real partition sizes
-
Step 3
The remaining plan is re-optimized
Re-optimizing can change three things:
Coalesce partitions
Switch join strategy
Split skewedskew: When one key has far more rows than the others, so one task does most of the work while the rest wait. Learn more → partitions
Walk through one query
Daily revenue for one country, from a 500 GB orders table joined to customers:
spark.sql(""" SELECT o.order_date, SUM(o.amount) FROM orders o JOIN customers c ON o.customer_id = c.id WHERE c.country = 'NZ' GROUP BY o.order_date """)
SELECT o.order_date, SUM(o.amount) FROM orders o JOIN customers c ON o.customer_id = c.id WHERE c.country = 'NZ' GROUP BY o.order_date
| Decision | Planned up front | What the stats showed | After AQE |
|---|---|---|---|
| Join | Sort-merge: the filtered customers size was guessed as large | Filtered customers are 6 MB | Broadcast hash join (under the 10 MB threshold) |
| Aggregation partitions | 200, from spark.sql.shuffle.partitions | Only 3 GB shuffled: 200 partitions averaging 15 MB, many far smaller | About 47 partitions of roughly 64 MB |
The arithmetic behind the second row: 3 GB divided by the 64 MB advisory size is about 47. Fewer, fuller tasks mean less scheduling overhead and fewer tiny output files, with no change to your code.
One more saving in the first row. By the time AQE switches the join to broadcast, the big side has often already been shuffled. That work is not thrown away: each executorexecutor: A worker process on a cluster machine that runs tasks and holds data in memory. Learn more → reads the shuffle files it wrote itself, on its own disk, instead of fetching them over the network. This is the local shuffle reader.
Key configs
| Config | Default | What it does |
|---|---|---|
spark.sql.adaptive.enabled | true | Turns AQE on or off. |
…coalescePartitions.enabled | true | Merges small shuffle partitions. |
…advisoryPartitionSizeInBytes | 64MB | Target partition size when merging or splitting. |
…autoBroadcastJoinThreshold | same as the non-adaptive one | Runtime size below which a join side is broadcast. |
…skewJoin.enabled | true | Splits skewed partitions in sort-merge joins. |
spark.conf.set("spark.sql.adaptive.enabled", "true") spark.conf.set("spark.sql.adaptive.advisoryPartitionSizeInBytes", "128MB")
SET spark.sql.adaptive.enabled = true; SET spark.sql.adaptive.advisoryPartitionSizeInBytes = 128MB;
Spot it in a plan
A plan that AQE manages starts with AdaptiveSparkPlan. Before an actionaction: An operation that needs a result (count, show, write), so Spark has to run the job. Learn more → runs it shows isFinalPlan=false; after it runs, the SQL tab of the Spark UI shows the final, re-optimized plan, with nodes such as AQEShuffleRead where partitions were coalesced or split.
== Physical Plan == AdaptiveSparkPlan isFinalPlan=false +- SortMergeJoin [customer_id], [id], Inner ...
When AQE cannot help
AQE only acts at shuffle boundaries, using statistics it has already measured. That leaves real gaps:
- The first stage. Nothing has been measured yet, so the file scan and anything before the first shuffle run as planned.
- Queries with no shuffle. A filter-and-write job has no boundary to re-plan at.
- Skewed aggregations. Skew handling splits partitions in sort-merge joins. A hot key in a
groupBystill lands on one task. See Data skew and saltingsalting: Adding a random number to a hot key so its rows spread over several tasks instead of one. Learn more →. - Structured Streaming. Streaming queries do not use AQE.
Try it yourself
Each example says what it shows, then the output from a real run and what to notice in it, so you can follow without running anything. To try one yourself, paste it into a local Spark session, with spark already created: each builds its own data.
Goal: Turn on the AQE settings a production job should have, then run a join with them.
AQE = { # default since Spark 3.2 "spark.sql.adaptive.enabled": "true", "spark.sql.adaptive.coalescePartitions.enabled": "true", "spark.sql.adaptive.advisoryPartitionSizeInBytes": "128m", "spark.sql.adaptive.skewJoin.enabled": "true", # runtime broadcast limit "spark.sql.adaptive.autoBroadcastJoinThreshold": "64m", } for key, value in AQE.items(): spark.conf.set(key, value) facts = spark.range(0, 2_000_000).selectExpr("id", "id % 1000 AS k") dims = (spark.range(0, 2_000_000) .selectExpr("id % 1000 AS k", "id AS v").where("v < 1000")) (facts.join(dims, "k").groupBy("k").count() .write.mode("overwrite").parquet("lab/aqe/joined_counts")) result = spark.read.parquet("lab/aqe/joined_counts") print(result.count(), "keys") result.orderBy("k").show(5)
Output from a real run
1000 keys +---+-----+ | k|count| +---+-----+ | 0| 2000| | 1| 2000| | 2| 2000| | 3| 2000| | 4| 2000| +---+-----+ only showing top 5 rows
What to notice:
- 1,000 keys, each with 2,000 rows: every fact row matched exactly one dimension row.
- AQE did its work at runtime, so the output looks like any join. The SQL tab in the Spark UI shows what it changed.
Goal: Watch AQE swap a planned sort-merge join for a broadcast join once it sees the real data size.
import contextlib, io from pyspark.sql import functions as F def plan(df): buf = io.StringIO() with contextlib.redirect_stdout(buf): df.explain() return buf.getvalue() big = spark.range(0, 5_000_000).withColumn("k", F.col("id") % 1000) other = spark.range(0, 5_000_000).withColumn("k", F.col("id") % 1000) # Keeps 100 rows, but without statistics the planner still thinks "other" is big. q = big.join(other.filter(F.col("id") < 100), "k").groupBy("k").count() print("planned join:", "SortMergeJoin" if "SortMergeJoin" in plan(q) else "other") q.collect() final = plan(q).split("Initial Plan")[0] final_join = "BroadcastHashJoin" if "BroadcastHashJoin" in final else "SortMergeJoin" print("final join:", final_join)
Output from a real run
planned join: SortMergeJoin final join: BroadcastHashJoin
What to notice:
- Before running, the plan says
SortMergeJoin: without statistics, Spark assumed the filtered side was big. - After running, the final plan says
BroadcastHashJoin: AQE saw only 100 rows came out of the filter and switched. - Print
plan(q)after the action to see both the Final Plan and the Initial Plan it replaced.
Common mistakes
- Setting shuffle partitions low and expecting AQE to raise them — Coalescing only merges. If you start with 20 partitions for 2 TB, each one is about 100 GB and AQE will not split them. Start high and let AQE merge down.
- Reading explain() and treating it as the final plan — Before an action, the plan says
isFinalPlan=false. The join you see may become a broadcast at runtime. Check the SQL tab in the Spark UI after the job runs. - Turning AQE off to debug, and leaving it off — A common way for jobs to get mysteriously slower after an incident. Turn it off for one session only, never in cluster defaults.
Key takeaways
- AQE re-plans at each shuffle boundary using measured sizes, not estimates.
- It coalesces small partitions, switches joins to broadcast, and splits skewed join partitions.
- It is on by default since Spark 3.2. Set shuffle partitions high and let it merge down.
- It cannot help the first stage, shuffle-free queries, skewed aggregations or streaming.
Interview prep
THE QUESTION
"What does Adaptive Query Execution change at runtime, and what can it not fix?"
Avoid: "AQE fixes all skew and partition problems". It works only at shuffle boundaries and only for some operators.
Follow-ups · answer out loud, then open
Follow-up"How can a query plan say SortMergeJoin in explain() but run as a broadcast join?"
AdaptiveSparkPlan isFinalPlan=false. After the shuffle stages run, AQE sees that one side is small and replans the join. The SQL tab of the Spark UI, or explain() on an executed query, shows the final plan.Scenario"AQE is on, but a groupBy on a skewed key is still slow. Why does AQE not help?"
Trap"AQE makes a full table scan of the first stage adaptive too."
Check yourself
3 questionsA query shuffles into 200 partitions, but most hold only a few kilobytes. AQE is on. What happens?
Show the answer
Small partitions are merged toward the advisory size, so fewer tasks run. AQE coalesces post-shuffle partitions toward spark.sql.adaptive.advisoryPartitionSizeInBytes (64 MB by default).
Which of these can AQE NOT fix?
Show the answer
A hot key in a groupBy aggregation. Skew handling applies to sort-merge joins, not aggregations.
What does isFinalPlan=false in explain() mean?
Show the answer
The plan may still change at runtime. AQE re-optimises during execution, so the plan before the action is provisional.
Practise this
Problems that use this, graded on hidden tests
Keep going
Up next · Self-tuning and file layout · lesson 2 of 2 · 8 min readThe small file problem
Why thousands of tiny files slow every read, how Spark jobs create them, and how to prevent and fix them.
Related lessons
AQE skew-join handlingSpark internals · 5 min read
Shuffle partitionsSpark internals · 6 min read
Broadcast joins
Previous: Dynamic allocation
Primary sources: Adaptive Query Execution