VAYULearn
Colour theme
Investigate a failure
VAYU Learn

Spark & PySpark

Partitioning Strategy for Spark - The Decision That Determines Everything

Wrong Partitioning Is the Root Cause of Most Spark Performance Problems. Here Is How to Get It Right the First Time.

Spark & PySpark
More hardware does not fix wrong partitioning. It just makes the wrong partitioning more expensive.

TL;DR

  • Partition count is the single most impactful configuration in any Spark job — too few causes spill and OOM, too many causes scheduling overhead
  • The formula is simple: target 100–200 MB per partition as a safe starting point — adjust based on your workload’s compute intensity and executor memory, calculate from actual data size, set explicitly — never rely on defaults
  • repartition does a full shuffle and is expensive; coalesce avoids the shuffle but can produce skewed output — know when each is appropriate
  • Partition skew is when one partition holds a disproportionate share of data — one executor runs for hours while the rest finish in minutes
  • AQE fixes many forms of skew automatically, but some skew patterns — extreme imbalance, upstream data layout issues, thresholds not met — still require manual intervention

The default shuffle partition count of 200 was chosen for a world of smaller clusters and smaller data. It is wrong for most production jobs.


The job ran in 25 minutes on the staging cluster. On production — same code, ten times the data — it took 4 hours.
Nobody touched the partition config between environments. Staging had 50 GB. Production had 500 GB. 200 shuffle partitions on 500 GB = 2.5 GB per partition. Executors with 4 GB of execution memory were spilling constantly.
One config change: spark.sql.shuffle.partitions = 2500. Production job: 90 minutes.
The code was fine the whole time.

Wrong Partitioning Compounds Through Every Stage

Partitioning is not a tuning parameter you adjust after the job is slow. It is a structural decision that affects every stage in the DAG.

Too few partitions: each partition is too large to fit in executor memory. Spill to disk. Every stage runs slower. Join stages become bottlenecks. The job looks like it needs more memory — but what it actually needs is more partitions.

Too many partitions: each partition is tiny. Thousands of tasks get scheduled for microseconds of work. The task scheduling overhead dominates. The driver struggles to track partition metadata. The job looks slow despite the cluster being mostly idle.

The right partition count sits in a range where each partition is large enough to justify its task overhead but small enough to fit comfortably in executor memory during the most expensive operation in the job.


What a Partition Actually Is

A partition is a contiguous chunk of data that lives on one executor at a time. One partition = one task. One task runs on one core.

This has two immediate implications:

The maximum parallelism of any stage equals the number of partitions in that stage. A job with 20 executors and 8 cores each can run 160 tasks simultaneously. If you have 50 partitions, you are using 50 cores — 110 are idle.

The memory pressure on each executor is proportional to the partition size of its current task. A 4 GB partition on an executor with 3 GB of execution memory will spill. A 100 MB partition will not.

Partition count is set at three moments: when data is read, when data is repartitioned explicitly, and after a shuffle. Each has different controls.


The Partitioning Trap

Engineers think about cluster size. Spark thinks about partition size. These are different things and the mismatch is where most partitioning problems live.

A cluster with 100 nodes and 200 partitions runs on 200 cores — the other 600 sit idle. Adding more nodes does nothing. The bottleneck is partition count, not hardware.

A cluster with 4 nodes and well-sized partitions runs efficiently. Each core stays busy, execution memory is used without spilling, and the job completes faster than the 100-node job with wrong partitioning.

This is why engineers consistently get partitioning wrong: they optimize for cluster size and assume Spark will parallelize correctly. Spark parallelizes exactly as much as the partition count allows — no more.

The practical consequence:

Scenario A: 10 TB dataset, 100 nodes, 200 shuffle partitions
→ 200 tasks, each 50 GB
→ most executors idle waiting for spilling tasks
→ job fails or runs for hours

Scenario B: 100 GB dataset, 4 nodes, 800 shuffle partitions
→ 800 tasks, each 125 MB
→ all cores utilized, no spill
→ job completes cleanly in 20 minutes

