Spark & PySpark
Spark Join Optimization - Beyond the Basics
Your Spark Join Is Causing a 45-Minute Shuffle. Here Are the Five Techniques That Bring It Under 3 Minutes.

TL;DR
- Spark has three main join strategies: broadcast hash join (no shuffle), sort-merge join (full shuffle both sides), and skew join handling — knowing which one is running is the first step to fixing performance
- The broadcast threshold default is 10 MB — raising it to 100–200 MB eliminates shuffles on many dimension joins, but the ceiling depends on executor memory and table stability
- Sort-merge join shuffles both sides of the join across the network — this is the dominant cost in most slow Spark jobs, and the fix is almost always eliminating the shuffle, not making it faster
- AQE can switch join strategies at runtime — a sort-merge join planned for a large table can become a broadcast hash join after filtering reduces one side — but only if statistics are current
- One skewed join key can cause a single task to run for hours while the rest finish in minutes — learn to spot it in the Spark UI before it becomes a production incident
The slowest join is the one you did not know was a sort-merge join.
A daily aggregation job was taking 3 hours. The team had been tuning executor memory for two weeks. Added nodes. Raised heap. Adjusted memory fraction. Nothing moved.
Nobody opened the SQL tab in the Spark UI. Everyone assumed memory was the bottleneck because the executors were dying with OOM errors. The OOM errors were real — caused by shuffle pressure from a join that should never have been a shuffle.
When someone finally checked the physical plan: a sort-merge join between a 400 GB transactions table and a 600 MB merchant lookup table.
600 MB. Shuffled across 80 executors. Every day. Because the broadcast threshold was 10 MB and nobody had changed it since the cluster was provisioned.
One config change. Runtime: 47 minutes. Two weeks of memory tuning: completely irrelevant.
How Spark Chooses a Join Strategy
Before you can fix a slow join, you need to know which strategy Spark chose and why.
Spark’s query planner selects a join strategy based on table size estimates from statistics. When statistics are accurate, the planner makes good decisions. When statistics are stale or missing — which is the common case — the planner falls back to conservative assumptions that often produce sort-merge joins where broadcast joins would be faster and cheaper.
The three strategies you will encounter in practice:
Broadcast hash join: one side is small enough to copy to every executor. No shuffle on the large side. Fastest possible join. Used when one side is under spark.sql.autoBroadcastJoinThreshold (default: 10 MB).
Sort-merge join: both sides are shuffled by join key, sorted, and merged. Correct for any data size. Expensive — two full shuffles, two sorts. Default when neither side qualifies for broadcast.
Shuffle hash join: one side is hashed into a hash table, the other is streamed against it. Avoids the sort cost. Used when one side is significantly smaller than the other but still above the broadcast threshold. Less common — disabled by default in many configurations.
The decision tree:
Is smaller side < autoBroadcastJoinThreshold?
Yes → broadcast hash join (fast, no shuffle on large side)
No → Is spark.sql.join.preferSortMergeJoin = true? (default)
Yes → sort-merge join (safe, expensive)
No → shuffle hash join if size ratio favors itThe most impactful change most teams can make: raise the broadcast threshold and ensure table statistics are current.
The Join Optimization Ladder
Before tuning any join, work through these questions in order. Stop as soon as you find a yes.
1. Can one side be broadcast?
→ Check table size. If under 200 MB and executor memory allows:
broadcast it. You are done. This eliminates the shuffle entirely.
2. Can data be reduced before the join?
→ Apply filters and column selection before the join.
Every row and column eliminated before the shuffle
is bytes that never cross the network.
3. Is skew present?
→ Check Spark UI → Stages → task duration distribution.
If one task is 5× the median: fix skew first.
Enable AQE skew join. If AQE isn't enough, salt manually.
4. Is this join repeated frequently on the same key?
→ Consider bucketing. Write the tables bucketed once,
eliminate the shuffle on every subsequent run.
Verify in the SQL tab that Exchange nodes disappear.
5. None of the above apply?
→ Accept sort-merge join. Ensure shuffle partitions are
sized correctly (target 100–200 MB per partition as a
starting point) and that both sides are filtered
as aggressively as possible before the shuffle.Most join performance problems are resolved at step 1 or 2. Steps 3–5 exist for the cases where the first two options are not available.
Strategy 1: Broadcast Hash Join
When Spark Uses It
Spark broadcasts the smaller table when its estimated size is below spark.sql.autoBroadcastJoinThreshold. The default is 10 MB — chosen conservatively because broadcasting a table that is larger than executor memory causes OOM.
In practice, most dimension tables (merchants, products, customers, regions) are well under 500 MB. Broadcasting them eliminates the shuffle on the large fact table entirely.
Forcing It When Spark Doesn’t
If statistics are stale, Spark may estimate a 200 MB table as larger than it is and fall back to sort-merge. Two ways to fix this:
from pyspark.sql.functions import broadcast
# Option 1: raise the threshold globally
spark.conf.set("spark.sql.autoBroadcastJoinThreshold", 200 * 1024 * 1024) # 200 MB
# Option 2: hint explicitly per join — overrides statistics
result = transactions.join(
broadcast(merchants),
on="merchant_id",
how="inner"
)
# Option 3: refresh statistics so the planner makes the right call automatically
spark.sql("ANALYZE TABLE merchants COMPUTE STATISTICS FOR ALL COLUMNS")The explicit broadcast hint is the most reliable. It works regardless of statistics freshness and makes the intent visible in the code.
When It Goes Wrong
Broadcasting a table that does not fit in executor memory causes OOM on the executor side — not the driver. The error looks like an executor failure rather than an obvious broadcast problem, which makes it harder to diagnose.
A safe upper bound: do not broadcast tables larger than 20–25% of executor memory. On an executor with 8 GB and spark.memory.fraction = 0.6, that is roughly 1–1.5 GB as an absolute ceiling.
A practical ceiling for most teams: 200 MB on executors with 8+ GB. On smaller executors or with volatile dimension tables, lower is safer. Broadcasting a 600 MB table requires large executors and confidence that the table fits — not a default recommendation.
Also: broadcasting is controlled by the driver, but the broadcast data lives in executor memory. On a cluster with 50 executors, a 300 MB broadcast table consumes 15 GB of aggregate executor memory — distributed, but not free.
Strategy 2: Sort-Merge Join
How It Works
When both sides are too large to broadcast, Spark falls back to sort-merge join:
- Both sides are shuffled by join key — every row with the same key lands on the same executor
- Each partition on both sides is sorted by join key
- The sorted partitions are merged (like a merge-sort) to produce join output
This is correct for any data size. It is also the most expensive join strategy — two full network shuffles, two sorts, significant memory pressure during the sort phase.
The Cost You Are Paying
The shuffle is the dominant cost. Every byte in both tables crosses the network at least once. On a 400 GB fact table joined with a 600 MB lookup, you are shuffling 400.6 GB across the network — every run.
The sort adds memory pressure. During the sort phase, each executor must hold its partition of both sides in memory simultaneously. If the partition is larger than execution memory, it spills — and sort spills are particularly expensive because the sort must restart from partially spilled state.
Reducing Sort-Merge Cost
The goal is to eliminate the shuffle where possible, and reduce the data volume before the shuffle where it is not.
# Technique 1: filter aggressively before joining
# Every row eliminated before the shuffle is a row that doesn't cross the network
# WORSE: join first, filter after
result = transactions.join(merchants, "merchant_id") \
.filter("transaction_date >= '2026-01-01'")
# BETTER: filter before join explicitly
# Catalyst often pushes predicates down automatically,
# but intermediate transformations between the filter and the join
# can block predicate pushdown silently.
# Explicit pre-filtering makes intent clear and guarantees
# the filter runs before the shuffle regardless of plan shape.
transactions_recent = transactions.filter("transaction_date >= '2026-01-01'")
result = transactions_recent.join(merchants, "merchant_id")
# Technique 2: select only needed columns before joining
# Reduces shuffle bytes proportionally to columns dropped
transactions_slim = transactions.select(
"transaction_id", "merchant_id", "amount", "transaction_date"
)
result = transactions_slim.join(merchants, "merchant_id")
# Technique 3: pre-sort and bucket to eliminate the shuffle entirely
# Requires writing bucketed tables — only worth it for repeated joins on the same key
# Write bucketed (do this once, reuse many times)
transactions.write \
.bucketBy(200, "merchant_id") \
.sortBy("merchant_id") \
.saveAsTable("transactions_bucketed")
merchants.write \
.bucketBy(200, "merchant_id") \
.sortBy("merchant_id") \
.saveAsTable("merchants_bucketed")
# Join on bucketed tables — can significantly reduce or eliminate
# shuffle and sort costs when Spark correctly leverages the bucketing.
# Requires matching bucket counts, same bucketing key, and
# spark.sql.sources.bucketing.enabled = true (default).
# Modern Spark does not always fully exploit bucketing — verify
# in the SQL tab that Exchange nodes are absent before assuming savings.
result = spark.table("transactions_bucketed") \
.join(spark.table("merchants_bucketed"), "merchant_id")Bucketing is the most powerful optimization for repeated joins on the same key — it eliminates the shuffle entirely. The trade-off: writing bucketed tables takes longer and requires pre-knowledge of the join keys.
Strategy 3: Skew Join Handling
A skewed join is a sort-merge join where one key appears far more often than others. The executor handling that key processes 80% of the data while the others finish in minutes and sit idle. The stage cannot complete until the slow executor finishes.
Detecting the Skewed Key
# Step 1: find which keys are disproportionately frequent
transactions.groupBy("merchant_id") \
.count() \
.orderBy(F.col("count").desc()) \
.show(10)
# If the top merchant has 10M rows and the median has 5K rows,
# that merchant_id will skew any join on merchant_id.
# Step 2: confirm skew is happening in a running job
# Spark UI → Stages → click the slow stage → Tasks tab
# Sort by Duration descending
# If one task is 10× the median duration: skew confirmedAQE Automatic Skew Handling
Enable this first — it handles the common case with no code changes:
spark.conf.set("spark.sql.adaptive.enabled", "true")
spark.conf.set("spark.sql.adaptive.skewJoin.enabled", "true")
spark.conf.set("spark.sql.adaptive.skewJoin.skewedPartitionFactor", "5")
spark.conf.set("spark.sql.adaptive.skewJoin.skewedPartitionThresholdInBytes", "256mb")AQE detects partitions that are significantly larger than the median and splits them into sub-partitions that are processed in parallel. When it works, you see tasks marked “(skewed)” in the Spark UI’s task list for that stage.
AQE skew handling works well for moderate skew — a few keys with 5–10× more data than average. It may not fully resolve extreme skew where one key has 100× the median volume. For that, manual salting is still necessary.
Manual Salting When AQE Is Not Enough
# Use salting when AQE skew join doesn't resolve the straggler
SALT_FACTOR = 10 # start low — 5 to 10 — increase only if skew persists
# higher values reduce skew but replicate the small side more
# Salt the large (skewed) table
transactions_salted = transactions.withColumn(
"salt",
(F.rand() * SALT_FACTOR).cast("int")
).withColumn(
"merchant_id_salted",
F.concat(F.col("merchant_id"), F.lit("_"), F.col("salt"))
)
# Explode the small table to match all salt values
merchants_exploded = merchants.withColumn(
"salt_exploded",
F.explode(F.array([F.lit(i) for i in range(SALT_FACTOR)]))
).withColumn(
"merchant_id_salted",
F.concat(F.col("merchant_id"), F.lit("_"), F.col("salt_exploded"))
)
# Join on salted key — skewed partition is now distributed
result = transactions_salted.join(
merchants_exploded,
on="merchant_id_salted"
).drop("salt", "salt_exploded", "merchant_id_salted")The cost: the merchants table is replicated SALT_FACTOR times. Verify that the merchants table is small enough that this replication is cheaper than the skewed straggler task.
Reading the Join Strategy in the Spark UI
The SQL tab in the Spark UI shows the physical query plan — including which join strategy Spark chose for each join in your query.
What to look for:
BroadcastHashJoin → broadcast hash join. No shuffle on the large side. Fast.
SortMergeJoin → sort-merge join. Full shuffle on both sides. Look at the shuffle read/write size for this stage to understand the cost.
ShuffledHashJoin → shuffle hash join. One full shuffle, no sort. Cheaper than sort-merge but requires one side to fit in memory as a hash table.
BroadcastNestedLoopJoin → a fallback for non-equi joins or when other strategies fail. Almost always a performance problem — avoid non-equi joins on large tables.
The plan also shows Exchange nodes — each one is a shuffle. Count them. Fewer exchanges means fewer full data movements across the network.
AQE Join Strategy Switching
AQE can change the join strategy at runtime based on actual data sizes observed after filtering and aggregation. This is one of its most valuable features.
A query that joins two tables — one 100 GB, one 50 GB — gets planned as a sort-merge join. During execution, a filter reduces the 50 GB table to 80 MB. AQE detects this after the filter stage completes and switches the join to a broadcast hash join before executing the join stage.
The result: the join that was planned as a 150 GB sort-merge join executes as an 80 MB broadcast — no shuffle on the large side.
# Enable AQE join switching
spark.conf.set("spark.sql.adaptive.enabled", "true")
# AQE will automatically switch SortMergeJoin → BroadcastHashJoin
# when one side shrinks below the broadcast threshold after filtering
# Ensure the threshold is set high enough to catch most cases
spark.conf.set("spark.sql.autoBroadcastJoinThreshold", "200mb")
# Verify it happened: in the SQL tab, look for:
# "AdaptiveSparkPlan" wrapping the join
# The join type annotation may show the original plan vs the adaptive planAQE join switching only works when the actual size after filtering is below the broadcast threshold. If your filtered table is still 5 GB, the join stays as sort-merge. The threshold is the lever.
The Five Join Mistakes
1. Never checking which join strategy Spark chose
The most common mistake. Engineers tune executor memory, adjust partition counts, add nodes — while Spark is running a sort-merge join on a 300 MB dimension table that could be broadcast. Five minutes in the SQL tab would have shown this immediately.
Check the join strategy before tuning anything else. It is the highest-impact and lowest-effort check.
2. Not filtering before joining
Every row eliminated before a shuffle is a row that does not cross the network. A filter that reduces a 500 GB table to 100 GB before a join saves 400 GB of shuffle traffic. Spark’s Catalyst optimizer usually pushes filters down, but explicit pre-filtering before joins is clearer and guaranteed.
3. Broadcasting without checking executor memory
The broadcast hint bypasses the threshold check entirely. broadcast(my_table) will attempt to broadcast regardless of size. If the table is larger than the executor's available memory, the executor dies with an OOM error that looks nothing like a broadcast problem — it surfaces as ExecutorLostFailure with no obvious connection to the join.
# Before adding the broadcast hint, verify the table size
table_size_bytes = merchants.rdd.map(lambda row: len(str(row))).sum()
table_size_mb = table_size_bytes / (1024 * 1024)
print(f"Estimated table size: {table_size_mb:.1f} MB")
# Rule of thumb: only broadcast if size < 20% of executor memory
executor_memory_mb = 8192 # 8 GB
safe_broadcast_ceiling_mb = executor_memory_mb * 0.20
if table_size_mb > safe_broadcast_ceiling_mb:
print(f"WARNING: table may be too large to broadcast safely on this cluster")Using broadcast() as a performance hint without verifying the table size is one of the most common causes of unexplained executor failures in join-heavy pipelines.
4. Using a sort-merge join when one side is moderately small
If one side of a join is 500 MB and the broadcast threshold is at the default 10 MB, Spark does a full sort-merge join on a table that could be broadcast. Raising the threshold to 200 MB takes one line and eliminates the shuffle. Most teams never do this.
5. Ignoring the skew signal until it becomes an incident
A task that runs 10× longer than the median is a skew signal. Most engineers notice it, assume it will average out, and move on. It does not average out — it gets worse as data volume grows. A 10-minute straggler at 100 GB becomes a 4-hour straggler at 1 TB.
Check the task duration distribution in the Spark UI for any stage taking longer than expected. If one task is an outlier, find the skewed key and fix it before the data grows.
Final Takeaway
Most slow Spark joins are not slow because of cluster size, executor memory, or network bandwidth. They are slow because the wrong join strategy is running — usually a sort-merge join where a broadcast would work, or a sort-merge join with a skewed key that turns 40 executors into 1.
The Spark UI shows you exactly which strategy is running. Check it first. Fix the strategy before tuning anything else.
📌 Core Principle
The fastest join is the one that moves the least data across the network. Know which strategy is running. Eliminate the shuffle before you tune it.
Next in Series
️Writing Production-Grade PySpark — Patterns That Scale
Your joins are optimized. Your partitions are sized correctly.
Next: the code patterns that make PySpark jobs survive production — schema enforcement at ingestion, null handling that doesn’t silently corrupt aggregations, reusable transformation functions that don’t break when data changes, and how to test PySpark locally before it fails in the cluster.