Sub topic 13
Adaptive query execution and skew
This chapter assumes you can read a query plan with EXPLAIN, know what a stage, task and shuffle are, and understand the join strategies from the previous chapter (broadcast hash join, shuffle hash join, sort-merge join). It covers how Spark changes a plan while the query runs, and how that fixes the most common kind of slow join: data skew.
Why plans need to change at runtime
The optimizer picks a plan before any data is read. It relies on table statistics and size estimates. Those estimates can be wrong, especially after filters, joins and aggregations, where Spark has to guess how many rows survive.
Adaptive query execution (AQE) addresses this. AQE is a Spark feature that re-optimizes the remaining part of a query after each shuffle stage finishes. At that point Spark knows the real size of the shuffle output, so it can replace guesses with measurements. AQE is enabled by default in current Databricks Runtime versions and on SQL warehouses.
The three main AQE optimizations
Coalescing shuffle partitions
A shuffle writes output into a fixed number of partitions, set by spark.sql.shuffle.partitions (200 by default in open-source Spark). If the data is small, you get many tiny tasks, and scheduling overhead dominates. AQE looks at the actual partition sizes and merges adjacent small ones into fewer, larger partitions.
You do not need to hand-tune the shuffle partition count for each query. A generous value is fine because AQE reduces it when the data is small.
Switching join strategies
If the planner estimated that both sides of a join were large, it chooses a sort-merge join. After the shuffle stages finish, AQE may find that one side is actually small, for example because a filter removed most rows. It then converts the join to a broadcast hash join, and the other side no longer needs to be sorted.
The size limit for this conversion is controlled by spark.sql.autoBroadcastJoinThreshold (10 MB by default in open-source Spark). A runtime conversion is limited by what has already been shuffled, so some of the shuffle cost is already paid. A broadcast hint, as shown in the previous chapter, still avoids that cost when you know a table is small.
Splitting skewed partitions
Skew means a few join keys hold a disproportionate share of the rows. In a shuffle, all rows with the same key go to the same partition. One partition can be many times larger than the rest, so one task runs long while the others finish and sit idle. The stage takes as long as its slowest task.
With skew handling enabled, AQE detects oversized partitions in a sort-merge join and splits each one into several smaller sub-partitions. The matching rows from the other side are duplicated across those sub-partitions, so the join result stays correct.
Configuration settings
| Setting | Purpose |
|---|---|
| `spark.sql.adaptive.enabled` | Turns AQE on or off. |
| `spark.sql.adaptive.coalescePartitions.enabled` | Merges small shuffle partitions. |
| `spark.sql.adaptive.skewJoin.enabled` | Splits skewed partitions in sort-merge joins. |
| `spark.sql.adaptive.skewJoin.skewedPartitionFactor` | A partition is skewed if it is larger than this factor times the median partition size. |
| `spark.sql.adaptive.skewJoin.skewedPartitionThresholdInBytes` | A partition must also exceed this absolute size to count as skewed. |
A partition is treated as skewed only when it passes both the factor and the byte threshold. This prevents AQE from splitting partitions that are large relative to the median but still small in absolute terms.
Check the current values in your session before changing them:
SET spark.sql.adaptive.enabled;
SET spark.sql.adaptive.skewJoin.enabled;
SET spark.sql.adaptive.skewJoin.skewedPartitionFactor;Seeing AQE in a plan
With AQE on, EXPLAIN shows an AdaptiveSparkPlan node at the top. Before the query runs, the plan is marked isFinalPlan=false, because it can still change. After execution, the Query Profile and the Spark UI SQL tab show the final plan.
Look for these signs in the final plan:
AQEShuffleReadwithcoalescedmeans small partitions were merged.AQEShuffleReadwithskewedmeans a skewed partition was split.- A
BroadcastHashJoinwhereEXPLAINbefore the run showedSortMergeJoinmeans the join strategy changed at runtime.
EXPLAIN FORMATTED
SELECT c.region, SUM(o.amount) AS total
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
GROUP BY c.region;Run EXPLAIN first to see the initial plan. Then run the query and open the final plan in the Query Profile to compare.
Diagnosing skew
Skew shows up in stage metrics. In the Spark UI, open the slow stage and look at the task summary:
- The maximum task duration is far above the median.
- The maximum shuffle read size is far above the median.
- Most tasks finished early while one or two are still running.
- A single task spills to disk or runs out of memory while others do not.
In the Query Profile, a join or aggregation node with a very large time share and an uneven row distribution points to the same cause.
You can confirm which keys are heavy with a direct query:
SELECT customer_id, COUNT(*) AS row_count
FROM orders
GROUP BY customer_id
ORDER BY row_count DESC
LIMIT 20;If a handful of keys account for a large share of the rows, or if a placeholder such as NULL or -1 dominates, you have skew.
When AQE does not fix skew
AQE skew handling has limits. Know them before relying on it.
- Only some joins. It splits partitions in sort-merge joins. It does not help a skewed
GROUP BYaggregation, where a single key's rows must all be combined in one place. - One side at a time. A key that is heavy on both sides of the join cannot be split cleanly, because duplicating the matching rows multiplies the work.
- Needs a shuffle stage. AQE acts at shuffle boundaries. If the skew is introduced and consumed within one stage, there is nothing to re-plan.
- Thresholds. A moderately skewed partition below the byte threshold is left alone.
- Null keys. Rows with a
NULLjoin key never match in an inner join, but they still land in one shuffle partition. Filtering them before the join removes that partition.
Manual fixes for stubborn skew
When AQE is not enough, change the query or the data.
- Filter out useless keys. Remove
NULLor sentinel values before the join if they do not contribute to the result. - Broadcast the smaller side. A broadcast join has no shuffle on the large side, so skew on that side no longer matters.
- Salt the key. Add a random suffix to the heavy key on the large side, and expand the small side to cover every suffix. The heavy key then spreads across several partitions.
- Pre-aggregate. Reduce the large side before the join so each key appears once.
This example salts the join key with 8 buckets:
from pyspark.sql import functions as F
SALT_BUCKETS = 8
# Large, skewed side: assign each row a random salt.
orders_salted = orders.withColumn(
"salt", (F.rand() * SALT_BUCKETS).cast("int")
)
# Smaller side: replicate every row once per salt value.
customers_salted = customers.withColumn(
"salt", F.explode(F.array([F.lit(i) for i in range(SALT_BUCKETS)]))
)
joined = orders_salted.join(
customers_salted, ["customer_id", "salt"], "inner"
).drop("salt")Salting multiplies the size of the smaller side by the number of buckets, so use the smallest bucket count that evens out the work. It also adds code complexity, so try AQE settings and a broadcast first.
AQE and Photon
AQE is a planning feature in Spark, and it works with Photon. Photon executes the operators, and AQE decides the shape of the plan between stages. In the final plan, the re-planned join and shuffle read operators can still run in Photon. Check the Query Profile for the Photon marking on each operator, as described earlier, rather than assuming the re-planned stage stayed native.
Common mistakes
- Setting
spark.sql.shuffle.partitionsvery low to "avoid small tasks." This removes AQE's room to coalesce, and it can create oversized partitions. - Disabling AQE while debugging and forgetting to turn it back on.
- Reading the plan from
EXPLAINalone. The initial plan is not the final plan. - Lowering the skew factor and threshold too far, which splits partitions that were fine and adds overhead.
- Treating every slow stage as skew. Check that the max task time is well above the median before applying a fix.
Exercise
A join stage has 200 tasks. The median task reads 40 MB and finishes in 20 seconds. One task reads 6 GB and runs for 12 minutes. AQE is on and spark.sql.adaptive.skewJoin.enabled is true, but the final plan shows no skewed read. Name two possible reasons and one fix for each.
Show answer
First, the query may not use a sort-merge join. For example, the slow stage could be a skewed GROUP BY aggregation, which AQE does not split. Fix it by pre-aggregating in stages or by adding a salt column to the grouping key. Second, the heavy key may be heavy on both sides of the join, or the partition thresholds may not have been met. Fix it by filtering useless keys such as NULL, broadcasting the smaller side if it fits, or salting the key. Confirm in the Spark UI that the slow stage is a join and check the partition factor and byte threshold settings.
Exercise
You run EXPLAIN on a query and see a SortMergeJoin. After the query finishes, the Query Profile shows a BroadcastHashJoin. What happened, and why is a broadcast hint still useful?
Show answer
AQE measured the real shuffle output, found that one side was below the broadcast threshold, and converted the join at runtime. A hint is still useful because the conversion happens after the shuffle stages ran, so that shuffle cost is already paid. A hint lets Spark broadcast from the start and skip the shuffle on the large side.