Joins at scale
Part of the free LogicWiz Data Engineering course, Module 12: How Spark runs. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 6:50 on Friday morning and the nightly job is still running. First it joined 2 billion order lines to 20,000 products and shuffled both tables for 40 minutes. Now it joins the lines to customers: 199 tasks finished in a minute, and one task has been running for an hour. Nora reads the stage page: "Two joins, two different problems. Start with the small table."
You'll learn to
- Explain how a sort-merge join and a broadcast join each work
- Say what a broadcast costs the driver and every executor
- Predict which join Spark picks, and why it sometimes misses
- Spot a skewed key and size a salt for it
Learn
Two ways to bring keys together
A join has one job: rows with the same key must meet in one task. Spark has two ways to arrange the meeting.
- Move both tables, so that equal keys land in the same partition. That is a shuffle on each side.
- Copy the small table to every executor, so the big one can stay where it is. That is a broadcast.
Last night's job used the first way for both joins. That was the wrong choice for one of them, and the right choice with a hidden problem for the other.
2 billion rows moved for a tiny table
The first way has a name: a sort-merge join. Spark shuffles both sides by the join key into the same number of partitions. Then each task sorts its two piles by the key and walks them together, like zipping two sorted decks of cards.
It works at any size, because a sort that runs out of memory can spill to disk. Its price is two full shuffles and two sorts.
Now look at the first join again. 2 billion order lines were sorted and sent across the network to meet 20,000 products, a table that would fit on a phone.
A sort-merge join, stage by stage
Two tables joined by a sort-merge join: both are shuffled by the join key so matching keys land in the same partition, each partition is sorted, and one task per partition merges the two sides.
Press Next step. Watch both tables go through a shuffle, then one task per partition merging its two sorted sides. Count the rows shuffled at the bottom.
Copy the small table instead
The second way is a broadcast hash join. Spark turns the small table into a hash table (a lookup by key) and gives every executor its own copy. Each task then looks up its own order lines in the copy. The 2 billion lines never move.
The side that gets hashed and copied is called the build side.
A broadcast is not free. The small table passes through the driver, and every executor holds a full copy for as long as the join runs. Step through it.
A broadcast, step by step
A broadcast join in four steps: the products rows are collected to the driver, the driver builds a hash table, the table travels to two executors in 4 MB pieces, and each executor keeps one copy that its tasks probe with order lines that never moved.
Collect. The driver runs a small job first: tasks read the 20,000 products and send every row to the driver.
Build. The driver builds a hash table keyed by
product_idand turns it into bytes. For a moment the whole table sits in the driver's memory.Ship. The bytes travel in 4 MB pieces. Executors fetch pieces from the driver and from each other, which is why Spark calls it TorrentBroadcast.
Probe. Each executor now holds one copy, shared by all its tasks. Every task looks up its own order lines in it. No order line crossed the network.
Read each step left to right: the driver, then the executors. Count the copies: one on the driver while it builds, then one per executor. A cluster of 50 executors holds 50 copies.
The same join, shuffled and broadcast
import minispark as ms
orders = ms.read_csv('data/orders.csv', 4).keyBy(lambda r: r['customer_id'])
customers = ms.read_csv('data/customers.csv', 2).map(lambda r: (r['customer_id'], r['country']))
shuffled = orders.join(customers, 4)
print('shuffle join: ', shuffled.count(), 'rows |', ms.last_job())
broadcast = orders.broadcast_join(customers)
print('broadcast join:', broadcast.count(), 'rows |', ms.last_job())
broadcast.explain()
The same 80 rows both ways. The shuffle join moved both sides, 80 orders plus 30 customers = 110 records, in three stages. The broadcast join shuffled nothing: it copied the 30 customers to every task, in two stages. The last two lines of output list those stages.
The trap: hinting a big table. By itself Spark broadcasts only a table it estimates at 10 MB or less. A hint from you overrides that limit. Hint a table of several GB and the driver really collects and hashes it, and every executor really holds a copy. Expect "Not enough memory to build and broadcast the table to all worker nodes", "Could not execute broadcast in 300 secs", or, past 8 GB, "Cannot broadcast the table that is larger than 8.0 GiB". Broadcast dimensions and lookup tables, not facts.
A broadcast in a real plan
Runs on Databricks:
from pyspark.sql import functions as F
lines = spark.read.parquet("/Volumes/swiftkart/raw/order_lines")
products = spark.read.parquet("/Volumes/swiftkart/raw/products")
lines.join(F.broadcast(products), "product_id").explain()
== Physical Plan ==
AdaptiveSparkPlan isFinalPlan=false
+- Project [product_id#7, order_id#5, qty#8, unit_price#9, name#31, category#32]
+- BroadcastHashJoin [product_id#7], [product_id#30], Inner, BuildRight, false
:- Filter isnotnull(product_id#7)
: +- FileScan parquet [order_id#5,product_id#7,qty#8,unit_price#9] ...
+- BroadcastExchange HashedRelationBroadcastMode(List(cast(input[0, int, false] as bigint)),false), [plan_id=87]
+- Filter isnotnull(product_id#30)
+- FileScan parquet [product_id#30,name#31,category#32] ...
F.broadcast(products) is a hint: you tell Spark which side to copy. BuildRight says the right side (products) is the build side. The order lines have no Exchange above their scan, so they never move. Without the broadcast, the plan shows SortMergeJoin with an Exchange and a Sort on each side. The browser's PySpark has no F.broadcast, because there is no cluster to broadcast to.
Remember: a broadcast costs one collect and one build on the driver, then one copy in every executor. In return, the big table never moves.
How Spark picks a join
Spark decides before anything runs. Its planner (this part is called JoinSelection) walks down a short list and takes the first strategy that fits.
- A hint from you, if the join type allows it.
- A broadcast hash join, if a side that is allowed to be the build side is estimated at 10 MB or less (
spark.sql.autoBroadcastJoinThreshold). - A sort-merge join: the usual plan for two big tables.
The picture and the table below add the rarer strategies.
One rule surprises people. The join type limits which side may be the build side. A left outer join can broadcast only its right side. A right outer join can broadcast only its left. A full outer join can broadcast neither.
The list JoinSelection walks down
Six steps in order: hints, broadcast hash join under the threshold, shuffled hash join only when sort-merge is not preferred, sort-merge join, cartesian product, and broadcast nested loop join as the last resort.
Read it top to bottom, for a join with an equality in its condition. Spark stops at the first step that fits; the label on each arrow says why it moved on.
The five join strategies
| Operator | How it works | Needs | The risk |
|---|---|---|---|
| BroadcastHashJoin | Small side hashed and copied to every executor; the big side never moves | Equi-join; the build side under the threshold or hinted | The whole build side in memory on the driver and every executor |
| ShuffledHashJoin | Both sides shuffled; each task hashes its partition of the smaller side | Equi-join; a hint, or preferSortMergeJoin off and one side much smaller | One task's build partition must fit in memory |
| SortMergeJoin | Both sides shuffled and sorted, then merged | Equi-join on sortable keys | Two shuffles; one hot key's rows are buffered |
| BroadcastNestedLoopJoin | One side broadcast; every pair of rows tested | Any condition, such as a range | Rows x rows comparisons |
| CartesianProduct | Every row with every row, no broadcast | An inner join with no equality | Output of N x M rows |
An equi-join has at least one left.key == right.key condition. A join on a.ts BETWEEN b.start AND b.end alone is not one, and only the last two operators can run it.
Ask minicatalyst which join it would pick
import minicatalyst as mc
GB, MB = mc.GB, mc.MB
cases = [
('lines JOIN products', 200 * GB, 8 * MB, 'inner'),
('lines LEFT JOIN products', 200 * GB, 8 * MB, 'left'),
('lines FULL JOIN products', 200 * GB, 8 * MB, 'full'),
('products RIGHT JOIN lines', 8 * MB, 200 * GB, 'right'),
('orders JOIN customers', 48 * GB, 48 * MB, 'inner'),
]
for name, left, right, how in cases:
print(f'{name:26} {mc.choose_join(left, right, how=how)}')
print(mc.choose_join(48 * GB, 48 * MB, hint='broadcast'))
print(mc.choose_join(48 * GB, 1536 * MB, prefer_sort_merge=False))
print(mc.choose_join(48 * GB, 48 * MB, equi=False))
choose_join follows JoinSelection's order (open minicatalyst.py). Look at the third line: a full outer join cannot broadcast either side, so even an 8 MB table goes through a sort-merge join. The last line is a range join on two big inputs: only a cartesian product is left.
The guess behind the choice
So why did Spark not broadcast 20,000 products by itself? Step 2 compares 10 MB with an estimate, a guess made before anything runs. For a file scan the guess is the size of the files on disk, scaled down when fewer columns are read.
The guess has a blind spot. Without the cost-based optimiser (Lesson 12.7), a filter does not shrink the estimate at all. In the nightly job the 20,000 products are the active rows of a much bigger catalogue table, picked with a filter. Spark still estimates them at the full table's size, so a side that turns out to be a few MB is planned as a sort-merge join.
AQE (Lesson 12.10) decides again from the real shuffle sizes once the inputs have run.
Real pipelines join one big fact table to many small dimensions, so most joins in a well-built job are broadcast. When Spark misses one, the usual reason is the estimate: a dimension that comes out of a filter or a query, or a table with no statistics. Teams fix it with a broadcast hint on the dimension, leave AQE on as the safety net, then confirm BroadcastHashJoin in the plan.
One key, one slow task
Now the second join. Customers is a big table, so a sort-merge join is right. The problem is inside the shuffle: every row of a key goes to one partition.
At SwiftKart every guest checkout has customer_id 0. Say the 2 billion lines are 200 GB. With 200 shuffle partitions:
- an average task reads 200 / 200 = 1 GB
- guests are 30% of the lines: 0.3 x 200 = 60 GB, all in the one task that owns key 0
That task runs for an hour while 199 others finish in a minute, and the stage waits for it. This is skew. On the stage page it shows as a max task duration far above the median, the same outlier in shuffle read size, and often spill on that one task.
One hot key
A join where one key holds most of the rows: after the shuffle one partition is many times larger than the rest, its task runs long after the others have finished, and salting the key spreads it over several tasks.
Press Next step: after the shuffle one partition is many times larger than the others, and its task is still running when they are done. Then press Salt the key and watch the hot key spread over several tasks.
See the skew, then salt it
import minispark as ms
# 60 guest orders share customer 0; 20 customers have one order each
orders = [(0, i) for i in range(60)] + [(c, 100 + c) for c in range(1, 21)]
rdd = ms.parallelize(orders, 4)
print('read: ', rdd.sizes())
print('by key: ', rdd.partitionBy(4).sizes())
salted = rdd.map(lambda kv: ((kv[0], kv[1] % 4), kv[1]))
print('salted key:', salted.partitionBy(4).sizes())
The read is even: 20 rows per partition. Shuffled by key, one task holds 65: all 60 guest orders and 5 others. The last line adds a small number to the key, here order_id % 4. The guest orders now travel under four keys, (0, 0) to (0, 3), so four tasks share them and the slowest task holds 21 records, not 65. Any value that spreads rows evenly works. Spark code often uses (F.rand() * k).cast("int").
Salting a join, with the sums
That trick is called salting. You split a hot key into k keys by adding a small number, the salt, from 0 to k-1.
- Big side: add a salt to each row, so the key becomes
(customer_id, salt). - Small side: copy each row k times, once per salt, so every salted row still finds its match.
- Join on the key and the salt, then drop the salt.
For the guest key take k = 32: 60 GB / 32 is about 1.9 GB per task.
The price is on the small side. Copying all 20 million customers 32 times would shuffle 640 million rows. So salt only the hot keys: customer 0 gets 32 copies and everyone else keeps salt 0.
The hot task, before and after the salt
Three bars in gigabytes read by one task: 1 for an average task, 60 for the task that owns customer 0, and about 1.9 after salting that key with k equal to 32.
Each bar is the data one task reads. Salting does not shrink the work: it cuts the red bar into 32 pieces that run side by side.
Remember: salt only the hot keys. For a skewed groupBy, aggregate by (key, salt) first, then by key. AQE splits skewed sort-merge joins by itself (Lesson 12.10), but not aggregations.
Numbers to remember
| Setting or limit | Value | What it is |
|---|---|---|
| spark.sql.autoBroadcastJoinThreshold | 10 MB | A buildable side estimated at or under this is broadcast. -1 turns automatic broadcasts off |
| spark.sql.broadcastTimeout | 300 s | The broadcast table must be built within this time |
| Hard limits of a broadcast | 8 GB and 512 million rows | About 341 million rows unless the key is a single integer. Past them the job fails |
| spark.broadcast.blockSize | 4 MB | The size of the pieces TorrentBroadcast sends |
| The hash table | LongHashedRelation or UnsafeHashedRelation | The first for a single integer key (compact), the second otherwise. cast(... as bigint) in a plan's broadcast mode shows the integer key |
| Hint order | BROADCAST MERGE SHUFFLEHASH SHUFFLEREPLICATENL | Used only if the join type allows them |
| spark.sql.join.preferSortMergeJoin | true (an internal setting) | A shuffled hash join is picked only when this is false and one side is under threshold x shuffle partitions and at least 3 times smaller |
| spark.sql.sources.fileCompressionFactor | 1.0 | Multiplies the file size in the estimate of a scan. The estimate counts compressed bytes on disk; the same rows decoded into a hash table take more memory |
| A join with no equality | two strategies | BroadcastNestedLoopJoin if a side is small, else CartesianProduct for an inner join, else BroadcastNestedLoopJoin anyway |
What changed at SwiftKart
Two joins, two fixes.
For the products join you add a hint: lines.join(F.broadcast(products), "product_id"). The plan now says BroadcastHashJoin, and there is no Exchange above the 2 billion lines.
For the customers join you salt key 0, and only key 0, with k = 32. The one-hour task becomes 32 tasks of about 1.9 GB that run side by side.
Nora adds a line to the review checklist, the usual culprits of skew: a default key (0, unknown, an empty string), NULL keys in an outer join, one giant seller, one very busy day.
The job now finishes before Tess starts work. But its output folder holds thousands of tiny files. Lesson 12.5 is about partitions and files.
In one line
Spark shuffles both tables for a join unless one side is small enough to copy to every executor, it chooses from size estimates that can be wrong, and one huge key needs salting or AQE.
Interview corner
What is the difference between a broadcast hash join and a sort-merge join?
A sort-merge join shuffles both tables by the join key, sorts each partition and merges them: it scales to any size because sorts spill, but it moves both tables. A broadcast hash join collects the small table to the driver, builds a hash table, and copies it to every executor, so the big side never moves. Spark broadcasts a buildable side estimated under 10 MB, or one you hint; the cost is driver memory during the build and one copy per executor.
How does Spark choose a join strategy?
JoinSelection checks hints first, in the order BROADCAST, MERGE, SHUFFLE_HASH, SHUFFLE_REPLICATE_NL, if the join type allows them. For an equi-join it then picks a broadcast hash join if a buildable side is under spark.sql.autoBroadcastJoinThreshold, a shuffled hash join only if spark.sql.join.preferSortMergeJoin is false and one side is small and 3 times smaller, otherwise a sort-merge join. Non-equi joins get a broadcast nested loop join or a cartesian product. The join type limits the build side: left outer builds right, right outer builds left, full outer cannot broadcast.
Why might Spark not broadcast a table that is obviously small?
It decides on an estimate made at planning time. Without CBO a filter does not reduce the estimate, so a 3 GB table filtered to 1 MB still looks like 3 GB; a table produced by a subquery or with no statistics can look huge too. It can also be the wrong side for the join type, such as the left side of a left outer join. Fixes are a broadcast hint, CBO with ANALYZE TABLE statistics, or AQE, which switches to a broadcast join once it measures the real size.
How do you detect and fix data skew in a join?
In the Spark UI the stage shows a max task duration and shuffle read far above the median, often with spill on that task. First filter out junk keys (NULL, 0, unknown) if they should not join at all. Check that AQE skew join is on, which splits a skewed sort-merge partition. Otherwise salt: give the hot key k salt values on the big side and k copies of its row on the small side, so 60 GB with k = 32 becomes pieces of about 1.9 GB, and salt only the hot keys to keep the small side small.