More hardware does not fix wrong partitioning. It just makes the wrong partitioning more expensive.


The Partition Sizing Formula

At Read Time

When Spark reads Parquet or other columnar formats from object storage, the number of read partitions is controlled by:

# Max bytes per partition at read time
spark.conf.set("spark.sql.files.maxPartitionBytes", "134217728") # 128 MB default

# Minimum number of partitions — useful for very small files
spark.conf.set("spark.sql.files.minPartitionNum", "8")

# To see how many partitions your read produced:
df = spark.read.parquet("s3://bucket/data/")
print(f"Read partitions: {df.rdd.getNumPartitions()}")

128 MB is a reasonable default for most workloads. For compute-intensive transformations per row, lower it to 64 MB so each task completes faster. For I/O-heavy jobs with minimal transformation, 256 MB is fine.

At Shuffle Time

After any operation that requires data redistribution — groupBy, join, distinct, orderBy — Spark creates a new set of partitions. The count is controlled by:

# The formula
# target_partitions = total_shuffle_data_size_MB / target_partition_size_MB
# target_partition_size_MB = 128 (safe starting point — tune from here)
# compute-heavy jobs: try 64 MB | I/O-heavy jobs: 256 MB+ is reasonable

# Example: 500 GB shuffle
# 500,000 MB / 128 MB = ~3,900 partitions
spark.conf.set("spark.sql.shuffle.partitions", "3900")

The data size you care about is the shuffle write size — the output of the map stage, before it is read by the reduce stage. Find this in the Spark UI under Stages → Shuffle Write.

If you do not know the shuffle size in advance, start with:

# Rule of thumb for setting shuffle partitions without profiling first:
# partitions = max(200, num_executors × num_cores_per_executor × 2)
#
# For a cluster with 20 executors × 8 cores:
# partitions = max(200, 20 × 8 × 2) = max(200, 320) = 320
#
# This is a starting point. Profile and adjust from the Spark UI.

num_executors = 20
cores_per_executor = 8
shuffle_partitions = max(200, num_executors * cores_per_executor * 2)
spark.conf.set("spark.sql.shuffle.partitions", str(shuffle_partitions))

Then enable AQE to coalesce partitions that turn out to be smaller than expected:

spark.conf.set("spark.sql.adaptive.enabled", "true")
spark.conf.set("spark.sql.adaptive.coalescePartitions.enabled", "true")
spark.conf.set("spark.sql.adaptive.coalescePartitions.minPartitionSize", "64mb")

repartition vs coalesce — When to Use Which

These two operations both change partition count. They work completely differently.

repartition

repartition(n) does a full shuffle — every row is redistributed across n new partitions using a hash function. The result is evenly distributed by design.

Use it when:

  • You need to increase partition count
  • You need to redistribute data evenly before a skew-prone join
  • You are writing output files and need a specific number of files
# Increasing partitions — always use repartition
df = df.repartition(500)

# Repartition by a specific column — collocates rows with the same key
# Useful before a join on that column
df = df.repartition(500, "customer_id")

Cost: a full shuffle. Every row crosses the network. On a large dataset this is expensive — use it deliberately, not by default.

coalesce

coalesce(n) reduces partition count without a full shuffle. It combines adjacent partitions on the same executor. Fast and cheap — but the result can be uneven, especially if the input partitions are already skewed.

Use it when:

  • You are reducing partition count before writing output
  • You want to avoid creating too many small output files
  • The input data is already evenly distributed
# Reducing partitions before writing — coalesce is appropriate
df.coalesce(10).write.parquet("s3://bucket/output/")

Do not use coalesce to reduce partitions before a heavy computation. If you coalesce from 1000 to 10 before a join, you now have 10 large tasks instead of 1000 small ones. Spill becomes likely. Use repartition if you need to rebalance before computation.

The Decision Rule

