DataEng Hub
Spark SQLintermediateArticle · 10 min read

Broadcast Join vs Sort-Merge Join vs Shuffle Hash Join: How Spark Chooses

How each Spark join strategy moves data, the rules Spark uses to pick one, how AQE changes the choice at runtime, and when to step in with a hint.

Balaji S.
Lead Data Engineer

TL;DR

  • Broadcast hash join (BHJ): copy the small side to every executor; the big side never shuffles. Fastest, as long as the small side really is small.
  • Sort-merge join (SMJ): shuffle and sort both sides by the key, then merge. The default for big-to-big joins; scales and spills gracefully.
  • Shuffle hash join (SHJ): shuffle both sides, build a hash table from the smaller side in each partition, no sort. Faster than SMJ when that hash table fits; risky when it doesn't.
  • Spark picks from estimated sizes: broadcast if one side is under spark.sql.autoBroadcastJoinThreshold (10 MB) and the join type allows it, otherwise usually SMJ.
  • AQE re-plans with real sizes after the shuffle, and can turn SMJ into BHJ (10 MB in OSS Spark, 30 MB on Databricks) or SHJ. Hints override both.

The problem

NorthBridge's margin report joined 2 billion sales lines to five dimensions: stores (2,400 rows), products (180,000), promotions (40,000), suppliers (9,000) and a customer dimension (38 million).

The plan used sort-merge joins for all five. That meant shuffling the 2-billion-row fact table five times, once per join, about 1.4 TB of shuffle. The four small dimensions had no table statistics, so Spark didn't know they were small.

After ANALYZE TABLE on the dimensions, four joins became broadcast joins and the fact table shuffled once (for the customer join). Shuffle dropped to 290 GB, runtime from 64 minutes to 14.

Key concepts

Concept What it means Why it matters here
Equi-join Join condition is equality on keys (a.k = b.k) Only equi-joins can use hash and sort-merge strategies
Build side The side loaded into a hash table Must fit in memory
Stream side The side iterated row by row against the build side Can be any size
Broadcast Sending a full copy of a dataset to every executor Avoids shuffling the other side
Statistics Size and row count estimates from the catalog or file sizes The planner's only input before running
Join hint BROADCAST, MERGE, SHUFFLE_HASH, SHUFFLE_REPLICATE_NL Overrides the planner's choice

Decision chain Spark follows to pick a join strategy, AQE's runtime switches, and what each strategy costs Planned from estimates, then corrected by AQE from real shuffle sizes.

The three strategies

Broadcast hash join

  1. The small side is collected (via the driver) and broadcast to every executor.
  2. Each executor builds a hash table from it.
  3. Each task of the big side probes the hash table for its rows. No shuffle of the big side.
