What you will be able to do
- Explain when and how AQE re-optimizes a query plan at runtime, and how this differs from planning before execution
- Predict how AQE coalesces small post-shuffle partitions and name the properties that control it
- Describe when AQE converts a sort-merge join to a broadcast hash join, and when it cannot
- Decide whether AQE will treat a shuffle partition as skewed and split it
- Read explain() output and the Spark UI to tell which AQE optimizations took effect
Key concept
Adaptive Query Execution (AQE) — AQE re-optimizes a Spark SQL query while it is running. At each shuffle or broadcast exchange, Spark replaces its pre-execution size estimates with statistics measured from the stages that have finished, then re-plans the stages that are still to run.
1.How AQE re-plans a query while it runs
Spark chooses a query plan before any data moves, using estimates of how big each piece of data will be. Those estimates go wrong when table statistics are missing or stale, when the data is skewed, or deep inside a complex query. A plan built on a bad estimate can pick a slow join strategy, create hundreds of tiny tasks after a shuffle, or leave a few oversized tasks holding up a whole stage. Adaptive Query Execution (AQE) fixes these problems by re-optimizing the plan during execution, based on the actual size of the data.
That timing is what separates AQE from Catalyst whole-plan optimization, which fixes the plan before execution starts. AQE keeps optimizing after the query has begun, and every decision it makes rests on statistics measured from stages of the current query that have already finished. It does not use estimates computed in advance.
Re-planning happens at materialization points. Spark pipelines most operators, but a shuffle or broadcast exchange breaks the pipeline: every task producing the exchange output has to finish before the next stage can start. The part of a plan between two such points is a query stage. At a stage boundary, Spark has accurate statistics for every partition and no downstream work has started yet, so it can still change the rest of the plan without throwing away any work.
The loop works like this. AQE first launches the leaf stages, which depend on no other stage. As stages finish, it writes their runtime statistics back into the logical plan. It then re-runs the optimizer and physical planner, including AQE-specific rules such as partition coalescing and skew-join handling, and launches the next stages whose inputs are ready. This execute, re-optimize, execute cycle repeats until the query is done.
| Problem from a wrong estimate | AQE feature |
|---|---|
| Too many small tasks after a shuffle | Dynamically coalesces partitions after shuffle exchange |
| Slow join strategy chosen for a side that turns out small | Dynamically changes sort merge join into broadcast hash join |
| A few oversized tasks hold up the whole stage | Dynamically handles skew in sort merge join and shuffle hash join |
| Parts of the query return no rows | Dynamically detects and propagates empty relations |
spark.sql.adaptive.enabled is the master switch for AQE. It has defaulted to true since Apache Spark 3.2.0, so queries get AQE without any code change. AQE only applies to a query that is not a streaming query and that contains at least one exchange (usually from a join, aggregate or window), at least one subquery, or both. A query that qualifies shows AQE in its physical plan as one or more AdaptiveSparkPlan nodes, usually at the root of each main query and subquery. AQE re-optimizes every query it supports, but the result can still be the same plan the optimizer compiled before the run.
Checkpoint 1 of 9· Check yourself
A filter cuts one side of a join far more than Spark expected, so the plan made before execution estimates that side as large. With AQE enabled, at what point can Spark first correct the plan using the real size of that side?
AQE re-plans at materialization points, which are shuffle or broadcast exchanges. There, the finished stage gives real statistics for every partition, and the next stage has not started yet. It does not change the plan before execution, while tasks are running, or on a later run.
“This provides a natural opportunity for reoptimization, for it is when data statistics on all partitions are available and successive operations have not started yet.”Source: www.databricks.com
Checkpoint 2 of 9· Exam question
A data engineer wants to understand how Adaptive Query Execution (AQE) differs from Spark's traditional cost-based optimizer. Which statement correctly describes when AQE takes effect?
Correct answer: A — AQE re-optimizes the physical plan at runtime using actual statistics collected at shuffle and broadcast exchange boundaries, replacing the original pre-execution estimates.
- A. This is correct because AQE's defining behavior is re-planning at runtime: it pauses at each exchange boundary, gathers real partition and row-count statistics, and uses them to pick a better plan for the next stage than the static optimizer could estimate up front.
- B. This is incorrect because rewriting the logical plan from the parsed AST based on indexes happens, if at all, during static analysis before execution, not through AQE's runtime re-optimization mechanism.
- C. This describes Delta file compaction (such as OPTIMIZE), a storage-layer maintenance operation that is unrelated to AQE's per-query runtime re-planning of shuffle and join stages.
- D. This describes automatic caching of repeated lineage, which is not a behavior AQE performs; AQE only reacts to statistics gathered at exchange boundaries, not repeated transformation references.
- E. This describes cluster warm-up based on historical timing data, which Spark does not do; AQE's decisions come from statistics measured during the current query's own execution, not past runs.
2.Coalescing small shuffle partitions
The right number of shuffle partitions is hard to set by hand. It depends on the data, and data size changes from one stage to the next. With too few partitions, each task is big enough that sorts and aggregations may spill to disk. With too many, each partition is tiny: Spark makes lots of small network fetches and puts more load on the task scheduler. Very small tasks also get worse I/O throughput and pay scheduling and setup overhead that is large relative to the work they do.
AQE solves this by starting with a high partition count and merging down. spark.sql.shuffle.partitions sets how many partitions a shuffle writes (200 by default). With coalescing turned on, that number is only a starting count. When the map side of the shuffle finishes, AQE reads the shuffle file statistics and merges adjacent small partitions into larger ones before the next stage launches its tasks. If you want a different starting count for AQE, set spark.sql.adaptive.coalescePartitions.initialPartitionNum. When it is unset, it equals spark.sql.shuffle.partitions.
SELECT max(i)FROM tbl GROUP BY jSuppose tbl is small and the initial shuffle partition number is five. After local grouping, the partially grouped data is shuffled into five partitions, and three of them are very small. Without AQE, Spark starts five tasks for the final aggregation, one per partition, including the near-empty ones. With AQE, the three small partitions are merged into one, so the final aggregation runs three tasks. A groupBy on a column with only a few distinct values works the same way: most of its 200 post-shuffle partitions are nearly empty, and AQE merges them before the next stage, such as a table write, begins.
| Property | Default | Role |
|---|---|---|
| spark.sql.adaptive.coalescePartitions.enabled | true | Turns coalescing on; it also needs spark.sql.adaptive.enabled to be true |
| spark.sql.adaptive.advisoryPartitionSizeInBytes | 64 MB | Target size Spark aims for when merging small post-shuffle partitions |
| spark.sql.adaptive.coalescePartitions.minPartitionSize | 1MB | Minimum size of a partition after coalescing |
| spark.sql.adaptive.coalescePartitions.initialPartitionNum | (none) | Starting partition count before coalescing; falls back to spark.sql.shuffle.partitions |
Coalesced partitions come out close to the advisory size but no larger, and never smaller than the minimum size. To aim for roughly 128 MB per partition, raise spark.sql.adaptive.advisoryPartitionSizeInBytes and keep spark.sql.adaptive.coalescePartitions.enabled at true. If that flag is false, nothing gets merged, whatever the target size. The skew thresholds and the broadcast threshold belong to other AQE features, and changing them does not affect how partitions are merged.
Checkpoint 3 of 9· Check yourself
A groupBy on a column with only a few distinct values writes its shuffle with spark.sql.shuffle.partitions left at 200, so most post-shuffle partitions are nearly empty. AQE and partition coalescing are both enabled. What does Spark do before the next stage launches its tasks?
With coalescing enabled, spark.sql.shuffle.partitions is only the starting count. When the map side finishes, AQE uses the measured shuffle statistics to merge adjacent small partitions before the next stage runs. It does not rerun the shuffle, and the skew settings have no effect on merging.
“then combine adjacent small partitions into bigger partitions at runtime by looking at the shuffle file statistics”Source: www.databricks.com
Checkpoint 4 of 9· Exam question
A PySpark job performs a wide aggregation:
result = (df.groupBy("region")
.agg(F.sum("amount").alias("total")))
result.write.mode("overwrite").saveAsTable("agg_totals")
The region column has very few distinct values, so many of the 200 shuffle partitions created by the aggregation end up nearly empty. With AQE enabled and default settings, what happens to these shuffle partitions before the write stage runs?
Correct answer: A — AQE merges the small post-shuffle partitions into fewer, larger partitions sized toward the spark.sql.adaptive.advisoryPartitionSizeInBytes target before the next stage starts.
- A. This is correct: AQE's coalescing feature reads the actual size of each post-shuffle partition and merges the small, nearly empty ones together so the write stage runs with fewer, more evenly sized tasks.
- B. This is incorrect because
spark.sql.shuffle.partitionsonly sets the initial partition count; AQE is specifically designed to adjust that count downward at runtime once real sizes are known. - C. This is incorrect because AQE does not simply warn and proceed with the original layout; its coalescing logic actively merges undersized partitions rather than leaving them to run as separate near-empty tasks.
- D. This describes partial aggregation, a separate optimization for reducing shuffle volume before the exchange; it does not describe what AQE does to the partitions after the shuffle has already happened.
- E. This is incorrect because AQE coalesces toward a target partition size, not down to a single partition, and it does not force a single output file regardless of data volume.
Checkpoint 5 of 9· Exam question
A team wants to tune AQE's post-shuffle partition coalescing so that Spark targets roughly 128 MB per coalesced partition instead of the 64 MB default, without changing anything about join or skew handling. Which two configuration properties are directly involved in this behavior? (Choose 2 answers)(Select 2)
Correct answers: A, B — spark.sql.adaptive.advisoryPartitionSizeInBytes, which sets the target size Spark aims for when merging small post-shuffle partitions together.; spark.sql.adaptive.coalescePartitions.enabled, which must stay set to true for Spark to merge any undersized post-shuffle partitions together at all.
- A. This is correct because this property is exactly the target size AQE's coalescing logic aims for when combining small post-shuffle partitions, so raising it to 128 MB directly changes the coalescing behavior described.
- B. This is correct because coalescing only runs when this flag is
true; it must stay enabled for the advisory partition size to have any effect on how partitions are merged. - C. This threshold governs skew detection for splitting oversized partitions, a separate feature from coalescing, so it does not affect how small partitions get merged together.
- D. This threshold controls whether a join side is small enough to broadcast, which is unrelated to how post-shuffle partitions are sized or merged after an aggregation.
- E. This sets the initial shuffle partition count before AQE runs, but it is not the mechanism that controls the coalescing target size, and AQE can still reduce the count below it at runtime.
3.Switching a sort-merge join to a broadcast join
Spark has two main ways to join large inputs, and AQE can swap one for the other mid-query. A sort-merge join shuffles both sides across the network so matching keys meet in the same partition, sorts each side, and then merges them. A broadcast hash join instead sends a copy of one side to every worker node, so the other side needs no sort. That is why it is usually the fastest join when one side fits comfortably in memory: every node has to hold the whole broadcast side. Spark plans one when the estimated size of a join side is below the broadcast threshold. Estimates can be badly wrong, though. A very selective filter, or a join side built from a chain of complex operators instead of a plain scan, can make a small relation look large, and then the static planner chooses a sort-merge join.
AQE re-plans the join once it knows the real size of each side. If runtime statistics show a join side below spark.sql.adaptive.autoBroadcastJoinThreshold, AQE converts the sort-merge join into a broadcast hash join. That threshold defaults to the same value as spark.sql.autoBroadcastJoinThreshold, and setting it to -1 turns broadcasting off. After the switch, Spark no longer has to sort both join sides. With spark.sql.adaptive.localShuffleReader.enabled (default true), it also reads the existing shuffle files locally, per mapper, which cuts network traffic.
Yes, because a runtime switch comes late. AQE may not learn the actual table sizes until it has shuffled both sides of the join, so the cost of that shuffle has already been paid. A broadcast join the optimizer plans before execution usually performs better than one AQE introduces at runtime. If you know one side is small, give Spark a hint. AQE respects query hints the same way static optimization does, and it still applies the dynamic optimizations that the hints don't affect.
Even when a table is under the threshold, AQE won't always broadcast it. Some join types can't broadcast a particular side; for example, AQE can't broadcast the left side of a LEFT OUTER JOIN. AQE also keeps the sort-merge join when the share of non-empty partitions is below spark.sql.adaptive.nonEmptyPartitionRatioForBroadcastJoin, because most tasks in that join already finish quickly. Join order is another thing AQE leaves alone: it doesn't reorder joins at runtime. Join order comes from the cost-based optimizer, which relies on collected table statistics.
Checkpoint 6 of 9· Check yourself
Runtime statistics show that the left side of a LEFT OUTER JOIN is only 5 MB, well below spark.sql.adaptive.autoBroadcastJoinThreshold. Most of its partitions are non-empty, yet AQE keeps the sort-merge join. What is the most likely reason?
Being under the threshold is not enough. The join type must also allow that side to be broadcast, and a LEFT OUTER JOIN cannot broadcast its left side. The adaptive threshold defaults to the value of spark.sql.autoBroadcastJoinThreshold, not -1, and AQE does not need a hint to make the switch.
“Some join types can't broadcast one side. For example, AQE can't broadcast the left side of a LEFT OUTER JOIN.”Source: docs.databricks.com
4.Splitting skewed partitions in joins
Data skew means data is spread unevenly across partitions. In a join, it shows up as one task running long after the others have finished. AQE detects skew automatically from shuffle file statistics. It splits each oversized partition into smaller subpartitions and joins each one to the matching partition from the other side, copying that partition when needed, so the skewed work ends up spread over roughly evenly sized tasks.
Take table A joined with table B, where A's partition A0 is much larger than its other partitions. Without the optimization, four tasks run the sort-merge join and one of them takes far longer than the rest. With it, A0 is split and five tasks run the join, each taking roughly the same time, so the stage finishes sooner. This applies to sort-merge joins and shuffle hash joins. Broadcast joins are never skew-optimized because they have no shuffle partitions to split.
| Property | Default | Meaning |
|---|---|---|
| spark.sql.adaptive.skewJoin.enabled | true | Turns skew join handling on or off |
| spark.sql.adaptive.skewJoin.skewedPartitionFactor | 5 | Partition must be larger than this multiple of the median partition size |
| spark.sql.adaptive.skewJoin.skewedPartitionThresholdInBytes | 256MB | Partition must also be larger than this absolute size |
A partition has to pass both tests. The relative test keeps AQE from splitting partitions that are only large because every partition is large. The absolute test keeps it from bothering with partitions that are big compared with the median but still cheap to process. If the Spark UI shows a skewed join stage that AQE left alone, the skewed partitions are probably under one of the thresholds, and lowering the factor or the byte threshold lets AQE catch them. AQE skew handling is automatic and usually performs better than the skew join hint, so it is the first fix to reach for.
Checkpoint 7 of 9· Check yourself
In the Spark UI, one task in a sort-merge join stage runs far longer than the others. Its partition is 200 MB, and the median partition is 20 MB. AQE is enabled with default skew settings but did not split the partition. Which change lets AQE handle this skew?
200 MB is 10 times the median, so it passes the factor-of-5 test. It fails the 256MB absolute test, and a partition must pass both. Lowering the byte threshold lets AQE split it. Raising the factor would make detection harder, broadcast joins are never skew-optimized, and coalescing does not affect skew detection.
“If the skewed partitions are smaller than the thresholds, adjust spark.sql.adaptive.skewJoin.skewedPartitionFactor and spark.sql.adaptive.skewJoin.skewedPartitionThresholdInBytes.”Source: docs.databricks.com
5.Seeing what AQE changed in the plan
AQE changes the plan while the query runs, so where and when you look at the plan determines what you see. DataFrame.explain() shows two plans under each AdaptiveSparkPlan node: the initial plan, before AQE applies any optimizations, and the current plan. The node's isFinalPlan flag stays false before and during execution and becomes true when the query finishes. At that point the current plan is the final plan.
The statistics on each shuffle and broadcast stage tell you whether AQE has measured anything yet. Before and during a stage's run, they carry isRuntime=false and are compile-time estimates. After the stage runs, isRuntime=true and the numbers are runtime measurements. In the Spark UI, the query plan diagram shows the latest plan and updates as the query runs. Nodes that have already run keep their metrics and stay fixed, while nodes that haven't run yet can still change.
SQL EXPLAIN is the exception. It doesn't run the query, so AQE never gets a chance to re-optimize. Its output shows only the initial plan, which can differ from the plan that actually runs. To see what AQE did, compare the current or final plan against the initial plan and look for these signatures.
| Optimization | Sign in the plan |
|---|---|
| Join strategy change | A different physical join node than in the initial plan |
| Partition coalescing | A CustomShuffleReader node with the Coalesced property |
| Skew join handling | A SortMergeJoin node with the isSkew field set to true |
| Empty relation propagation | A LocalTableScan node with an empty relation field replaces part or all of the plan |
Checkpoint 8 of 9· Match them up
You compare the final plan from DataFrame.explain() with the initial plan. Match each AQE optimization to the sign it leaves in the final plan.
Tap a term, then the definition that fits it.
Each AQE optimization changes the plan in its own way. Comparing the current or final plan with the initial plan shows which optimizations took effect.
“Partition coalescing. The plan contains a CustomShuffleReader node with the Coalesced property.”Source: docs.databricks.com
Checkpoint 9 of 9· Check yourself
An engineer wants to know if AQE switched a join to a broadcast hash join. They run SQL EXPLAIN on the query, and the output shows a SortMergeJoin. What can they conclude from this output?
SQL EXPLAIN never runs the query, so AQE never gets to re-optimize it, and the output is only the initial plan. To see what AQE changed, use DataFrame.explain() after the query runs, or the Spark UI.
“SQL EXPLAIN doesn't run the query, so AQE can't re-optimize it. The output shows only the initial plan”Source: docs.databricks.com
Sources1
Sources
(4)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.https://docs.databricks.com/aws/en/optimizations/aqeOfficial docs
“At the end of each shuffle or broadcast exchange, Databricks has accurate statistics for the data produced so far.”
↩︎ How AQE re-plans a query while it runs“AQE-applied queries contain one or more AdaptiveSparkPlan nodes, usually as the root node of each main query or sub-query.”
↩︎ How AQE re-plans a query while it runs“The query isn't a streaming query.”
↩︎ How AQE re-plans a query while it runs“The target size after coalescing. Coalesced partitions are close to, but no larger than, this size.”
↩︎ Coalescing small shuffle partitions“Very small tasks have worse I/O throughput and tend to suffer more from scheduling overhead and task setup overhead.”
↩︎ Coalescing small shuffle partitions“AQE might not switch to a broadcast join until after it shuffles both sides of the join”
↩︎ Switching a sort-merge join to a broadcast join“For example, AQE can't broadcast the left side of a LEFT OUTER JOIN.”
↩︎ Switching a sort-merge join to a broadcast join“AQE doesn't reorder joins at runtime.”
↩︎ Switching a sort-merge join to a broadcast join“AQE treats a partition as skewed only when both of these conditions are true”
↩︎ Splitting skewed partitions in joins“Use AQE skew join handling. It's automatic and usually performs better than the skew join hint.”
↩︎ Splitting skewed partitions in joins“SQL EXPLAIN doesn't run the query, so AQE can't re-optimize it.”
↩︎ Seeing what AQE changed in the plan“The flag is false before and during query execution, and changes to true when the query finishes.”
↩︎ Seeing what AQE changed in the plan“After the stage runs, isRuntime is true and the statistics are runtime measurements.”
↩︎ Seeing what AQE changed in the plan“Skew join handling. The plan contains a SortMergeJoin node with the isSkew field set to true.”
↩︎ Seeing what AQE changed in the plan“Adaptive query execution (AQE) is query re-optimization that occurs during query execution.”
↩︎ Key concept“At the end of each shuffle or broadcast exchange, Databricks has accurate statistics for the data produced so far.”
↩︎ Exam trap 1“The target size after coalescing. Coalesced partitions are close to, but no larger than, this size.”
↩︎ Exam trap 2“AQE might not switch to a broadcast join until after it shuffles both sides of the join”
↩︎ Exam trap 3“AQE treats a partition as skewed only when both of these conditions are true”
↩︎ Exam trap 4“SQL EXPLAIN doesn't run the query, so AQE can't re-optimize it.”
↩︎ Exam trap 5“Some join types can't broadcast one side. For example, AQE can't broadcast the left side of a LEFT OUTER JOIN.”
↩︎ Checkpoint“Partition coalescing. The plan contains a CustomShuffleReader node with the Coalesced property.”
↩︎ Checkpoint“SQL EXPLAIN doesn't run the query, so AQE can't re-optimize it. The output shows only the initial plan”
↩︎ Checkpoint - 2.https://spark.apache.org/docs/latest/sql-performance-tuning.htmlSecondary source
“which is enabled by default since Apache Spark 3.2.0”
↩︎ How AQE re-plans a query while it runs“If not set, it equals to spark.sql.shuffle.partitions.”
↩︎ Coalescing small shuffle partitions“The default value is the same as spark.sql.autoBroadcastJoinThreshold.”
↩︎ Switching a sort-merge join to a broadcast join“a table that will be broadcast to all worker nodes when performing a join”
↩︎ Switching a sort-merge join to a broadcast join - 3.https://www.databricks.com/blog/2020/05/29/adaptive-query-execution-speeding-up-spark-sql-at-runtime.htmlSecondary source
“a shuffle or broadcast exchange breaks this pipeline. We call them materialization points”
↩︎ How AQE re-plans a query while it runs“AQE coalesces these three small partitions into one and, as a result, the final aggregation now only needs to perform three tasks rather than five.”
↩︎ Coalescing small shuffle partitions“such as the presence of a very selective filter”
↩︎ Switching a sort-merge join to a broadcast join“broadcast hash join is usually the most performant if one side of the join can fit well in memory”
↩︎ Switching a sort-merge join to a broadcast join“It then splits the skewed partitions into smaller subpartitions, which will be joined to the corresponding partition from the other side respectively.”
↩︎ Splitting skewed partitions in joins“This provides a natural opportunity for reoptimization, for it is when data statistics on all partitions are available and successive operations have not started yet.”
↩︎ Checkpoint“then combine adjacent small partitions into bigger partitions at runtime by looking at the shuffle file statistics”
↩︎ Checkpoint - 4.
“Broadcast joins are never skew-optimized”
↩︎ Splitting skewed partitions in joins“If the skewed partitions are smaller than the thresholds, adjust spark.sql.adaptive.skewJoin.skewedPartitionFactor and spark.sql.adaptive.skewJoin.skewedPartitionThresholdInBytes.”
↩︎ Checkpoint