Shuffle partitions
Every shuffle in Spark splits the data into a fixed number of pieces, 200 by default, whatever the data size. 200 is too many for a small job and far too few for a big one. This lesson shows what the setting controls, how to size it, and how adaptive query execution helps.
Step 2 · Spark internals · Silver · Shuffles and joins, lesson 2 of 5
On this page
Show code in
Every code block on the page follows this.
Read first: Partitions · Narrow vs wide transformations (skip if you know them)
In plain words first
Sorting the post for a town, you decide in advance how many sorting bins to use. For a village, 200 bins means most of them hold one letter. For a city, 200 bins overflow. The right number depends on how much post there is.
spark.sql.shuffle.partitions is the number of bins every shuffleshuffle: 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 → uses.
What it controls
Every Exchange created by a DataFrame join, groupBy, distinct or window splits data into this many partitionspartition: 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 →, so the next stagestage: A group of steps Spark can run without moving data between machines. A new stage starts at every shuffle. Learn more → runs this many taskstask: The work for one partition in one stage, run on one CPU core. Learn more →. It does not affect reading files (that is maxPartitionBytes) or explicit repartition(n) calls.
Why 200 is rarely right
| Shuffle size | With 200 partitions | Effect |
|---|---|---|
| 200 MB | 1 MB each | 200 tiny tasks, scheduling overhead dominates, and 200 small output files if written |
| 20 GB | 100 MB each | About right |
| 2 TB | 10 GB each | Huge tasks spillspill: Writing data to local disk because it does not fit in memory. Slower, but the job keeps running. Learn more → to disk, run for a long time, may fail with out-of-memory |
Sizing it
Divide the largest shuffle in the job by a target partition size. Read the shuffle size from the Spark UI (Stages tab, "Shuffle Write").
Rule of thumb
partitions ≈ largest shuffle size / 128-200 MB 2 TB / 200 MB ≈ 10,000 partitions then round to a multiple of the total cores, so the last wave of tasks is full
spark.conf.set("spark.sql.shuffle.partitions", "2000")
SET spark.sql.shuffle.partitions = 2000;
It is a session setting read when a query is planned, so you can change it between steps of a job when stages have very different sizes.
With AQE
Since Spark 3.2, AQEAQE: Adaptive Query Execution: Spark re-plans a running query using the real data sizes it has measured. Learn more → is on by default and coalesces small shuffle partitions after measuring them, toward spark.sql.adaptive.advisoryPartitionSizeInBytes (64 MB). That changes the advice:
- Set the initial number high enough for your largest shuffle. AQE only merges partitions; it does not split ordinary ones.
- AQE can choose the initial number itself from
spark.sql.adaptive.coalescePartitions.initialPartitionNumif set. - Small shuffles now come out right automatically, so the 200 MB example above becomes a handful of tasks.
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: Set the shuffle partition count for the job's biggest shuffle, and let AQE merge the partitions that turn out small.
import os from pyspark.sql import functions as F # Sized for the job's largest shuffle (about 128 MB each); AQE merges the small ones. spark.conf.set("spark.sql.shuffle.partitions", "400") spark.conf.set("spark.sql.adaptive.enabled", "true") spark.conf.set("spark.sql.adaptive.coalescePartitions.enabled", "true") spark.conf.set("spark.sql.adaptive.advisoryPartitionSizeInBytes", "128m") daily = (spark.range(0, 1_000_000) .groupBy((F.col("id") % 30).alias("day")) .agg(F.count(F.lit(1)).alias("events"))) daily.write.mode("overwrite").parquet("lab/shuffle_partitions/daily") files = [f for f in os.listdir("lab/shuffle_partitions/daily") if f.endswith(".parquet")] print(len(files), "file(s) written, not 400") spark.read.parquet("lab/shuffle_partitions/daily").orderBy("day").show(5)
Output from a real run
1 file(s) written, not 400 +---+------+ |day|events| +---+------+ | 0| 33334| | 1| 33334| | 2| 33334| | 3| 33334| | 4| 33334| +---+------+ only showing top 5 rows
What to notice:
1 file(s) written, not 400: the shuffle asked for 400 partitions, but the data was tiny, so AQE merged them into one.- The result is correct: 1,000,000 events over 30 days is about 33,334 a day.
Goal: See how many partitions a shuffle produces, and what AQE does with them.
import contextlib, io from pyspark.sql import functions as F # a DataFrame fixes its plan when first used: rebuild after settings change def make_query(): return spark.range(0, 1_000_000).groupBy((F.col("id") % 10).alias("k")).count() spark.conf.set("spark.sql.adaptive.enabled", "false") print("AQE off:", make_query().rdd.getNumPartitions(), "partitions") spark.conf.set("spark.sql.shuffle.partitions", "8") print("AQE off, 8 partitions set:", make_query().rdd.getNumPartitions(), "partitions") spark.conf.set("spark.sql.shuffle.partitions", "200") spark.conf.set("spark.sql.adaptive.enabled", "true") q = make_query() # run it, so the plan below is the final one q.collect() buf = io.StringIO() with contextlib.redirect_stdout(buf): q.explain() print("AQE on, partitions coalesced:", "coalesced" in buf.getvalue())
Output from a real run
AQE off: 200 partitions AQE off, 8 partitions set: 8 partitions AQE on, partitions coalesced: True
What to notice:
- With AQE off, a shuffle gives exactly
spark.sql.shuffle.partitionspartitions: 200 by default, 8 when set to 8. - With AQE on, the plan shows the 200 partitions were coalesced into fewer, because the data was small.
Common mistakes
- Leaving 200 for a multi-terabyte job — Gigantic tasks, spills and OOMs.
- Setting it low and trusting AQE — AQE merges; it does not split normal partitions.
- Confusing it with spark.default.parallelism — That one applies to RDD operations, not DataFrame shuffles.
Key takeaways
- spark.sql.shuffle.partitions (200) sets the partition count of every DataFrame shuffle.
- Size it from the largest shuffle: about 128 to 200 MB per partition.
- With AQE, start high and let it merge down.
- Streaming queries keep the number from their checkpoint.
Interview prep
THE QUESTION
"Do you still need to tune spark.sql.shuffle.partitions with AQE?"
Avoid: "AQE handles it, so the setting no longer matters". AQE only coalesces downward; a too-low starting value still gives huge partitions.
Follow-ups · answer out loud, then open
Follow-up"How would you size spark.sql.shuffle.partitions for a stage that shuffles 2 TB?"
Scenario"A streaming query was started with 200 shuffle partitions. You change the setting to 50 and restart. What happens?"
Trap"More shuffle partitions is always safer."
Check yourself
3 questionsWhat does spark.sql.shuffle.partitions affect?
Show the answer
The number of partitions after DataFrame shuffles. It sets the partition count for joins, aggregations and other exchanges.
A job shuffles 1 TB. Roughly how many shuffle partitions is reasonable?
Show the answer
5,000 to 8,000. 1 TB / 128-200 MB gives roughly 5,000 to 8,000.
With AQE on, should the initial number be low or high?
Show the answer
High enough for the largest shuffle; AQE merges small ones. Coalescing only merges, so start high.
Practise this
Interview problems on spark performance, graded on hidden tests
Keep going
Up next · Shuffles and joins · lesson 3 of 5 · 8 min readJoin strategies
Broadcast hash, shuffle hash, sort-merge and nested loop joins: how Spark picks one, and how to steer it.
Related lessons
Adaptive Query ExecutionSpark internals · 7 min read
PartitionsSpark internals · 8 min read
The small file problem
Previous: Narrow vs wide transformations
Primary sources: Performance tuning · Configuration