Spark Join Strategies: Broadcast vs Shuffle, Visualized

Every Spark join is a bet on how data moves across the network. Broadcast the small table and skip the shuffle entirely, or shuffle both sides and sort — here's how Spark's planner picks, when it picks wrong, and what data skew does to the bill.

Every Spark job I’ve seen die has died at a join. Not at the read, not at the write — at the moment two datasets that live on different machines need to meet. The join is where the network bill comes due, and the strategy Spark picks determines whether that bill is megabytes or terabytes.

This is the third post in the Spark series. The first one explained how a DataFrame becomes stages — narrow transformations stay in one stage, wide ones like joins force a shuffle boundary. The second one showed the engine inferring the DAG from your reads. This one goes one level deeper: once the planner knows there’s a join, how does it execute it?

There are three physical strategies for equi-joins, and understanding all three — plus the exact conditions under which Spark picks each — is the single highest-leverage piece of Spark performance knowledge I know.

The three strategies, in one picture

Three physical join strategies: broadcast hash join copies the small table to every executor with zero shuffle, sort-merge shuffles and sorts both sides, shuffle hash shuffles both sides and builds hash tables with no sort
The three physical equi-join strategies: broadcast skips the shuffle, sort-merge is the default workhorse, shuffle hash is the specialist.

The planner’s decision order is roughly this:

  1. Can one side be broadcast? If the smaller side’s estimated size is under spark.sql.autoBroadcastJoinThreshold (default 10 MB), Spark collects it to the driver, serializes it, ships a copy to every executor, and each executor hash-joins it against its local slice of the big table. No Exchange nodes, no shuffle of the big side. This is the fastest option by a wide margin whenever it applies.
  2. Otherwise, is sort-merge deprioritized and one side much smaller? If spark.sql.join.preferSortMergeJoin is false and one side is much smaller than the other (Spark checks a configured size ratio), it picks the shuffle hash join: both sides are still hash-partitioned across the network, but each partition builds an in-memory hash table of the smaller side instead of sorting.
  3. Otherwise, sort-merge. Both sides shuffle, both sides sort, then a merge join walks the two sorted runs. It’s the default for large × large joins, and it’s the most robust: sorts can spill to disk, so it won’t OOM the way hash tables can.

Join hints (BROADCAST, MERGE, SHUFFLE_HASH) let you override the planner when you know better — but Spark only applies a hint when it’s valid for the join at hand. A hint is a strong suggestion, not a command.

Broadcast hash join: the cheapest shuffle is the one you skip

Broadcast is the strategy you should reach for first, because its cost profile is almost unfair: the big table doesn’t move at all.

Broadcast hash join: the dimension table is collected to the driver and broadcast to every executor, while the fact table partitions are read locally with no shuffle
Broadcast hash join: the small table goes everywhere, the big table never moves.

The mechanics, step by step:

  1. The small side is collected to the driver — yes, the driver, which is why broadcasting a table that’s bigger than you thought is the classic driver-OOM story.
  2. The driver serializes it and creates a broadcast variable; every executor receives a full copy.
  3. Each executor builds a hash table from its copy and streams its local partitions of the big table through it.

Two knobs matter. spark.sql.autoBroadcastJoinThreshold (default 10M, i.e. 10,485,760 bytes) is the maximum size Spark will broadcast on its own; set it to -1 to disable automatic broadcasting entirely. The broadcast() function (or the BROADCAST hint) forces it regardless of size — which is how you broadcast a 200 MB dimension table you know fits comfortably in executor memory, and also how you shoot yourself in the foot if it doesn’t.

There’s one subtlety that bites people exactly once: the build side depends on the join type. In a LEFT JOIN, the left side is preserved, so only the right side can be the broadcast side — wrapping the small left table in broadcast() won’t do what you expect. (Full outer joins can’t broadcast at all.) And one more: the planner decides on estimated sizes from table statistics or file metadata. If your statistics are stale — after a heavy filter, say — Spark may broadcast a table that’s actually 2 GB, or shuffle a table that’s actually 3 MB. ANALYZE TABLE is cheap insurance; explain() is how you check what the planner actually chose.

Sort-merge join: the default workhorse

