Skip to content
Silver 6 min read · spark.sql.autoBroadcastJoinThreshold 2 practice problems ↓

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

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

  1. 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 →

  2. Broadcast

    The driver sends it to every executor

  3. Build

    Each executor builds a hash table from it

  4. 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; -1 disables 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.
PySparkSpark SQL · Forcing a broadcast
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 typeCan broadcast
innerEither side
left outer, left semi, left antiThe right side only
right outerThe left side only
full outerNeither, 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.
Tip: raising the threshold to 100 to 200 MB is a common, reasonable tuning step on clusters with plenty of memory. Raising it to gigabytes usually is not.

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.

Production patternPySpark · Broadcast in a job: an explicit hint and a sensible 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.

ExplorePySpark · Sort-merge vs broadcast on the same join
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: SortMergeJoin took about three times longer than BroadcastHashJoin here.
  • 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?"

Whether it is a sort-merge join shuffling 2 TB. If so, broadcast the dimension (hint, or raise the threshold above 50 MB), confirm BroadcastHashJoin in the plan, and mention the limits: driver memory, broadcastTimeout, the 8 GB cap, and that the left side of a left join cannot be broadcast.

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?"
The threshold is compared with Spark's size estimate, not the file size. Compressed Parquet can be several times larger in memory, filters or joins in front of it may make the estimate unknown, and statistics may be missing. Check 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?"
The broadcast side is collected to the driver before it is sent out, so the driver needs room for it, and in memory it can be much larger than on disk. Either raise driver memory to fit, filter and select columns before broadcasting, or go back to a sort-merge join.
Trap"Broadcasting is free once the table is small, so set the threshold to 2 GB."
Every executor keeps a copy: 2 GB times 200 executors is 400 GB of memory taken from execution and cache, on top of the driver collecting it and timeouts on slow builds. Tens to a couple of hundred MB is a reasonable ceiling.

Check yourself

3 questions

What 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 read
Caching and persistence
cache(), persist() and storage levels: when caching speeds a job up and when it hurts.

Related lessons

Previous: Join hints and slow non-equi joins

Primary sources: Join strategy hints · Performance tuning