Skip to content
Silver 7 min read · spark.sql.adaptive.enabled 2 practice problems ↓

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

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.

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

  2. Step 2

    Spark reads the real partition sizes

  3. Step 3

    The remaining plan is re-optimized

Re-optimizing can change three things:

Coalesce partitions

Merges many tiny shuffle partitions into fewer, right-sized ones.

Switch join strategy

Turns a sort-merge joinsort-merge join: Spark's default join for two large tables: both sides are shuffled and sorted by the key, then matched in one pass. Learn more → into a broadcast joinbroadcast join: A join where the small table is copied to every machine, so the big table never has to be shuffled. Learn more → when one side turns out small.

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

Breaks an oversized join partition into several tasks.

Walk through one query

Daily revenue for one country, from a 500 GB orders table joined to customers:

PySparkSpark SQL
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
DecisionPlanned up frontWhat the stats showedAfter AQE
JoinSort-merge: the filtered customers size was guessed as largeFiltered customers are 6 MBBroadcast hash join (under the 10 MB threshold)
Aggregation partitions200, from spark.sql.shuffle.partitionsOnly 3 GB shuffled: 200 partitions averaging 15 MB, many far smallerAbout 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

ConfigDefaultWhat it does
spark.sql.adaptive.enabledtrueTurns AQE on or off.
…coalescePartitions.enabledtrueMerges small shuffle partitions.
…advisoryPartitionSizeInBytes64MBTarget partition size when merging or splitting.
…autoBroadcastJoinThresholdsame as the non-adaptive oneRuntime size below which a join side is broadcast.
…skewJoin.enabledtrueSplits skewed partitions in sort-merge joins.
PySparkSpark SQL · Setting configs
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 groupBy still 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.

Production patternPySpark · AQE settings for a production job
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.

ExplorePySpark · Watch AQE replace a sort-merge join with a broadcast join at runtime
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?"

AQE re-plans at each shuffle boundary using the measured size of the finished stages. It does three things: coalesces small shuffle partitions toward the advisory size, switches a sort-merge join to a broadcast join (or a shuffled hash join) when one side turns out small, and splits skewed partitions in sort-merge joins. Its limits: it cannot change anything before the first shuffle (the scan stage), it does not split skew in aggregations or windows, it only coalesces downward so the initial shuffle partition count still has to be high enough, and it does not apply to streaming queries.

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?"
explain() before execution shows the initial plan, marked 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?"
AQE's skew handling only splits partitions of sort-merge (and shuffled hash) joins. For an aggregation, partial aggregation usually helps already; if it cannot (collect_list, distinct counts), salt the key: aggregate by key and salt, then by key.
Trap"AQE makes a full table scan of the first stage adaptive too."
No. AQE can only use statistics of stages that have finished, which means at shuffle boundaries. The first stage that reads from storage runs as planned.

Check yourself

3 questions

A 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 read
The 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

Previous: Dynamic allocation

Primary sources: Adaptive Query Execution