When neither side is small enough to broadcast, Spark’s default is the sort-merge join, and it earns that default by being nearly impossible to kill: it handles any size, and its sorts spill to disk when memory runs out.

Shuffle joins: both tables are hash-partitioned by the join key across the network, and one hot key can bloat a single partition into a straggler task
Shuffle joins: both sides hash-partitioned by key — and the skew problem that haunts them.

The three phases, visible in explain() as Exchange → Sort → SortMergeJoin on both sides:

  1. Shuffle. Both DataFrames are hash-partitioned by the join key (Exchange hashpartitioning(...)), so rows with the same key land on the same partition. This is the expensive part: the entire contents of both tables cross the network.
  2. Sort. Each partition is sorted by the join key. Sorting is CPU-heavy but memory-safe — it spills.
  3. Merge. A merge join walks both sorted runs, emitting matches. Linear in the partition size once sorted.

Sort-merge needs an equi-join with sortable keys, and it works for every join type including full outer. It’s also the strategy that benefits most from preparation: if both sides are already bucketed or partitioned by the join key, the shuffle (and sometimes the sort) disappears from the plan. That’s the real payoff of bucketing — not faster reads, but joins that don’t shuffle.

Shuffle hash join: the one Spark almost never picks

Shuffle hash sits in an awkward middle: it shuffles like sort-merge (both sides cross the network) but skips the sort, building an in-memory hash table of the smaller side in each partition instead. No sort step means less CPU — but the build side must fit in memory per partition, which is a stricter requirement than it sounds.

Spark’s planner is conservative about it. With spark.sql.join.preferSortMergeJoin at its default true, the planner will essentially never choose shuffle hash on its own. It becomes a candidate when you flip that config to false (or use the SHUFFLE_HASH hint) and one side is much smaller than the other — big enough that broadcasting is off the table, small enough that per-partition hash tables are plausible.

When does it win in practice? Medium × large joins where the smaller side is, say, hundreds of megabytes: too big to broadcast comfortably, much smaller than the multi-terabyte fact table, and the sort phase of a sort-merge would dominate the runtime. The honest way to find out is to test it — force the strategy with a hint, compare stage times in the Spark UI, and watch executor memory. If the build side has any skew (see below), the hash table on the hot partition is where your OOM will come from.

Skew: the hot key problem

All of the above assumes keys are roughly evenly distributed. Real data laughs at that assumption. One customer_id with 40% of all orders — a default account, a test user, a null that got coalesced — and hash partitioning sends 40% of the fact table to a single partition.

For sort-merge, the hot partition means one straggler task doing a huge sort and merge while 199 executors sit idle; the job takes as long as the slowest task. For shuffle hash, it’s worse: the hot partition’s hash table can blow past executor memory and OOM the task. Broadcast joins, notably, don’t care — there’s no key shuffle, so a hot key changes nothing.

Spark’s answer is Adaptive Query Execution’s skew handling. With AQE enabled, Spark watches partition sizes at runtime and splits skewed partitions — by default, a partition counts as skewed when it’s more than 5× the median partition size (spark.sql.adaptive.skewJoin.skewedPartitionFactor) and larger than 256 MB (spark.sql.adaptive.skewJoin.skewedPartitionThresholdInBytes). The split partitions are then joined separately and unioned.

AQE helps, but the durable fixes are in your control:

  • Salt the key. Add a random salt to the hot key on the big side and replicate the small side’s matching rows across salts (df.withColumn("salt", floor(rand() * 10))), join on (key, salt). It spreads the hot key across partitions at the cost of duplicating the small side’s hot rows.
  • Isolate and broadcast. Filter the hot key out, broadcast-join just those rows against the dimension table, and union with the regular join of the rest.
  • Fix the data. A hot key is often a data-quality smell — a default -1 customer or a null key. Sometimes the right fix is upstream.

Try it live: the Join Lab

Enough theory — drive the strategies yourself:

