Broadcast joins
Joining a huge table to a small one is very common: orders to countries, events to products. Spark can send the small table to every machine instead of shuffling both, which is often the biggest single speed-up available. This lesson shows how it works, when Spark does it, and when it backfires.
Step 2 · Spark internals · Silver · Shuffles and joins, lesson 5 of 5
On this page
Show code in
Every code block on the page follows this.
Read first: Join strategies (skip if you know it)
In plain words first
A school sends a 2-page list of bus routes to every classroom, so each class can match its own students to a bus without leaving the room. That beats bringing every student to the hall to sort them by route.
That is a broadcast join: copy the small table to every executorexecutor: A worker process on a cluster machine that runs tasks and holds data in memory. Learn more →, and each one joins its own part of the big table locally, with no shuffleshuffle: Moving rows between machines so that all rows with the same key end up together. Needed by joins, groupBy and sorting, and usually the most expensive step of a job. Learn more →.
How it works
-
Collect
The small side is computed and collected to the driverdriver: The process that runs your program, plans the work and sends tasks to executors. Learn more →
-
Broadcast
The driver sends it to every executor
-
Build
Each executor builds a hash table from it
-
Probe
Each tasktask: The work for one partition in one stage, run on one CPU core. Learn more → streams its large-side partitionpartition: A chunk of a DataFrame's rows. Spark processes each partition as one task, so partitions decide how much work runs in parallel. Learn more → through the hash table
Compare a sort-merge joinsort-merge join: Spark's default join for two large tables: both sides are shuffled and sorted by the key, then matched in one pass. Learn more → of two large tables: both sides shuffled by key, both sorted, then merged. Broadcasting replaces two shuffles and two sorts with one small transfer.
When Spark broadcasts
- Automatically, when its estimated size is below
spark.sql.autoBroadcastJoinThreshold(10 MB by default;-1disables it). - With AQEAQE: Adaptive Query Execution: Spark re-plans a running query using the real data sizes it has measured. Learn more →, at runtime, when the measured size after a shuffle is below
spark.sql.adaptive.autoBroadcastJoinThreshold, which defaults to the same value. - When you ask:
F.broadcast(df)or a SQL hinthint: A request in a query, such as BROADCAST, that steers how Spark runs a join. Spark ignores a hint it cannot honour. Learn more →. Hints override the threshold.
from pyspark.sql import functions as F orders.join(F.broadcast(countries), "country_code")
SELECT /*+ BROADCAST(c) */ o.*, c.name FROM orders o JOIN countries c ON o.country_code = c.code
Which side can be broadcast
| Join type | Can broadcast |
|---|---|
| inner | Either side |
| left outer, left semi, left anti | The right side only |
| right outer | The left side only |
| full outer | Neither, as a broadcast hash join |
The rule: the side that must keep unmatched rows is the one streamed, so the other side is broadcast. Broadcasting the left side of a left join would lose track of left rows with no match across executors.
When broadcasting backfires
- A "small" table that is not small — Statistics can be wrong, especially after filters and joins. A 2 GB table forced into a broadcast must be collected to the driver and copied to every executor: driver out-of-memory or very slow jobs.
- Too big for the hard limit — A broadcast table is limited to 8 GB; beyond that Spark fails the query.
- Timeouts — Building a broadcast that takes longer than
spark.sql.broadcastTimeout(300 seconds) fails the query, typically when the small side is itself an expensive query. - Memory on every executor — Each executor holds a copy. With 200 executors, a 500 MB table occupies 100 GB of cluster memory.
Check what Spark chose
In explain(), look for BroadcastHashJoin with a BroadcastExchange under one side, versus SortMergeJoin with an Exchange on both sides. With AQE, the plan before execution may say SortMergeJoin and change at runtime; the SQL tab of the Spark UI shows the final plan.
Try it yourself
Each example says what it shows, then the output from a real run and what to notice in it, so you can follow without running anything. To try one yourself, paste it into a local Spark session, with spark already created: each builds its own data.
Goal: Broadcast a small table in a production job, with an explicit hint and a session-wide size threshold.
from pyspark.sql import functions as F # Session-wide: broadcast tables up to 64 MB automatically (the default is 10 MB). spark.conf.set("spark.sql.autoBroadcastJoinThreshold", "64m") orders = spark.range(0, 2_000_000).selectExpr( "id AS order_id", "id % 200 AS country_id", "id % 997 AS amount") countries = spark.range(0, 200).selectExpr( "id AS country_id", "concat('c', id) AS country") # The hint makes the plan independent of size estimates. revenue = (orders.join(F.broadcast(countries), "country_id") .groupBy("country").agg(F.sum("amount").alias("revenue"))) revenue.write.mode("overwrite").parquet("lab/broadcast/revenue") result = spark.read.parquet("lab/broadcast/revenue") print(result.count(), "countries") result.orderBy("country").show(5)
Output from a real run
200 countries +-------+-------+ |country|revenue| +-------+-------+ | c0|4977285| | c1|4977315| | c10|4977585| | c100|4980285| | c101|4980315| +-------+-------+ only showing top 5 rows
What to notice:
- 200 countries, one revenue row each: the 2 million orders were joined to the 200-row table without shuffling the orders.
- Country names sort as text:
c0,c1,c10,c100. - The hint makes the plan independent of size estimates; the threshold (64 MB here) covers joins without a hint.
Goal: Run the same join as a sort-merge join and as a broadcast join, and time both.
import contextlib, io, time from pyspark.sql import functions as F def join_type(df): buf = io.StringIO() with contextlib.redirect_stdout(buf): df.explain() broadcast = "BroadcastHashJoin" in buf.getvalue() return "BroadcastHashJoin" if broadcast else "SortMergeJoin" orders = spark.range(0, 5_000_000).withColumn("country_id", F.col("id") % 200) countries = spark.range(0, 200).selectExpr( "id AS country_id", "concat('c', id) AS name") spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1) # keep AQE from switching at runtime spark.conf.set("spark.sql.adaptive.enabled", "false") for label, dim in [("no broadcast", countries), ("broadcast", F.broadcast(countries))]: q = orders.join(dim, "country_id").groupBy("name").count() t = time.time() q.collect() print(f"{label}: {join_type(q)}, {time.time() - t:.2f}s")
Output from a real run
no broadcast: SortMergeJoin, 1.72s broadcast: BroadcastHashJoin, 0.58s
What to notice:
- Same query, two strategies:
SortMergeJointook about three times longer thanBroadcastHashJoinhere. - On a real cluster the gap is far bigger, because the sort-merge join sends every order row across the network.
Common mistakes
- Broadcasting the preserved side of an outer join — Spark ignores the hint and falls back to another strategy.
- Trusting size estimates after complex transformationstransformation: An operation that describes a new DataFrame (filter, select, join) without running anything yet. Learn more → — Check actual sizes in the Spark UI.
- Setting the threshold to several GB — Driver and executor memory pressure, and timeouts.
Key takeaways
- Broadcast joins ship the small side everywhere and avoid shuffling the large side.
- Automatic below 10 MB estimated, or at runtime with AQE; force with F.broadcast or a hint.
- Outer joins can only broadcast the non-preserved side; full outer cannot.
- Big broadcasts cost driver and executor memory and can time out.
Interview prep
THE QUESTION
"A join of a 2 TB fact table with a 50 MB dimension takes an hour. What do you check?"
Avoid: "just broadcast it" without the limits: driver memory, the 8 GB cap, broadcastTimeout, and that the preserved side of an outer join cannot be broadcast.
Follow-ups · answer out loud, then open
Follow-up"The dimension is 50 MB on disk. Why might Spark not broadcast it with a 100 MB threshold?"
explain("cost"), add a hint, or rely on AQE, which uses the measured size after a shuffle.Scenario"After you forced a broadcast, the driver started failing with OutOfMemoryError. Why?"
Trap"Broadcasting is free once the table is small, so set the threshold to 2 GB."
Check yourself
3 questionsWhat is the default spark.sql.autoBroadcastJoinThreshold?
Show the answer
10 MB. The default is 10 MB; -1 disables automatic broadcasting.
In a left outer join, which side can be broadcast?
Show the answer
Right. The left side must keep unmatched rows, so it is streamed and the right side is broadcast.
Which plan node shows a broadcast join?
Show the answer
BroadcastHashJoin. BroadcastHashJoin, with a BroadcastExchange under the small side.
Practise this
Problems that use this, graded on hidden tests
Keep going
Up next · new module: Memory and resources · 6 min readCaching and persistence
cache(), persist() and storage levels: when caching speeds a job up and when it hurts.
Related lessons
Join strategiesSpark internals · 7 min read
Adaptive Query ExecutionSpark internals · 6 min read
Dynamic partition pruning
Previous: Join hints and slow non-equi joins
Primary sources: Join strategy hints · Performance tuning