Need to increase partition count?     → repartition
Need even distribution before a join? → repartition
Need to reduce count before writing? → coalesce
Need to reduce count before compute? → repartition (not coalesce)

Detecting Partition Skew

Partition skew is when one partition holds significantly more data than the others. In practice this looks like: 39 tasks finish in 4 minutes, one task runs for 90 minutes. The stage cannot complete until the slow task finishes. Your 40-executor cluster is effectively running on 1 executor for most of the stage.

The Spark UI Signal

Open the Stages tab. Click into the slow stage. Look at the task duration distribution — specifically the gap between median duration and maximum duration.

If median task time is 2 minutes and max task time is 90 minutes, you have skew. The skewed partition is almost certainly associated with a high-frequency key value.

Also check the task size distribution in the same view. A task processing 50 GB while others process 100 MB is unmissable.

The Code Signal

# Diagnose skew before it becomes a 90-minute stage
def diagnose_partition_skew(df, sample_fraction=0.1):
partition_sizes = (
df.sample(fraction=sample_fraction)
.withColumn("partition_id", F.spark_partition_id())
.groupBy("partition_id")
.count()
.orderBy(F.col("count").desc())
)

stats = partition_sizes.agg(
F.max("count").alias("max_rows"),
F.mean("count").alias("avg_rows"),
F.min("count").alias("min_rows")
).collect()[0]

skew_ratio = stats.max_rows / stats.avg_rows
print(f"Max partition: {stats.max_rows:,} rows")
print(f"Avg partition: {stats.avg_rows:,.0f} rows")
print(f"Skew ratio: {skew_ratio:.1f}x")

if skew_ratio > 5:
print("WARNING: significant skew detected — consider salting or AQE skew join")
elif skew_ratio > 2:
print("CAUTION: moderate skew — monitor stage task duration in Spark UI")
else:
print("OK: partition distribution is healthy")

return skew_ratio

diagnose_partition_skew(transactions_df)

A skew ratio above 5× is a problem worth fixing. Below 2× is generally fine.


Fixing Partition Skew

Salting

Salting breaks a high-frequency key into multiple artificial sub-keys, distributing the data across more partitions. It is the manual fix when AQE cannot handle the skew.

import pyspark.sql.functions as F
from pyspark.sql.types import IntegerType

SALT_FACTOR = 20 # split each skewed key into 20 sub-keys
# starting point — begin with 5–10 and increase only if skew persists
# higher values reduce skew but multiply small-table memory cost

# Step 1: add salt to the large table
transactions_salted = transactions_df.withColumn(
"salt",
(F.rand() * SALT_FACTOR).cast(IntegerType())
).withColumn(
"customer_id_salted",
F.concat(F.col("customer_id"), F.lit("_"), F.col("salt"))
)

# Step 2: explode the small table to match all salt values
customers_exploded = customers_df.withColumn(
"salt_exploded",
F.explode(F.array([F.lit(i) for i in range(SALT_FACTOR)]))
).withColumn(
"customer_id_salted",
F.concat(F.col("customer_id"), F.lit("_"), F.col("salt_exploded"))
)

# Step 3: join on the salted key
result = transactions_salted.join(
customers_exploded,
on="customer_id_salted",
how="inner"
).drop("salt", "customer_id_salted", "salt_exploded")

The trade-off: the small table (customers) is replicated SALT_FACTOR times. For a 1 GB customers table with SALT_FACTOR=20, you are holding 20 GB in memory during the join. Make sure the small table is actually small before salting.

AQE Skew Join

Spark 3.0+ detects and handles skewed join partitions automatically when AQE is enabled. It splits oversized partitions and processes them in parallel without requiring code changes.

spark.conf.set("spark.sql.adaptive.enabled", "true")
spark.conf.set("spark.sql.adaptive.skewJoin.enabled", "true")

