# Spark adaptive query execution explained: shuffle partitions, broadcast joins and skew

Spark plans a query before it has seen the data, then adaptive query execution fixes the plan mid-flight. We ran one skewed join in PySpark 4.3 four ways and watched 200 shuffle partitions shrink to one, a sort-merge join become a broadcast join, and a hot key get split.

Most slow Spark jobs are slow for the same few reasons: a shuffle with the wrong number of partitions, a join that moves far more data than it needs to, or one key that holds a third of the rows. For years the fix was manual tuning, setting `spark.sql.shuffle.partitions` per job and adding join hints. Adaptive query execution (AQE) changed that. It lets Spark look at real statistics from completed stages and rewrite the rest of the plan while the query runs.

This article explains what AQE does, step by step, and measures it. We ran the same skewed join, four million orders against two hundred thousand customers, in PySpark 4.3.0 on a four-core local session, with AQE and broadcast joins switched on and off, and read the physical plans. The numbers are small, but the plan changes are exactly the ones you see on clusters.

## What happened

### Apache Spark 4.3.0 released (30 October 2026)

Apache Spark 4.3.0 was released on 30 October 2026. The release notes say it addressed over 1,100 Jira tickets from more than 210 contributors and marks the start of a quarterly feature-release cadence. Highlights include stateful queries in Structured Streaming Real-Time Mode with end-to-end latency on the order of 100 milliseconds, built on native concurrent stage scheduling and pipelined shuffles; SCD Type 2 in Auto CDC for Spark Declarative Pipelines; `JSON_TABLE` and `VARIANT` transformation functions; a SQL `ASOF JOIN`; and a preview of nanosecond-precision timestamps.

### Faster small-data queries and a REBALANCE hint option (30 October 2026)

Two items matter for tuning. Spark 4.3 adds opt-in shuffle-free single-task execution for small queries and opt-in Arrow-native Dataset caching, aimed at reducing fixed overhead when iterating on small data. It also supports an advisory partition size in the `REBALANCE` hint, so you can ask for output partitions of a target size directly in SQL. PyPI shows PySpark 4.3.0 published on 30 October 2026, with maintenance releases 4.2.1, 4.1.4 and 4.0.5 published on 27 October.

## Why shuffles are the expensive part

Spark splits a query into stages separated by **shuffles**. A shuffle happens whenever rows must be regrouped by key: for a join, a `groupBy`, a `distinct` or a window. Each task in the upstream stage writes its rows into buckets by key hash, and each task in the downstream stage fetches its bucket from every upstream task over the network or disk.

A shuffle is like a post office sorting room. Every van arrives with mixed letters, and each letter must be sorted into the right outgoing van by postcode. If you have far too many outgoing vans, most leave nearly empty. If you have too few, a few are overloaded. If one postcode gets a third of all mail, that van leaves hours late and everybody waits.

The number of outgoing vans is the number of shuffle partitions. Without AQE it is fixed by `spark.sql.shuffle.partitions`, which defaults to 200, regardless of whether the data is 10 megabytes or 10 terabytes.

## What AQE changes at runtime

AQE has been enabled by default since Spark 3.2.0 (`spark.sql.adaptive.enabled = true`). After each shuffle stage finishes, Spark knows the real size of every shuffle partition. It uses that to re-optimise the remaining plan. The Spark tuning guide describes three main features.

### 1. Coalescing post-shuffle partitions

Spark starts with many shuffle partitions and merges small neighbours after the map stage. With `spark.sql.adaptive.coalescePartitions.parallelismFirst = true` (the default), it ignores the advisory size (`spark.sql.adaptive.advisoryPartitionSizeInBytes`, default 64 MB) and only respects a minimum partition size (default 1 MB), to keep parallelism high. Setting `parallelismFirst` to false makes Spark aim for the 64 MB advisory size instead, which the guide recommends for busy clusters.

### 2. Converting sort-merge joins to broadcast joins