== Physical Plan ==
*(2) BroadcastHashJoin [store_id#12], [store_id#88], Inner, BuildRight, false
:- *(2) Filter isnotnull(store_id#12)
:  +- *(2) ColumnarToRow
:     +- FileScan parquet northbridge.silver.sales_lines ...
+- BroadcastExchange HashedRelationBroadcastMode(...)
   +- *(1) Filter isnotnull(store_id#88)
      +- FileScan parquet northbridge.silver.stores ...

Limits:

  • The broadcast side must fit in driver memory and every executor's memory. There's a hard limit of 8 GB, but you'll hit memory problems well before that.
  • Which side can be broadcast depends on the join type:
Join type Side that can be broadcast
Inner, cross Either
Left outer, left semi, left anti Right only
Right outer Left only
Full outer Neither (BHJ not possible)

A LEFT JOIN from a small table to a big one can't broadcast the big one, which is why join order and type matter.

Sort-merge join

  1. Both sides are shuffled by the join key so matching keys land in the same partition.
  2. Each partition is sorted by the key on both sides.
  3. Both sorted streams are merged in one pass.
SortMergeJoin [customer_id#20], [customer_id#140], LeftOuter
:- Sort [customer_id#20 ASC NULLS FIRST], false, 0
:  +- Exchange hashpartitioning(customer_id#20, 200), ENSURE_REQUIREMENTS
:     +- FileScan parquet northbridge.silver.sales_lines ...
+- Sort [customer_id#140 ASC NULLS FIRST], false, 0
   +- Exchange hashpartitioning(customer_id#140, 200), ENSURE_REQUIREMENTS
      +- FileScan parquet northbridge.silver.customers ...

It's the default for large joins because sorting can spill to disk; neither side has to fit in memory. The cost is two shuffles and two sorts. AQE can split its skewed partitions; see Data Skew in Spark.

Shuffle hash join

  1. Both sides are shuffled by the join key, like SMJ.
  2. In each partition, the smaller side is loaded into a hash table.
  3. The other side streams through and probes it. No sort.

It saves the sort, which can be a big win, and since Spark 3.1 it supports full outer joins. But the hash table for each partition must fit in memory; one big or skewed partition can mean OOM. That's why Spark prefers SMJ by default (spark.sql.join.preferSortMergeJoin=true).

How Spark chooses

For an equi-join with no hints, roughly:

  1. Broadcast hash join if one side's estimated size is below spark.sql.autoBroadcastJoinThreshold (default 10 MB) and the join type allows broadcasting that side.
  2. Shuffle hash join if preferSortMergeJoin is false and one side is small enough to build a hash map per partition (and much smaller than the other side).
  3. Sort-merge join if the join keys are sortable. This is where most large joins end up.
  4. Otherwise shuffle hash join if possible, and as a last resort a broadcast nested loop join or cartesian product.

For non-equi joins (a.ts BETWEEN b.start AND b.end, a.x < b.y), hash and sort-merge strategies can't be used. Spark picks a broadcast nested loop join if one side can be broadcast, otherwise a cartesian product for inner joins. Both compare every row with every row and get very slow on big inputs. On Databricks, the range join optimization (RANGE_JOIN hint) helps for point-in-interval and interval-overlap joins.

Where the size estimate comes from

The planner only knows what statistics tell it:

Source Estimate quality
Delta table on Databricks Size from the transaction log; generally good
Table with ANALYZE TABLE ... COMPUTE STATISTICS Good, if recent
Plain Parquet path, no catalog stats File size on disk (compressed), so in-memory size is underestimated
Subquery or DataFrame after filters/aggregations Propagated estimates; can be far off

Stale or missing statistics are the most common reason a small table isn't broadcast. Compressed-size estimates are the most common reason a "small" table that gets broadcast blows up memory.

ANALYZE TABLE northbridge.silver.stores COMPUTE STATISTICS;
DESCRIBE EXTENDED northbridge.silver.stores;   -- look for Statistics: ... bytes, ... rows

How AQE changes the choice

With AQE on (the default), the join is first planned from estimates. Then, after the shuffle map stages for both sides finish, AQE knows the actual sizes and can re-plan:

  • SMJ → BHJ if one side's actual size is below the adaptive broadcast threshold. In OSS Spark that's spark.sql.adaptive.autoBroadcastJoinThreshold (defaults to the static threshold, 10 MB); on Databricks it's spark.databricks.adaptive.autoBroadcastJoinThreshold, 30 MB by default.
  • SMJ → SHJ if every post-shuffle partition is below spark.sql.adaptive.maxShuffledHashJoinLocalMapThreshold (default 0, which disables it).
  • Split skewed partitions in SMJ and SHJ.

The runtime switch to broadcast happens after both sides have been shuffled, so it saves the sort and the reduce-side work, not the shuffle itself. That's why a correct broadcast decision at planning time (good statistics or a hint) is still better than relying on AQE to rescue it.

Confirm what ran in Spark UI → SQL / DataFrame: the final plan (isFinalPlan=true) shows the strategy that actually executed. EXPLAIN before running only shows the initial plan. See Reading the Spark UI.

Hints

# Databricks Runtime 16.4 LTS+, PySpark
from pyspark.sql import functions as F
 
sales = spark.table("northbridge.silver.sales_lines")
stores = spark.table("northbridge.silver.stores")
customers = spark.table("northbridge.silver.customers")
 
sales.join(F.broadcast(stores), "store_id")                       # BROADCAST
sales.join(customers.hint("shuffle_hash"), "customer_id")          # SHUFFLE_HASH
sales.join(customers.hint("merge"), "customer_id")                 # MERGE (sort-merge)
SELECT /*+ BROADCAST(s) */ *
FROM northbridge.silver.sales_lines f
JOIN northbridge.silver.stores s ON f.store_id = s.store_id;
 
SELECT /*+ SHUFFLE_HASH(c) */ *
FROM northbridge.silver.sales_lines f
JOIN northbridge.silver.customers c ON f.customer_id = c.customer_id;

Rules:

  • If both sides have hints, the priority is BROADCAST > MERGE > SHUFFLE_HASH > SHUFFLE_REPLICATE_NL.
  • A hint that can't be honoured is ignored with a warning, e.g. BROADCAST on the left side of a left outer join.
  • A broadcast hint ignores the size threshold. That's the point, and the danger: the table grows, the hint stays.

To stop automatic broadcasting entirely (for debugging, or a cluster with a tiny driver), set spark.sql.autoBroadcastJoinThreshold to -1. On Databricks, also set the adaptive threshold, or AQE can still switch to broadcast at runtime.

Choosing in practice

Situation Strategy How
Fact to small dimension (< tens of MB in memory) BHJ Stats, or F.broadcast
Fact to medium dimension (hundreds of MB) BHJ if executors have room, else SMJ Test; watch driver and executor memory
Big to big SMJ Default; ensure AQE skew handling is on
Big to big, well-distributed keys, sort is the bottleneck SHJ SHUFFLE_HASH hint, after checking partition sizes
Same key, several joins Join once, reuse Aggregate or join before branching
Range or interval condition BNLJ / range join Broadcast the small side; Databricks RANGE_JOIN hint
Left join where the left side is the small one Can't broadcast the right Consider rewriting as right join, or filter the big side first

A broader point from Star Schema in the Lakehouse: dimensional models produce exactly the joins BHJ is best at. Keeping dimensions narrow and well-maintained (stats, compaction) keeps them broadcastable.

The result

After statistics on the four small dimensions, NorthBridge's margin report broadcast stores, products, promotions and suppliers, and used a sort-merge join for customers. AQE split two skewed customer partitions. Shuffle fell from 1.4 TB to 290 GB, runtime from 64 minutes to 14, and the job moved to a smaller cluster.

From production: gotchas and lessons

  1. Symptom: A 3 MB dimension was joined with a sort-merge join. Cause: No statistics; it was read from a path, not a table, after a distinct() that made estimates unknown. Fix: Read it as a catalog table with stats, or F.broadcast() it explicitly.

  2. Symptom: Driver OOM at month-end, fine the rest of the month. Cause: A BROADCAST hint on a promotions table that grew 10× during month-end campaigns. Fix: Removed the hint; let stats and AQE decide. Hints are for tables whose size you control.

  3. Symptom: BroadcastTimeout after 300 seconds. Cause: The broadcast side was the output of an expensive query, and building it took longer than spark.sql.broadcastTimeout. Fix: Materialize the small side first (write it, or cache it), or raise the timeout if the build is legitimately slow.

  4. Symptom: A left join from a 50-row lookup to a billion-row table was very slow. Cause: In a left outer join only the right side can be broadcast, and the right side was the huge one. Fix: Swap the sides as a right join (or restructure the query) so the small table is the one broadcast.

  5. Symptom: A join with ON a.ts BETWEEN b.valid_from AND b.valid_to ran for hours. Cause: No equality condition, so Spark used a nested loop join. Fix: Add an equality key too (a.product_id = b.product_id AND a.ts BETWEEN ...) so Spark can hash or sort-merge on it, and use the range join hint on Databricks.

Performance and cost notes

Shuffle is the expensive part of most joins: every byte is written to local disk, sent over the network and read back. A broadcast join shuffles nothing on the big side, so turning one SMJ on a large fact table into a BHJ is often the single biggest win in a job. But a broadcast is copied to every executor; a 500 MB broadcast on a 100-node cluster moves 50 GB and takes 500 MB of memory on each node.

When not to use this

Don't hint every join. The planner plus AQE get most joins right when statistics are current. Use hints when you've seen the wrong choice in the final plan, and know the table's size won't change underneath the hint.

Checklist

  • Statistics current on dimension tables
  • Small dimensions broadcast in the final plan
  • No broadcast hints on tables that grow unpredictably
  • Join types checked for which side can be broadcast
  • Big-to-big joins use SMJ with AQE skew handling on
  • Non-equi joins have an equality key where possible
  • Final plan read in the SQL tab, not just EXPLAIN

Practice

Further reading

#joins#broadcast#sort-merge#shuffle-hash#aqe#query-plan

Keep going

Article10 min read

Data Skew in Spark: Detect It and Fix It

Find the hot key behind a stage that never finishes, then fix it with AQE skew joins, key cleanup, hot-key isolation or salting, in that order.

One practical note a week

Get new articles, problems and guides in your inbox.