What you will be able to do
- Explain why a broadcast hash join avoids shuffling the large side of a join
- State what spark.sql.autoBroadcastJoinThreshold controls, its 10 MB default, and what -1 does
- Force a broadcast with functions.broadcast(), DataFrame.hint("broadcast") or a SQL BROADCAST hint, and confirm it in the physical plan
- Predict which strategy Spark uses when conflicting join hints are given, and why a hint can still be ignored
Key concept
Broadcast hash join — A join strategy where Spark copies the whole of the smaller relation to every executor and builds an in-memory hash table from it. Each executor then probes that table with its own partitions of the large relation, so the large side never has to be redistributed by join key.
1.Why a broadcast join skips the shuffle
A join usually needs every row of one table to meet the matching rows of the other. When both tables are big, Spark gets them together with a shuffle join: it moves rows across the network so that equal keys end up in the same place (see shuffles and partitions). That exchange is often the most expensive part of the job. A broadcast join removes it when one side is small.
The small side is sent in full to every executor. Each executor builds a hash table from it in memory, then reads through its own partitions of the large table and looks up each row's key. Every match the large table needs is already local, so none of the large table's partitions leave the executor that holds them. The executor finishes its share of the join on its own.
This makes broadcast hash join usually the fastest strategy, but only while the copied side really is small. Every executor holds a full copy, so a side that does not fit comfortably in memory turns the advantage into a liability. In that case Spark plans a shuffle join, which is slower. A typical case is a 500 GB orders fact table joined to a 2 MB regions dimension. Copying 2 MB to each executor is cheap, while shuffling 500 GB is not.
Strategy choice also depends on the join condition. An equi-join condition compares a column on one side with a column on the other for equality, as in ON t1.key = t2.key. When the join has an equi-join key, a broadcast produces a broadcast hash join: the copied table is held as an in-memory hashmap, and a hashmap is probed by key. Without an equi-join key, Spark uses a broadcast nested loop join, and a complex predicate that is not a simple equality can make the broadcast hash join ineligible altogether. Even when the broadcast works, each probing row still costs one hash table lookup.
Sorting both sides and merging them is how a sort merge join works, and that strategy still moves data between executors. A broadcast join sorts nothing. It copies the small table to every executor and probes an in-memory hash table with the large table's local rows, which is why the large side is never exchanged.
Checkpoint 1 of 7· Check yourself
Which of these joins is the best candidate for a broadcast hash join?
A broadcast hash join pays off when one side is small enough to copy in full to every executor and the join has an equi-join key. Broadcasting a 200 GB or 600 GB side would not fit comfortably in executor memory, and a range condition with no equi-join key leads to a broadcast nested loop join, not a broadcast hash join.
“broadcast hash join is usually the most performant if one side of the join can fit well in memory”Source: www.databricks.com
Checkpoint 2 of 7· Exam question
Why does a broadcast join avoid the shuffle stage that a standard join between two large tables requires?
Correct answer: A — The smaller dataset is copied in full to every executor, letting each executor complete the join locally without exchanging the larger dataset's partitions.
- A. This is correct: a broadcast join sends a full copy of the small side to every executor, so the join against the large side's local partitions never needs to move rows across the network. That removal of the shuffle exchange is the entire performance benefit of the strategy.
- B. Spark does not build a compressed columnar cache of the larger table on each executor; the join strategy is about sending the small side, not compressing the large side. This describes a caching mechanism Spark does not use for broadcast joins.
- C. Pre-sorting both sides and merging matching rows describes a sort-merge join, a separate strategy Spark uses when neither side is small enough to broadcast. It is not how a broadcast join avoids network movement.
- D. Hash-partitioning both sides by join key and still exchanging every partition describes a shuffle hash join, which keeps the shuffle exchange this question asks about avoiding. A broadcast join is chosen precisely to skip that exchange.
- E. Spark has no shared distributed cache layer that both executors read from during a join; the broadcast mechanism physically pushes a copy of the data to each executor's local memory instead. This option invents a caching tier that does not exist in Spark's join execution.
2.Automatic broadcasting and spark.sql.autoBroadcastJoinThreshold
You do not need a hint to get a broadcast join. Spark broadcasts a relation automatically when its estimated size is below spark.sql.autoBroadcastJoinThreshold. The value is a size in bytes. The default is 10485760, which is 10 MB. A session can raise or lower it, and setting it to -1 turns automatic broadcasting off.
| Property | Default | What it controls |
|---|---|---|
| spark.sql.autoBroadcastJoinThreshold | 10485760 (10 MB) | Largest table size, in bytes, that Spark broadcasts to all worker nodes for a join; -1 disables it |
| spark.sql.broadcastTimeout | 300 | How many seconds a broadcast join waits for the broadcast; a time limit, not a size limit |
The word that matters is *estimated*. Spark picks the join strategy before the query runs, using size estimates built from statistics. Some come from the data source, such as Parquet file metadata. Others come from the catalog and are refreshed whenever you run ANALYZE TABLE. When the statistics are missing or stale, the estimate can be far off. Then a 2 MB table can look too big to broadcast, and Spark falls back to a sort merge join even though the threshold would have allowed a broadcast.
Estimates also fail on derived relations. A very selective filter, or a relation built from several operators rather than a plain scan, can be much smaller at runtime than the planner expected. AQE dynamic join strategy switching handles this case. It measures the real size after an exchange and can turn a planned sort merge join into a broadcast hash join, so a broadcast can happen even though the static estimate ruled it out.
Checkpoint 3 of 7· Check yourself
A job joins a 400 GB sales table to a dimension table that is only 2 MB on disk. There is no hint, and spark.sql.autoBroadcastJoinThreshold is still at its 10 MB default, yet the physical plan shows a sort merge join. What is the most likely cause?
Spark chooses the join strategy before the query runs, using estimated sizes from statistics. If those statistics are missing or stale, a small table can look bigger than the threshold, and Spark plans a sort merge join. broadcastTimeout is a wait time in seconds, not a size limit, and the threshold applies to each table on its own with a 10 MB default.
“Those estimates might be wrong if table statistics are missing or stale”Source: docs.databricks.com
Checkpoint 4 of 7· Exam question
A Spark job automatically uses a broadcast hash join for a small dimension table with no explicit hint applied anywhere in the code. Which configuration property controls this automatic behavior, and what does its default value represent?
Correct answer: A — spark.sql.autoBroadcastJoinThreshold sets the largest estimated table size Spark broadcasts automatically, defaulting to 10 MB unless the session overrides it.
- A. This is correct:
spark.sql.autoBroadcastJoinThresholdis the size cutoff the planner compares a table's estimated size against, and its default of 10 MB is why small dimension tables get broadcast without any explicit hint. Setting it to -1 disables this automatic behavior entirely. - B.
spark.sql.shuffle.partitionsonly controls the number of partitions used after a shuffle occurs and has nothing to do with the size threshold that triggers automatic broadcasting. Its default of 200 is unrelated to table size estimation. - C.
spark.sql.broadcastTimeoutgoverns how long a broadcast exchange is allowed to run before timing out, not what size table qualifies for broadcasting in the first place. Its 300-second default is a wait limit, not a size limit. - D.
spark.driver.maxResultSizelimits how much data a driver can collect from actions likecollect(), and it is not the property the planner consults when deciding whether a table is small enough to broadcast. Raising it does not change broadcast eligibility. - E. Automatic size-based broadcasting is independent of
spark.sql.adaptive.enabledand works whether or not adaptive query execution is turned on. AQE can additionally convert a join to broadcast at runtime, but it is not a prerequisite for the size-based default behavior.
3.Requesting a broadcast with broadcast(), hint() and SQL hints
If you know a table is small but Spark's estimate says otherwise, you can mark it for broadcast yourself. pyspark.sql.functions.broadcast(df) returns the same DataFrame, marked as small enough for broadcast joins. It has been available since Spark 1.6 and supports Spark Connect. Pass the marked DataFrame to join() as the small side:
from pyspark.sql import functions as dbf
df = spark.createDataFrame([1, 2, 3, 3, 4], "int")
df_small = spark.range(3)
df_b = dbf.broadcast(df_small)
df.join(df_b, df.value == df_small.id).show()A hint is not limited by the threshold. When a relation carries the BROADCAST hint, Spark prioritises a broadcast join with that relation as the build side, even if its estimated size is above spark.sql.autoBroadcastJoinThreshold. That is why orders.join(broadcast(regions), "region_id") gets rid of an unwanted sort merge join. The marker on regions overrides the planner's size estimate. Methods such as cache(), coalesce(), repartition() or sorting change how the data is stored or partitioned, but none of them asks for a broadcast.
DataFrame.hint("broadcast") does the same job as broadcast(), written as a method on the DataFrame. The physical plan shows the result: the plain join plans SortMergeJoin, and the hinted join plans BroadcastHashJoin. Running explain() is the quickest way to confirm a broadcast actually happened.
df.join(df2, "name").explain()
# == Physical Plan ==
# ...
# ... +- SortMergeJoin ...
# ...
df.join(df2.hint("broadcast"), "name").explain()
# == Physical Plan ==
# ...
# ... +- BroadcastHashJoin ...
# ...In SQL, the request goes in a /*+ ... */ comment right after SELECT. Spark accepts three names for it: BROADCAST, BROADCASTJOIN and MAPJOIN. The argument is the table to broadcast. If the query gives that table an alias, the hint has to use the alias, because the alias hides the original table name.
> SELECT /*+ BROADCAST(t1) */ * FROM t1 INNER JOIN t2 ON t1.key = t2.key;
> SELECT /*+ BROADCASTJOIN (t1) */ * FROM t1 left JOIN t2 ON t1.key = t2.key;
> SELECT /*+ MAPJOIN(t2) */ * FROM t1 right JOIN t2 ON t1.key = t2.key;Checkpoint 5 of 7· Fill the gap
Complete this sample so that df_small is marked as the side Spark should copy to every executor, even if its estimated size is above the automatic threshold.
from pyspark.sql import functions as dbf
df = spark.createDataFrame([1, 2, 3, 3, 4], "int")
df_small = spark.range(3)
df_b = dbf. ? (df_small)
df.join(df_b, df.value == df_small.id).show()functions.broadcast() returns the same DataFrame marked as small enough for broadcast joins, and that marker gives it priority as the build side. repartition(), coalesce() and cache() only change how the data is partitioned or stored. None of them requests a broadcast.
Source: docs.databricks.comCheckpoint 6 of 7· Exam question
A data engineer joins a 500 GB fact table orders with a 2 MB dimension table regions on region_id using orders.join(regions, "region_id"). The job runs slowly because Spark chooses a sort-merge join instead of broadcasting regions. Which code change forces Spark to broadcast regions for this join?
Correct answer: A — from pyspark.sql.functions import broadcast
result = orders.join(broadcast(regions), "region_id")
- A. This is correct: wrapping
regionswith thebroadcast()function explicitly marks it for a broadcast hash join, overriding whatever plan the optimizer would otherwise pick regardless of the table's estimated size. This is the standard DataFrame-API way to force the strategy. - B. Calling
.cache()onregionsonly persists it in memory for reuse across actions; it does not tell the join planner to use a broadcast strategy. The join could still execute as a sort-merge join. - C. Repartitioning
ordersinto 200 partitions changes how the large side is distributed for a shuffle-based join but does nothing to markregionsfor broadcasting. This still leaves the choice of join strategy to the optimizer's default logic. - D. Coalescing
regionsdown to one partition changes its physical layout but does not instruct Spark to broadcast it; the optimizer still decides the join strategy based on its own cost estimates. Coalesce is a partition-count operation, not a join hint. - E. Sorting
regionswithin its partitions prepares data for a sort-based join rather than requesting a broadcast; it does not change which join strategy the planner selects. This action has no effect on broadcast eligibility.
4.How Spark resolves conflicting join hints
BROADCAST is one of four join strategy hints. Each one tells Spark which strategy to use for the relation it names. Each hint also has its own names in SQL:
| Hint | Strategy requested | Also accepted as |
|---|---|---|
| BROADCAST | Broadcast join | BROADCASTJOIN, MAPJOIN |
| MERGE | Shuffle sort merge join | SHUFFLE_MERGE, MERGEJOIN |
| SHUFFLE_HASH | Shuffle hash join | — |
| SHUFFLE_REPLICATE_NL | Shuffle-and-replicate nested loop join | — |
When the two sides of a join carry different strategy hints, a fixed priority decides: BROADCAST over MERGE over SHUFFLE_HASH over SHUFFLE_REPLICATE_NL. The losing hint is dropped, not treated as an error. The query runs, and the HintErrorLogger logs a warning that the overridden hint will not take effect.
> SELECT /*+ BROADCAST(t1), MERGE(t1, t2) */ * FROM t1 INNER JOIN t2 ON t1.key = t2.key;Sometimes both sides carry BROADCAST. Spark can still only build one hash table, so it picks the build side itself, based on the join type and the sizes of the two relations. Hinting both sides therefore does not mean both get copied.
A hint is a strong request, but Spark does not promise to follow it. Not every strategy supports every join type, and if the hinted strategy cannot run the join you wrote, Spark uses another one. So after adding a hint, check explain() instead of assuming the plan changed.
Spark tries a broadcast join with b as the build side, because BROADCAST outranks SHUFFLE_HASH. The SHUFFLE_HASH hint is overridden, and a warning is logged saying it will not take effect. The query does not fail.
Checkpoint 7 of 7· Match them up
Each scenario below puts join strategy hints on a join between t1 and t2. Match each scenario to what Spark does.
Tap a term, then the definition that fits it.
Conflicting hints are settled by a fixed priority (BROADCAST, then MERGE, then SHUFFLE_HASH, then SHUFFLE_REPLICATE_NL), and the losing hint only produces a logged warning. When both sides are hinted BROADCAST, Spark picks one build side. Hints are not guaranteed: a strategy that does not support the join type gets replaced by another one.
“When different join strategy hints are specified on both sides of a join, Spark prioritizes the BROADCAST hint over the MERGE hint”Source: spark.apache.org
Practise it for real
Use the physical plan to see a broadcast hint change the join strategy
1.Create df from [(2, "Alice"), (5, "Bob")] with schema ["age", "name"], and df2 from Row(height=80, name="Tom") and Row(height=85, name="Bob").
Why: Two small DataFrames with a shared key column make the plans easy to read.
You should see: Two DataFrames that both have a name column.
2.Run df.join(df2, "name").explain()
Why: Shows which strategy Spark picks for this join without any hint.
You should see: The physical plan contains SortMergeJoin.
3.Run df.join(df2.hint("broadcast"), "name").explain()
Why: The hint marks df2 as the side to broadcast.
You should see: The physical plan contains BroadcastHashJoin instead of SortMergeJoin.
Stuck? Get a nudge
If both plans already show BroadcastHashJoin, the automatic threshold probably picked up the tiny df2. Set spark.sql.autoBroadcastJoinThreshold to -1 for the session and run the unhinted join again.
Sources
(9)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“The lookup table is copied to each executor and stored in memory as a hashmap”
↩︎ Why a broadcast join skips the shuffle“If the lookup table is large, the optimizer falls back to a shuffle join, which is slower.”
↩︎ Why a broadcast join skips the shuffle“If the lookup predicate is complex (not a simple equality check), broadcast join may also become ineligible.”
↩︎ Why a broadcast join skips the shuffle“Even with broadcast hash join, each row still incurs the cost of a hash table lookup during execution.”
↩︎ Why a broadcast join skips the shuffle“The lookup table is copied to each executor and stored in memory as a hashmap”
↩︎ Key concept - 2.
“instruct Spark to broadcast the smaller table to all executors instead of performing a shuffle join”
↩︎ Why a broadcast join skips the shuffle - 3.https://www.databricks.com/blog/2020/05/29/adaptive-query-execution-speeding-up-spark-sql-at-runtime.htmlSecondary source
“broadcast hash join is usually the most performant if one side of the join can fit well in memory”
↩︎ Why a broadcast join skips the shuffle“Spark plans a broadcast hash join if the estimated size of a join relation is lower than the broadcast-size threshold.”
↩︎ Automatic broadcasting and spark.sql.autoBroadcastJoinThreshold“such as the presence of a very selective filter”
↩︎ Automatic broadcasting and spark.sql.autoBroadcastJoinThreshold - 4.https://spark.apache.org/docs/latest/sql-performance-tuning.htmlSecondary source
“either broadcast hash join or broadcast nested loop join depending on whether there is any equi-join key”
↩︎ Why a broadcast join skips the shuffle“Configures the maximum size in bytes for a table that will be broadcast to all worker nodes when performing a join.”
↩︎ Automatic broadcasting and spark.sql.autoBroadcastJoinThreshold“By setting this value to -1, broadcasting can be disabled.”
↩︎ Automatic broadcasting and spark.sql.autoBroadcastJoinThreshold“Timeout in seconds for the broadcast wait time in broadcast joins”
↩︎ Automatic broadcasting and spark.sql.autoBroadcastJoinThreshold“These statistics are collected or updated whenever you run ANALYZE TABLE.”
↩︎ Automatic broadcasting and spark.sql.autoBroadcastJoinThreshold“will be prioritized by Spark even if the size of table”
↩︎ Requesting a broadcast with broadcast(), hint() and SQL hints“We accept BROADCAST, BROADCASTJOIN and MAPJOIN for broadcast hint”
↩︎ Requesting a broadcast with broadcast(), hint() and SQL hints“Spark will pick the build side based on the join type and the sizes of the relations”
↩︎ How Spark resolves conflicting join hints“there is no guarantee that Spark will choose the join strategy specified in the hint”
↩︎ How Spark resolves conflicting join hints“Timeout in seconds for the broadcast wait time in broadcast joins”
↩︎ Exam trap 1“suggested by the statistics is above the configuration spark.sql.autoBroadcastJoinThreshold”
↩︎ Exam trap 2“there is no guarantee that Spark will choose the join strategy specified in the hint”
↩︎ Exam trap 4“suggested by the statistics is above the configuration spark.sql.autoBroadcastJoinThreshold”
↩︎ Prediction“When different join strategy hints are specified on both sides of a join, Spark prioritizes the BROADCAST hint over the MERGE hint”
↩︎ Checkpoint - 5.https://docs.databricks.com/aws/en/optimizations/aqeOfficial docs
“Before a query runs, the optimizer chooses a query plan based on estimates of the data size.”
↩︎ Automatic broadcasting and spark.sql.autoBroadcastJoinThreshold“Dynamically changes sort merge join into broadcast hash join.”
↩︎ Automatic broadcasting and spark.sql.autoBroadcastJoinThreshold“Those estimates might be wrong if table statistics are missing or stale”
↩︎ Checkpoint - 6.
“Marks a DataFrame as small enough for use in broadcast joins.”
↩︎ Requesting a broadcast with broadcast(), hint() and SQL hints - 7.https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.functions.broadcast.htmlSecondary source
“New in version 1.6.0. Changed in version 3.4.0: Supports Spark Connect.”
↩︎ Requesting a broadcast with broadcast(), hint() and SQL hints - 8.
“Specifies some hint on the current DataFrame.”
↩︎ Requesting a broadcast with broadcast(), hint() and SQL hints - 9.
“When a table name is occluded by an alias you must use the alias name in the hint”
↩︎ Requesting a broadcast with broadcast(), hint() and SQL hints“prioritizes the BROADCAST hint over the MERGE hint over the SHUFFLE_HASH hint”
↩︎ How Spark resolves conflicting join hints“is overridden by another hint and will not take effect.”
↩︎ How Spark resolves conflicting join hints“prioritizes the BROADCAST hint over the MERGE hint over the SHUFFLE_HASH hint”
↩︎ Exam trap 3