Skip to the page
Tecyfy

PySpark Joins: Broadcast, Sort-Merge and Shuffled Hash, and How Spark Chooses

How Spark joins two DataFrames: broadcast hash joins, sort-merge joins and shuffled hash joins, how Spark chooses between them, the join hints, what adaptive query execution changes at run time, and how to read the plan. Plans from PySpark 4.2.

Tecyfy · Published · Updated · 8 min read

Spark joins two DataFrames in one of two broad ways. A broadcast join copies the small side to every executor, so the large side is joined where it already sits, with no shuffle. A shuffle join moves the rows of both sides across the network so that equal keys land in the same partition, then joins each partition; Spark's default shuffle join is the sort-merge join. Spark picks a broadcast join by itself when one side is estimated to be under 10 MB, and you can force or forbid one with a hint or a setting.

Every plan below came from PySpark 4.2.

Broadcast join

When one side is small, such as a table of 1,000 products joined to a million orders, Spark sends a full copy of it to each executor and builds a hash table from it there:

from pyspark.sql import functions as F

joined = orders.join(products, "product_id")
joined.explain()
+- BroadcastHashJoin [product_id#2L], [product_id#4L], Inner, BuildRight, false, false
   :- ... Range (0, 1000000, ...)
   +- BroadcastExchange HashedRelationBroadcastMode(...)
      +- ... Range (0, 1000, ...)

There is no Exchange hashpartitioning on the orders side: the million rows never moved. That is the point of a broadcast join: the large side is not shuffled.

Spark chooses this on its own when its size estimate of a side is below spark.sql.autoBroadcastJoinThreshold, 10 MB by default. To force it for a table you know is small, wrap it in broadcast():

joined = orders.join(F.broadcast(products), "product_id")

The hint wins even when the setting is turned off. In our test, with spark.sql.autoBroadcastJoinThreshold set to -1, the plain join became a sort-merge join and the hinted one stayed a broadcast join.

The limits. The broadcast table is collected on the driver and then held in memory on every executor, so a table that is too large causes out-of-memory errors or a timeout (spark.sql.broadcastTimeout, 300 seconds by default). Not every join type can use a broadcast join, so Spark may ignore the hint: in our test, a broadcast() hint on either of those was ignored.

Shuffle joins

When both sides are large, Spark shuffles both by the join key into spark.sql.shuffle.partitions partitions, 200 by default, and joins each pair of partitions. Joining a million orders to 2 million payments:

+- SortMergeJoin [order_id#1L], [order_id#7L], Inner
   :- Sort [order_id#1L ASC NULLS FIRST], false, 0
   :  +- Exchange hashpartitioning(order_id#1L, 200)
   +- Sort [order_id#7L ASC NULLS FIRST], false, 0
      +- Exchange hashpartitioning(order_id#7L, 200)

The two Exchange lines are the shuffles, and the Sort lines are what make it a sort-merge join: both sides are sorted by key within each partition and then merged. It is Spark's default for large joins because it works for any size, spilling to disk when a partition does not fit in memory.

A shuffled hash join shuffles the same way but builds a hash table from the smaller side of each partition instead of sorting both. It skips the sort, which helps when one side is much smaller than the other but too big to broadcast, but each partition's hash table must fit in memory. Ask for it with a hint:

joined = orders.join(payments.hint("shuffle_hash"), "order_id")   # ShuffledHashJoin

The full list of join strategy hints is broadcast, merge (sort-merge), shuffle_hash and shuffle_replicate_nl (a nested loop join, for joins with no equality condition). When both sides carry different hints, Spark prefers them in that order. A hint is a request, not a guarantee: Spark ignores a hint the join type cannot use.

Broadcast or shuffle?

Broadcast hash joinSort-merge joinShuffled hash join
WhenOne side small (under 10 MB by default, more with the hint)Both sides largeOne side much smaller, too big to broadcast
Data movedSmall side copied to every executorBoth sides shuffledBoth sides shuffled
MemoryWhole small side on every executorCan spill to diskEach partition of the smaller side
Skew in the large sideNo effectSlow tasks; AQE can split themSlow tasks
Chosen bySize estimate, or broadcast()Default for large joinsshuffle_hash hint, or AQE

What adaptive query execution changes

Spark's choice before a query runs depends on size estimates, which can be missing or inaccurate. Adaptive query execution (AQE), on by default since Spark 3.2.0, revisits the plan after each shuffle using the real sizes:

  • It turns a sort-merge join into a broadcast join when one side turns out at run time to be under the broadcast threshold (spark.sql.adaptive.autoBroadcastJoinThreshold, which defaults to the same 10 MB). This is not as efficient as planning a broadcast join from the start, because the shuffle has already happened, but it skips the sort.
  • It turns a sort-merge join into a shuffled hash join when every partition is small enough, if you set spark.sql.adaptive.maxShuffledHashJoinLocalMapThreshold.
  • It combines small shuffle partitions, so the 200 default partitions do not become 200 tiny tasks.
  • It splits skewed partitions in sort-merge joins. See our guide to data skew in PySpark.

Because of AQE, you rarely need to tune spark.sql.shuffle.partitions by hand any more. Set it high enough for your largest shuffle and let AQE coalesce.

Note that df.explain() before the query runs shows AdaptiveSparkPlan isFinalPlan=false: the plan AQE starts from. To see what actually ran, look at the SQL tab of the Spark UI, or the plan after an action, where it reads isFinalPlan=true.

Making joins faster

  1. Filter and select before joining. Fewer rows and narrower rows mean less to shuffle or broadcast. Spark pushes filters down for you where it can, but it cannot drop columns you later use.
  2. Broadcast dimension tables that are small but which Spark's estimate misses, for instance after a filter.
  3. Check the plan for BroadcastHashJoin, SortMergeJoin or ShuffledHashJoin, and in the Spark UI for one task that runs much longer than the others.
  4. Join on keys of the same type. A string key joined to a number forces a cast on every row.
  5. Fix skew when one key holds most of the rows, by letting AQE split it, broadcasting, or salting.

Tecyfy Takeaway

Broadcast the small side whenever it fits in memory: no shuffle of the large side. For two large tables Spark uses a sort-merge join, which shuffles and sorts both sides. Let AQE correct the plan at run time, read the plan to see which join ran, and reach for hints only when you know something about the sizes that Spark's estimates do not.

Questions

What is the difference between a broadcast join and a shuffle join in Spark?
A broadcast join copies the small side to every executor, so the large side is joined where it sits with no shuffle. A shuffle join moves rows of both sides across the network so equal keys land in the same partition, then joins each partition.
When does Spark use a broadcast join automatically?
When it estimates one side to be under spark.sql.autoBroadcastJoinThreshold, 10 MB by default. Adaptive query execution can also switch a sort-merge join to a broadcast join at run time when a side turns out to be small.
How do I force a broadcast join in PySpark?
Wrap the small DataFrame in broadcast(): orders.join(F.broadcast(products), 'product_id'). The hint works even when the automatic threshold is turned off, but Spark is not guaranteed to use it, since a strategy may not support every join type; in our test it ignored the hint for a full outer join and for the left side of a left outer join.
What is a sort-merge join?
Spark's default join for 2 large tables: both sides are shuffled by key, sorted within each partition and merged. It works for any size because it can spill to disk, but it moves and sorts all the data.
How large a table can I broadcast in Spark?
Spark broadcasts a side by itself only under spark.sql.autoBroadcastJoinThreshold, 10 MB by default. A broadcast() hint broadcasts it regardless of that threshold, but every executor holds a copy, and a broadcast that takes too long hits spark.sql.broadcastTimeout, 300 seconds by default. The table is collected on the driver and held in memory on every executor, so one too large causes out-of-memory errors or hits the 300-second broadcast timeout.

Sources

Where each fact comes from

  1. 1Performance Tuning
  2. 2Hints