# A partition is considered skewed when:
# size > skewedPartitionFactor × median partition size
# AND size > skewedPartitionThresholdInBytes
spark.conf.set("spark.sql.adaptive.skewJoin.skewedPartitionFactor", "5")
spark.conf.set("spark.sql.adaptive.skewJoin.skewedPartitionThresholdInBytes", "256mb")

AQE skew join handles the common case — one or a few high-frequency keys — without code changes. It does not help when skew is caused by a data quality issue (nulls concentrated in one partition, a corrupted key) or when skew is extreme enough that splitting still produces partitions that are too large.

When AQE handles the skew: the Spark UI shows split tasks in the affected stage — you will see some tasks marked with “(skewed)” in the task list.

When AQE cannot handle it: the stage still has one outlier task and you need to salt manually.


The Four Partitioning Mistakes

These appear in production jobs constantly, including at teams that have been running Spark for years.

1. Never changing the shuffle partition default

spark.sql.shuffle.partitions = 200 ships as the default. On any dataset over 100 GB, this often produces partitions large enough to cause spill on typical executor configurations — though the exact threshold depends on your executor memory and workload. The fix takes one line. The cost of not fixing it compounds through every shuffle stage in every job.

Set this explicitly for every job. There is no universal right answer — it depends on data size and cluster configuration — but any explicit value beats the default for production workloads over 100 GB.

2. Using coalesce before a heavy computation

df.coalesce(10).groupBy(...).agg(...) seems reasonable. It is not. You have reduced 1000 evenly-distributed partitions to 10 very large partitions. The groupBy now has 10 tasks, each processing 100× more data than necessary. Spill follows.

Coalesce before writes. Repartition before computation.

3. Repartitioning without knowing the key distribution

df.repartition(500, "customer_id") distributes data by customer_id hash. If one customer_id represents 40% of your data, that partition gets 40% of the data — immediately skewed. Before repartitioning by a key, check the key distribution.

# Check key distribution before repartitioning by it
df.groupBy("customer_id") \
.count() \
.orderBy(F.col("count").desc()) \
.show(10)
# If the top key has 10× the rows of the median key, do not repartition by it

4. Setting shuffle partitions globally for a multi-stage job

A job with five stages may need different partition counts at each stage. The shuffle partition count set at the SparkSession level applies to all shuffles. Stage 1 might need 200 partitions (10 GB input). Stage 4 might need 5000 partitions (500 GB intermediate data).

AQE coalesce handles the downward adjustment automatically. For upward adjustments mid-job, set the config inside the job logic before the stage that needs it:

# Changing shuffle partitions mid-job is technically possible
# but should be rare — AQE coalesce handles most cases automatically.
# Reserve this for situations where AQE is disabled or where a specific
# stage has dramatically different data volume than the rest of the job.

# Stage 1 — small data, AQE will coalesce down from a higher default
spark.conf.set("spark.sql.shuffle.partitions", "2000")
df_clean = df_raw.groupBy("date").agg(F.sum("amount"))

# Only override manually if profiling shows AQE isn't handling it correctly:
# spark.conf.set("spark.sql.shuffle.partitions", "200") # explicit override

Final Takeaway

Partitioning is not a performance optimization. It is a correctness decision about how your data is physically distributed across executors. Get it wrong and every stage in your job pays the price — in spill, in skew, in idle cores, in 4-hour jobs that should take 40 minutes.

The defaults exist for compatibility, not performance. Set partition counts explicitly, check the distribution before repartitioning by a key, and let AQE handle the cases where the optimal count depends on runtime data sizes.

Core Principle

One wrong partition decision at the start
compounds through every stage that follows.
Measure first. Set explicitly.
Never trust the default on production data.

Next in Series

Spark Join Optimization — Beyond the Basics

Your join is causing a 45-minute shuffle.

Next: the five techniques that bring it under 3 minutes — broadcast join thresholds, sort-merge join internals, skew join handling with salting, AQE join strategy switching, and the specific Spark UI signals that tell you exactly which join strategy is running and whether it is the right one.