
Why Spark AQE Leaves Skewed Join Tasks Running Slowly
Spark AQE doesn’t split every slow join task. By default, a partition must exceed both 5× the median partition size and 256 MB, and the join type and side must support splitting. Start with task metrics and the final adaptive plan to find out why a task stayed slow.
The next step depends on the cause:
- No split: Check both thresholds, AQE settings, and join eligibility before tuning.
- Slow tasks after splitting: Check replicated reads, oversized shuffle blocks, spill, and join output.
- Work outside the join: Address scans, filtering, aggregation, or output writing rather than skew settings.
- Hot keys or excess data: Consider filtering, pre-aggregation, broadcasting, hot-key isolation, or salting.
Change one thing at a time. Compare total runtime - not just task speed - and verify row counts, duplicates, nulls, and join results.
Spark AQE Skewed Join Troubleshooting
Find the Bottleneck in Task Metrics and the Executed Plan
Compare Task Duration, Shuffle Read, and Spill
Start with task metrics to separate skew from operator work, memory pressure, or executor contention. Open the slow stage in Spark UI’s SQL Details view. Compare the maximum task duration with the median and the 95th and 99th percentiles. Confirm that a few outliers - not all tasks - are holding up the stage. Then compare shuffle-read bytes and records, input size and records read, executor run time, peak execution memory, and memory and disk spill.
Before checking the plan, use the strongest metric pattern to narrow down the cause. These patterns are clues, not proof. Compare individual tasks: stage totals can hide overloaded partitions. If you don’t see shuffle-skew signals, check scan and executor issues.
| Observed metric pattern | Most likely cause | Next check |
|---|---|---|
| Long duration + much larger shuffle reads | Uneven shuffle partitions or hot keys | Inspect the join exchange, key distribution, and signs of partition splitting |
| Long executor run time with ordinary input sizes | Expensive expressions, aggregation, window processing, or join output | Inspect operator metrics and output records |
| Heavy spill in slow tasks | Memory pressure from sorting, wide rows, or large state | Check sort and aggregation operators, peak execution memory, and GC time |
| Large scan input + normal shuffle reads | Uneven files or source reads | Check file sizes, pruning, and scan parallelism |
| Slow tasks cluster on one executor | Executor or host contention | Compare executor summaries, GC time, task locality, failures, and host-level resource use |
Don’t add memory spill and disk spill into one total. Memory spill measures deserialized shuffle data; disk spill measures serialized shuffle data. If spill clusters in the tasks with the largest reads, partition imbalance may be creating memory pressure. If input sizes are similar, check operator state and executor behavior first.
Inspect the Final Adaptive Plan and AQE Settings
Once the metrics point to a likely cause, check it against the final adaptive plan. In SQL Details, trace the slow stage through its physical operators. Follow Exchange boundaries and inspect nearby scans, SortMergeJoin, ShuffledHashJoin, HashAggregate, and Window nodes.
A stage can contain several operators. An Exchange feeding a join doesn’t prove the join caused the delay. Use operator row counts and stats to find where the amount of work grows.
Compare the initial and final operators for three outcomes: a skew split, a join-strategy change, or no join-level fix. Check partition coalescing, too; skew handling may appear as isSkew on the join.
Verify the session’s effective values for spark.sql.adaptive.enabled and spark.sql.adaptive.skewJoin.enabled. Record the Spark version and any platform overrides. If no split appears, check whether the partition missed the thresholds, the join was ineligible, or the slow work sits outside the join.
sbb-itb-61a6e59
Check Skew Thresholds and Join Support
Check Both Partition-Size Thresholds
If the final adaptive plan shows no split, check the exact skew cutoff Spark used. Spark flags a partition as skewed only when its size exceeds both thresholds: spark.sql.adaptive.skewJoin.skewedPartitionThresholdInBytes and spark.sql.adaptive.skewJoin.skewedPartitionFactor × median partition size. Lowering the byte threshold alone won't help if the median-based cutoff still blocks detection.
Treat spark.sql.adaptive.advisoryPartitionSizeInBytes as a target, not a cap. Spark recommends keeping the skew threshold above this advisory size. A single unsplittable block can leave a split larger than the target.
Review Default Settings and Tuning Risks
Check the effective session values for your deployed Spark version and distribution. Don't rely only on upstream defaults, and record the advisory size too. Lower thresholds may shorten outlier tasks, but they can also add scheduling work and replicated reads.
| Setting | Role | Documented upstream default | Tuning risk |
|---|---|---|---|
spark.sql.adaptive.skewJoin.skewedPartitionFactor |
Sets the median-relative cutoff | 5.0 |
Lower values can create more split tasks and replicated reads. |
spark.sql.adaptive.skewJoin.skewedPartitionThresholdInBytes |
Sets the absolute size cutoff | 256 MB |
Lower values can flag ordinary partitions and add overhead. |
spark.sql.adaptive.forceOptimizeSkewedJoin |
Forces skew-join optimization even if it adds another shuffle | false |
Can add a shuffle, but does not extend support to broadcast, nested-loop, aggregation, window, or non-join shuffles. |
Check Which Joins and Sides AQE Can Split
Match the join type and larger side to Spark's split rules. AQE skew handling applies to supported shuffle-based joins, mainly sort-merge joins and shuffled hash joins.
For supported joins, the split rules are:
- Inner or cross join: Either side can be split, including both sides.
- Left outer, left semi, or left anti join: Only the left side can be split.
- Right outer join: Only the right side can be split.
- Full outer join: Neither side is eligible in this support matrix.
Inspect the final physical plan and join type before deciding that AQE failed.
AQE splits shuffle partitions into block ranges and may replicate matching-side rows. An unsplittable block can still run slowly, while replication can increase reads and spill. If the join isn't eligible for splitting, consider filtering, pre-aggregation, or key salting rather than threshold tuning.
Limitation of Apache Spark AQE SkewedJoin Optimization
Match the Fix to the Task Metrics
Once the metrics show where time goes, choose the smallest fix that removes the bottleneck. Match the dominant symptom to the lowest-cost remedy in the table.
| Remedy | Supporting metrics | Main benefit | Principal tradeoff |
|---|---|---|---|
| AQE threshold tuning | Eligible shuffle join; one or both skew tests fail | Splits missed stragglers | More tasks and replicated reads |
| Broadcasting | Small build side; enough memory and network headroom | Removes the join shuffle | Memory pressure and timeout risk |
| Filtering and projection | Unneeded rows or columns; high shuffle bytes or spill | Cuts scan, shuffle, serialization, and memory cost | Must retain required data |
| Pre-aggregation | Many duplicate rows per key; output uses aggregates that can be merged | Reduces rows before the join | Can change grain or drop detail |
| Hot-key isolation | A few keys dominate bytes, records, or output | Routes hot keys separately | Needs monitoring and separate execution paths |
| Key salting | Hot-key skew remains after reduction; shuffle input still drives runtime | Spreads hot-key input across tasks | Replicates the other side; does not fix many-to-many output growth |
Adjust Thresholds or Change the Join Strategy
If skew detection misses a slow partition, start with the thresholds and join eligibility. If both tests pass, don't lower the thresholds. Instead, check configuration scope, plan eligibility, or work unrelated to skew. If the join pattern isn't supported, consider a rewrite only if it preserves the results.
Broadcasting is another option when the join type allows it. Check the actual build-side size, executor headroom, concurrent broadcasts, and transfer time. Spark documents a 10 MB automatic broadcast threshold and a 300-second timeout, but these are configuration defaults - not safety limits for every workload. Broadcasting doesn't remove upstream skew or excessive join output.
Reduce Input and Spread Hot Keys
If the data itself is still the bottleneck, reduce the work before the join. Push valid filters and column projection ahead of it. Pre-aggregate only when the required grain and join semantics allow it. For skewed, mergeable aggregates, compute partial results, then merge them by the original key. This reduces work instead of just moving it around. For those looking to master data engineering at a deeper level, understanding these low-level optimizations is essential.
When a few keys dominate, route them through a separate path. If you still need to redistribute the input, salt only those hot keys: assign large-side rows to deterministic buckets and replicate matching-side rows across those buckets. Set the bucket count using measured volume and the target partition size. Preserve duplicates, null handling, and join semantics. Salting spreads input across tasks; it doesn't eliminate many-to-many output.
Diagnose Slow Tasks After Splitting
Compare split tasks with the original workload. Check total shuffle read, matching-side replication, spill, executor run time, and join output. Balanced reads with high output point to many-to-many output growth. Increasing reads and spill suggest replication or memory pressure.
A single oversized shuffle block can still limit splitting. Use the metrics to decide whether to reduce input, isolate hot keys, check memory headroom, or fix unintended matches.
Verify Runtime and Result Correctness
Measure One Change at a Time
After tuning thresholds, changing the join strategy, or salting keys, check runtime and correctness using the same workload. Use the same input snapshot, including known hot keys. Hold the Spark version, cluster size, adaptive settings, executor settings, file layout, partitioning, and cache state constant. Change one setting or transformation per run. Repeat runs and report the median and full range.
Record end-to-end and stage runtime, task-duration spread, shuffle reads and writes, peak execution memory, memory and disk spill, task count, executor failures, and output rows or bytes. Check downstream operators, too. Shorter tasks don’t help if replication, GC, retries, or downstream work increases.
Save the executed adaptive plan and confirm that the intended change took effect. Note any added exchanges, broadcast failures, or timeouts. EXPLAIN COST shows optimizer estimates; the executed plan and Spark UI show what happened at runtime. The first pass checks speed. The second checks whether the results stayed the same.
Check Results After Salting or Rewriting
Salting and rewrites can cut runtime while changing multiplicity or null behavior. Run a small, deterministic regression dataset alongside the performance test.
For salted equijoins, confirm that each large-side row gets one salt, matching smaller-side rows cover the full salt range, and the join uses both the key and salt. Drop the helper column before comparing results. Check row counts, multiplicity, nulls, and aggregates against the original query - not just distinct keys.
Use null-safe comparisons to reconcile grouped counts on the full business key and payload columns in both directions. For outer joins, test unmatched rows separately. Replicating the smaller side can duplicate unmatched rows; in full outer joins, an unmatched row from a copied side can appear once per salt. Before accepting the rewrite, validate unmatched counts from both sides, duplicate keys, and null-key behavior.
Conclusion: Separate Threshold Problems From Workload Problems
When task metrics point to skew, check the final plan to confirm eligibility: AQE can split only supported shuffle joins with partitions that exceed both skew thresholds. Keep the skew threshold above the advisory partition size, and account for the replicated reads that splitting can add.
If the metrics point away from join skew, shift from AQE tuning to reducing the workload. Match the fix to the metric pattern, then check both runtime and results.
FAQs
Can increasing shuffle partitions fix skew that AQE misses?
Increasing shuffle partitions won’t always fix skew that Adaptive Query Execution (AQE) misses. It can increase parallelism, but join keys with too much data can still overload some tasks while others sit idle.
If skew persists, use filtering, pre-aggregation, or key salting to spread work more evenly across your cluster.
How can I choose a salt bucket count for hot keys?
Choose a bucket count that fits the severity of the data skew and your cluster’s capacity. For example, adding a random suffix with CONCAT(key, '_', CAST(RAND() * 10 AS INT)) spreads the data across 10 buckets. Balance the load across available executors so individual tasks don’t become bottlenecks.
How do I detect skew caused by null join keys?
Check task metrics and execution plans for stages where one task processes much more data or takes much longer than the others. Then look for too many null values in the join key columns. These nulls can pile data into a single reducer or task, creating stragglers that slow down the join.