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
The planner’s decision order is roughly this:
- 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. NoExchangenodes, no shuffle of the big side. This is the fastest option by a wide margin whenever it applies. - Otherwise, is sort-merge deprioritized and one side much smaller? If
spark.sql.join.preferSortMergeJoinisfalseand 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. - 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.
The mechanics, step by step:
- 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.
- The driver serializes it and creates a broadcast variable; every executor receives a full copy.
- 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.
The three phases, visible in explain() as Exchange → Sort → SortMergeJoin on both sides:
- 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. - Sort. Each partition is sorted by the join key. Sorting is CPU-heavy but memory-safe — it spills.
- 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
-1customer or a null key. Sometimes the right fix is upstream.
Try it live: the Join Lab
Enough theory — drive the strategies yourself:
| strategy | network moved | shuffled | stages | planner |
|---|---|---|---|---|
| BHJ | 100 MB | 0 B | 2 (gather + join) | — |
| SMJ | 5.0 GB | 5.0 GB | 3 (2 shuffles + join) | ✓ picks this |
| SHJ ★ | 5.0 GB | 5.0 GB | 3 (2 shuffles + join) | — |
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
| Strategy | When it wins | Watch out for |
|---|---|---|
| Broadcast hash join | One side ≤ autoBroadcastJoinThreshold (10 MB default); star-schema dimension joins | Driver OOM if the small side is bigger than estimated; wrong build side on outer joins |
| Sort-merge join | Both sides large and similarly sized; the safe default | Full shuffle of both sides; stragglers under skew |
| Shuffle hash join | Smaller side much smaller but not broadcastable; sort phase dominates | Never picked by default (preferSortMergeJoin=true); build-side OOM, especially with skew |
And the configs, in one place:
| Config | Default | Effect |
|---|---|---|
spark.sql.autoBroadcastJoinThreshold | 10M | Max size (bytes) Spark will broadcast automatically; -1 disables |
spark.sql.join.preferSortMergeJoin | true | When false, shuffle hash becomes a candidate for uneven joins |
spark.sql.broadcastTimeout | 300s | How long to wait for the broadcast variable to be built |
spark.sql.adaptive.skewJoin.enabled | true (Spark 3.x) | Split skewed partitions at runtime |
spark.sql.adaptive.skewJoin.skewedPartitionFactor | 5 | Skew = bigger than 5× median partition… |
spark.sql.adaptive.skewJoin.skewedPartitionThresholdInBytes | 256M | …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
- Apache Spark configuration — Runtime SQL Configuration (
spark.sql.autoBroadcastJoinThreshold,spark.sql.join.preferSortMergeJoin, AQE skew configs) - Apache Spark Tuning Guide (join strategy guidance, broadcast variables)
- Spark SQL Programming Guide (join hints including
BROADCAST,MERGE,SHUFFLE_HASH) - Joins.scala — Spark’s planner source (the actual strategy-selection order, including the “much smaller” check)