JOINLAB — LIVE
Pick a join strategy, size the tables, watch the data move
The small table is collected to the driver, serialized, and shipped to every executor. Each executor builds a hash table and joins it against its local slice of the big table — zero shuffle.
dim_customers size25.0 MB
fact_orders size5.0 GB
executors4
autoBroadcastJoinThreshold10 MB
dim_customers25.0 MB · 104,858 rowsfact_orders5.0 GB · 38,347,922 rowsbroadcast × 4 executorsno shuffle — read locallyE1dim copyfact✓ local joinE2dim copyfact✓ local joinE3dim copyfact✓ local joinE4dim copyfact✓ local joindim (25.0 MB) is copied to all 4 executors — fact (5.0 GB) never crosses the networktotal broadcast traffic: 100 MB
Network moved
100 MB
broadcast traffic (dim × executors)
Bytes shuffled
0 B
no Exchange nodes
Stages
2 (gather + join)
no sort step
⚠ You overrode the planner
Spark's planner would choose Sort-merge join — you picked Broadcast hash join. The plan above shows what your choice costs: 100 MB moved vs 5.0 GB for the planner's pick.
== Physical Plan == BroadcastHashJoin (build right) :- Scan parquet fact_orders +- BroadcastExchange +- Scan parquet dim_customers
All three strategies at these sizes (winner highlighted)
strategynetwork movedshuffledstagesplanner
BHJ100 MB0 B2 (gather + join)—
SMJ5.0 GB5.0 GB3 (2 shuffles + join)✓ picks this
SHJ ★5.0 GB5.0 GB3 (2 shuffles + join)—
When each strategy wins (at your current settings)
★ Shuffle hash join wins here: dim is much smaller (5.0 GB vs 25.0 MB) but too big to broadcast — shuffle hash skips the sort. Spark won't pick it by default though: it needs a SHUFFLE_HASH hint or preferSortMergeJoin=false.
BHJ · hint
Needs an explicit broadcast() hint above 10.0 MB. Remember the whole dim is collected to the driver first — raise the threshold with care.
SMJ · solid
Default for large × large. Sorts spill to disk instead of OOMing — slow but safe.
SHJ · worth testing
dim is much smaller but not broadcastable — shuffle hash skips the sort. Needs a SHUFFLE_HASH hint or preferSortMergeJoin=false; Spark will not pick it on its own.
Note: simulated in your browser — sizes, byte counts and stage counts are a deterministic teaching model, not a Spark run. Real strategy selection also weighs table statistics, join hints, and Adaptive Query Execution, which can rewrite the plan at runtime.

Two experiments worth running. First: set the dimension table to 25 MB and the fact table to 5 GB, then switch between broadcast and sort-merge and watch the network-bytes number — that’s the cost of one wrong planner decision. Second: flip the skew toggle with sort-merge selected and watch the hot partition appear; then switch to broadcast and notice that skew stops mattering. The planner-verdict banner tells you when your pick disagrees with what Spark would do on its own — including the byte-count difference, so you can see exactly what an override costs.

The cheat sheet

StrategyWhen it winsWatch out for
Broadcast hash joinOne side ≤ autoBroadcastJoinThreshold (10 MB default); star-schema dimension joinsDriver OOM if the small side is bigger than estimated; wrong build side on outer joins
Sort-merge joinBoth sides large and similarly sized; the safe defaultFull shuffle of both sides; stragglers under skew
Shuffle hash joinSmaller side much smaller but not broadcastable; sort phase dominatesNever picked by default (preferSortMergeJoin=true); build-side OOM, especially with skew

And the configs, in one place:

ConfigDefaultEffect
spark.sql.autoBroadcastJoinThreshold10MMax size (bytes) Spark will broadcast automatically; -1 disables
spark.sql.join.preferSortMergeJointrueWhen false, shuffle hash becomes a candidate for uneven joins
spark.sql.broadcastTimeout300sHow long to wait for the broadcast variable to be built
spark.sql.adaptive.skewJoin.enabledtrue (Spark 3.x)Split skewed partitions at runtime
spark.sql.adaptive.skewJoin.skewedPartitionFactor5Skew = bigger than 5× median partition…
spark.sql.adaptive.skewJoin.skewedPartitionThresholdInBytes256M…and bigger than 256 MB

Three habits that prevent most join pain: run explain() before you tune anything (the physical plan tells you which strategy was actually chosen); keep table statistics fresh so the 10 MB broadcast decision is made on real numbers; and treat a hot key as a data problem first and a tuning problem second. The join is where Spark jobs go to die — but only when the data moves further than it has to.

Sources

Keep reading