A sort-merge join shuffles both sides by key. A broadcast hash join sends the small side to every executor and never shuffles the large side. Spark chooses a broadcast join at planning time when the estimated size of one side is below `spark.sql.autoBroadcastJoinThreshold` (default 10 MB). Estimates are often wrong, especially after filters. AQE re-checks the real size after a stage runs and can switch to a broadcast join then, using `spark.sql.adaptive.autoBroadcastJoinThreshold`, which defaults to the same value.

### 3. Splitting skewed partitions in joins

A partition counts as skewed when it is larger than `spark.sql.adaptive.skewJoin.skewedPartitionFactor` (default 5.0) times the median partition size **and** larger than `spark.sql.adaptive.skewJoin.skewedPartitionThresholdInBytes` (default 256 MB). AQE splits such partitions into smaller pieces and duplicates the matching partition from the other side, so the hot key is processed by several tasks instead of one.

| AQE feature | Problem it fixes | Key setting and default |
|---|---|---|
| Coalesce partitions | Hundreds of tiny tasks after a shuffle | `coalescePartitions.enabled = true`, min size 1 MB, advisory 64 MB |
| Broadcast conversion | Shuffle of a large table joined to a table that turned out small | `autoBroadcastJoinThreshold`, 10 MB |
| Skew join | One huge partition makes one task run for ages | Factor 5.0 and threshold 256 MB, both must hold |
| Shuffled hash join conversion | Sorting cost when partitions are small enough for hash maps | `maxShuffledHashJoinLocalMapThreshold` |

## The experiment

We wrote two Parquet tables and joined them:

```python
from pyspark.sql import SparkSession, functions as F

spark = (SparkSession.builder.master("local[4]")
         .config("spark.sql.shuffle.partitions", "200").getOrCreate())

orders = (spark.range(0, 4_000_000)
  .withColumn("customer_id",
      F.when(F.col("id") % 10 < 3, F.lit(0))      # 30% of rows: customer 0
       .otherwise(F.col("id") % 200_000))
  .withColumn("amount", (F.col("id") % 1000) / 10.0))

customers = (spark.range(0, 200_000).withColumnRenamed("id", "customer_id")
  .withColumn("segment", F.element_at(
      F.array(F.lit("SMB"), F.lit("Consumer"), F.lit("Enterprise")),
      (F.col("customer_id") % 3 + 1).cast("int"))))

orders.write.mode("overwrite").parquet("/tmp/orders")
customers.write.mode("overwrite").parquet("/tmp/customers")

o = spark.read.parquet("/tmp/orders")
c = spark.read.parquet("/tmp/customers")
q = o.join(c, "customer_id").groupBy("segment").agg(F.sum("amount"))
```

Thirty percent of orders belong to one customer, a deliberate hot key. We ran the query after a warm-up, built a fresh DataFrame for each run, and took the median of three runs for each configuration.

### Results

| Configuration | Join chosen | Final result partitions | Median time |
|---|---|---|---|
| AQE off, broadcast disabled (`-1`) | SortMergeJoin | 200 | 4.42 s |
| AQE on, broadcast disabled | SortMergeJoin | 1 | 2.01 s |
| AQE off, broadcast threshold 10 MB | BroadcastHashJoin | 200 | 1.21 s |
| AQE on, broadcast threshold 10 MB | BroadcastHashJoin | 1 | 0.55 s |

All four returned the same answer: SMB 106,280,666.0, Consumer 46,760,002.0 and Enterprise 46,759,332.0.

Three lessons:

1. **Coalescing alone halved the time.** With AQE off, the final aggregation ran 200 tasks for three output rows. With AQE on, the plan shows `AQEShuffleRead coalesced` and a single partition.
2. **Broadcasting removed the big shuffle.** The customer table is small, so sending it to every task avoided shuffling four million orders at all. That was the largest single gain.
3. **They stack.** AQE plus broadcast was about eight times faster than neither.

Timings on a laptop are noisy and much smaller than on a cluster, but the direction is reliable because the plan changes are structural.

### Watching the skew handling

With broadcast disabled, the 30 percent hot key did not trigger skew handling, because no partition crossed the default 256 MB threshold on this small dataset. To see the mechanism, we lowered `skewedPartitionThresholdInBytes` and the advisory size to 1 MB. The final plan then showed:

```
SortMergeJoin(skew=true) [customer_id], [customer_id], Inner
:- Sort ...
:  +- AQEShuffleRead coalesced and skewed
:     +- ShuffleQueryStage 0
```

The join stage ran 24 tasks instead of a handful, because the partition holding customer 0 was split into several pieces. On real clusters, where one partition might be tens of gigabytes, this is the difference between a job that finishes and one with a single straggler task running for an hour.

## Reading a plan

Call `df.explain()` before running to see the initial plan, and inspect the final plan after running (in the Spark UI's SQL tab, or `df._jdf.queryExecution().executedPlan()` in PySpark as we did). Look for:

- `AdaptiveSparkPlan isFinalPlan=true`: AQE was active and the plan is final.
- `AQEShuffleRead coalesced`: small partitions were merged.
- `AQEShuffleRead ... skewed` and `SortMergeJoin(skew=true)`: skew splitting happened.
- `BroadcastHashJoin` versus `SortMergeJoin`: whether the large side was shuffled.
- `PushedFilters` on `FileScan parquet`: whether filters reached the Parquet reader.

## Tuning beyond AQE

AQE fixes the plan after a shuffle. It cannot fix what happens before the first shuffle or problems in your data layout.

| Symptom | Likely cause | Fix |
|---|---|---|
| Thousands of tiny input tasks | Many small files | Compact files or raise `spark.sql.files.maxPartitionBytes` |
| Huge first-stage tasks | Very large unsplittable files (for example gzip CSV) | Use splittable formats such as Parquet |
| Join still sort-merge with a small table | Statistics unknown or table just above threshold | Raise the threshold carefully or add a `broadcast()` hint |
| Skew remains | Hot key below thresholds, or skew in aggregation not join | Lower thresholds, or salt the key for aggregations |
| Too many output files | Partitioned writes with many partitions per task | `REBALANCE` hint, now with an advisory size in Spark 4.3 |
| Repeated recomputation | The same DataFrame reused in several actions | Cache or persist it deliberately, then unpersist |

Table formats help here too. Writing [Delta Lake](/tools/delta-lake) or Iceberg tables with compaction and clustering gives the first stage evenly sized files and file-level statistics, so less data reaches the first shuffle at all.

When one job is slow, work in order: open the Spark UI, find the longest stage, compare its median and maximum task times, and check shuffle read sizes per task. A maximum far above the median is skew. Many tasks reading kilobytes each is over-partitioning. A large shuffle read on a join with a small table is a missed broadcast. Each points to one row of the table above.

Salting is the manual fallback for skew AQE cannot see: add a random number from 0 to N to the hot key on the large side, explode the small side N times with the same numbers, join on both, then aggregate. It spreads one key across N tasks at the cost of duplicating the small side.

## What it means in practice

On Spark 3.2 and later, start with AQE's defaults rather than hand-tuning `spark.sql.shuffle.partitions` for every job. Set the initial number of shuffle partitions high enough for your largest stage and let coalescing shrink it. Check that small dimension tables are broadcast. Treat skew as a data problem first: AQE's thresholds are deliberately conservative, so a hot key in a 50 GB job may still need salting.

The same engine sits under many platforms, including [Databricks](/tools/databricks), [Amazon EMR](/tools/amazon-emr) and plain open-source clusters, so these settings carry across. The [Apache Spark](/tools/apache-spark) and [PySpark](/tools/pyspark) pages, the [big data engines topic](/topics/big-data/engines) and the [Apache Parquet](/tools/apache-parquet) page cover the surrounding pieces.

## What to do now

1. **Confirm AQE is on.** Check `spark.sql.adaptive.enabled` in your session; it is true by default since Spark 3.2.0.
2. **Read final plans, not just initial ones.** Look for coalesced reads, skew flags and broadcast joins in the Spark UI's SQL tab.
3. **Broadcast small dimensions.** Make sure tables under the threshold are actually broadcast, and use a `broadcast()` hint when statistics are missing.
4. **Set `parallelismFirst` deliberately.** On busy shared clusters, set it to false so Spark targets the 64 MB advisory size instead of maximum parallelism.
5. **Find hot keys.** Count rows per join key on big tables; any key above a few percent of rows is a skew candidate.
6. **Lower skew thresholds only with evidence.** Tune factor and threshold when the UI shows straggler tasks on known hot keys.
7. **Fix input layout.** Compact small files and use Parquet so the first stage starts with sensible task sizes.
8. **Try Spark 4.3 features on a branch.** Test the `REBALANCE` advisory size for writes and the opt-in small-query execution for interactive work.

## Risks and open questions

**Broadcasting the wrong side can crash drivers.** Raising the broadcast threshold too far can push large tables into memory on every executor.

**AQE thresholds may hide skew on mid-sized jobs.** The 256 MB default means moderate skew goes untreated, so straggler tasks can still dominate run time.

**Laptop benchmarks are directional only.** Local runs exaggerate fixed overheads and understate network costs; re-measure on your cluster.

**Opt-in features change behaviour.** Spark 4.3's shuffle-free small-query execution and Arrow-native caching are opt-in, so test them before enabling them broadly.

**Watch next:** how the quarterly release cadence starting with Spark 4.3 changes upgrade planning, and whether concurrent stage scheduling and pipelined shuffles, now used by Real-Time Mode, spread to batch workloads.

## Frequently asked questions

### What does adaptive query execution do in Spark?

It re-optimises a query while it runs, using real statistics from completed shuffle stages. It can merge small shuffle partitions, switch a sort-merge join to a broadcast join and split skewed partitions.

### Is AQE enabled by default?

Yes, since Spark 3.2.0 `spark.sql.adaptive.enabled` defaults to true. Its sub-features, such as coalescing partitions and skew join handling, are also enabled by default.

### Should I still set spark.sql.shuffle.partitions?

Set it as an upper bound that suits your largest stages, and let AQE coalesce downward. Without AQE, the default of 200 is often too many for small data and too few for very large data.

### Why did AQE not fix my skewed join?

A partition is treated as skewed only if it exceeds both 5 times the median partition size and 256 MB by default. Smaller hot partitions, or skew in aggregations rather than joins, need lower thresholds or manual salting.

### When should I use a broadcast join?

When one side of the join is small enough to fit comfortably in each executor's memory, typically a dimension table. It avoids shuffling the large side entirely, which was the biggest gain in our test.

## Summary

Spark's adaptive query execution uses statistics from finished shuffle stages to rewrite the rest of a query: it coalesces small partitions, converts sort-merge joins to broadcast joins when one side turns out small, and splits skewed partitions. In our PySpark 4.3.0 test on four million skewed orders, the median time fell from 4.42 seconds with neither AQE nor broadcast to 0.55 seconds with both, with identical results, and lowering skew thresholds made Spark split the hot key across more tasks. Spark 4.3.0, released on 30 October 2026, starts a quarterly cadence and adds tools such as an advisory size for the `REBALANCE` hint, but reading final plans and fixing data layout remain the core of Spark tuning.

## Sources

- [Apache Spark: Spark Release 4.3.0](https://spark.apache.org/releases/spark-release-4-3-0.html)
- [GitHub: Spark Release 4.3.0 notes source](https://github.com/apache/spark-website/blob/asf-site/releases/_posts/2026-10-30-spark-release-4-3-0.md)
- [Apache Spark: Performance Tuning guide](https://spark.apache.org/docs/latest/sql-performance-tuning.html)
- [GitHub: Spark SQL performance tuning docs source](https://github.com/apache/spark/blob/master/docs/sql-performance-tuning.md)
- [PyPI: pyspark release history](https://pypi.org/project/pyspark/#history)
- [Apache Spark: PySpark documentation](https://spark.apache.org/docs/latest/api/python/index.html)
