Joins: Advanced
The plan, operator by operator
This is what explain() prints for clicks.join(purchases, "user_id") with broadcast disabled, listed from the scans upward. Each side gets its own Scan, Exchange and Sort, and the 2 branches meet at the join.
| Operator | Where it runs | What it costs |
|---|---|---|
| `Scan` and `Filter isnotnull(user_id)` | Map stage, one per side | Reads the input and drops NULL keys, which can never satisfy an equality |
| `Exchange hashpartitioning(user_id, 200)` | Stage boundary | Every row of that side is written to shuffle files and fetched by the reducer that owns its key |
| `Sort [user_id ASC NULLS FIRST]` | Reduce stage | Each task sorts its slice of that side, n log n work, writing sorted runs to disk if memory runs short |
| `SortMergeJoin [user_id], [user_id], Inner` | Reduce stage, same tasks as the sorts | One forward pass over both sorted slices, plus one output row per matching pair |
The Sort is a second sort, separate from the one inside the shuffle. Sort-based shuffle orders map output by partition ID so each reducer can find its block, and inside a block the rows arrive in whatever order the map tasks wrote them. The join needs key order, so each side gets a Sort in the reduce stage. That sort has to consume the whole fetched slice before the merge sees its first row.
Counting stages and tasks
Say clicks is read as 40 input partitions, purchases as 60, and spark.sql.shuffle.partitions is 200. The DAGScheduler cuts the job at the 2 Exchanges, which gives 3 stages. Stage 1 scans clicks in 40 tasks and writes shuffle files, and stage 2 does the same for purchases in 60 tasks. The 200 tasks of stage 3 each fetch one partition from both sides, sort both and merge them. Stages 1 and 2 do not depend on each other, so they can run at the same time. The join costs 2 shuffles and 300 tasks.
The merge, step by step
Neither cursor moves backward, so the merge reads each input row once. The output size is a separate number: a key with 2 left rows and 3 right rows emits 6, which is the duplicate-key blowup produced inside this loop. The animation runs the plan on 4 clicks and 5 purchases with 2 shuffle partitions. Follow u1: its 2 clicks and 3 purchases meet on one reduce task.
spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1)clicks.join(purchases, "user_id").collect()
| user_id | clicks rows | purchases rows | joined rows |
|---|---|---|---|
| u1 | 2 | 3 | 6 |
| u2 | 1 | 1 | 1 |
| u3 | 1 | 0 | 0 |
| u4 | 0 | 1 | 0 |
| total | 4 | 5 | 7 |
Keys u3 and u4 each sit on one side only. They are shuffled and sorted like the rest, and then the merge drops them. An inner sort-merge join pays to move and sort rows that produce nothing, so a filter applied before the join trims all 3 steps.
When a side arrives already partitioned
The plan leaves out an Exchange when a side's rows are already hash-partitioned on the join key into the partition count the join will use. A side produced by repartition(200, "user_id") qualifies, and so does the output of an earlier sort-merge join on user_id. Two tables bucketed on the key with the same bucket count skip both Exchanges. The join's own output is partitioned on user_id, so a groupBy("user_id") after it adds no shuffle. A groupBy on another column adds one.
Both tables hold several GB. How many shuffles does this job run, and where does the groupBy execute?
Run a sort-merge join on the practice tables. Broadcast is off, so orders and order_items are both shuffled on order_id. The groupBy on the join key runs inside the join's reduce stage. Each result row is a completed order with its count of item lines.
spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1)
orders = spark.table("orders").filter("status = 'Completed'")
items = spark.table("order_items")
lines = orders.join(items, "order_id").groupBy("order_id").count()
lines.orderBy("order_id").show(10)Grouping the same join on another column costs one more shuffle. groupBy("product_id") needs its rows hash-partitioned on product_id, and the join leaves them partitioned on order_id. The plan therefore gains a third Exchange hashpartitioning(product_id, 200) after the SortMergeJoin, and the job gains a fourth stage to read it.
A hash or sort-merge join works because equal keys can be routed to one task. Rows that might match meet there, and rows that cannot match are never compared. A range condition offers nothing to route by. Take t.start_ts >= w.from_ts AND t.start_ts < w.to_ts: a trip starting at 14:07 could fall in any window of the table, so no partitioning of the windows rules any of them out in advance. Spark has to test the condition on pairs.
What Spark plans with no equality
| Situation | Physical operator | How pairs are formed |
|---|---|---|
| One side under the broadcast threshold, or hinted | `BroadcastNestedLoopJoin` | The small side is copied to every executor; each task loops over its rows of the big side and, for each one, over the whole copy |
| Neither side small, inner join | `CartesianProduct` | One task per pair of partitions: 50 left and 40 right make 2,000 tasks, and each right partition is read once per left one |
| Neither side small, outer join | `BroadcastNestedLoopJoin`, forced | Spark broadcasts one side whatever its size, which can exhaust driver or executor memory |
in_window = (trips.start_min >= surge_windows.from_min) & (trips.start_min < surge_windows.to_min)trips.join(F.broadcast(surge_windows), in_window).collect()
Pricing a range join in pairs
A nested loop costs the number of pairs tested, whatever share of them match. Take a surge-pricing job: 48 million trips a day across 500 cities, with a surge window every 2 minutes in each city. That makes 720 windows per city per day and 360,000 in all. Each trip belongs to exactly one window of its own city. The range-only condition also matches it to the concurrent window in the other 499 cities, which returns about 24 billion rows, so city_id is needed for a correct answer as well as for speed. The 2 keyed versions below both return the right 48 million rows.
| Join condition | Windows tested per trip | Pairs tested per day |
|---|---|---|
| time range only | 360,000 | 17.28 trillion |
| equal `city_id`, plus the time range | 720 | 34.56 billion |
| equal `city_id` and hour, plus the time range | 30 | 1.44 billion |
Pairs tested equal trips times the windows each trip is checked against, and every equality term cuts the second factor. One equality is enough to change the operator. Spark takes the equal columns as join keys, plans a sort-merge or broadcast hash join on them, and evaluates the range as a filter on each pair within a key group. The plan then shows a keyed operator such as SortMergeJoin [city_id], [city_id], Inner, with the range condition after the join type.
Binning a range into a key
The sequence ends at the hour of the window's last instant, one microsecond before to_ts, so a window ending exactly on the hour stays in one bin. Choose the bin from the window length. Bins much shorter than a window copy each window into many bins and inflate that side. Bins much longer leave many windows per bin and push the pair count back up. With 2-minute windows on even minutes, an hour bin copies nothing and leaves 30 windows per city-hour.
<, > or BETWEEN and no equality, check its operator with explain(). If it is BroadcastNestedLoopJoin or CartesianProduct, multiply the 2 row counts: that product is the work.Spark joins 2 million sessions to a 3MB table of 50,000 campaign windows on s.ts BETWEEN c.start_ts AND c.end_ts, with default settings. Which operator runs, and how many pairs does it test?
On the practice tables, the cell below pairs each product with every cheaper product in its category. Category equality is the join key, and the price comparison runs on pairs inside each category. Replace join(right, "category") with crossJoin(right) and run it again. The counts can only grow, and so does the work, since every product is now tested against every other.
left = spark.table("products").select("product_id", "category", "price")
right = spark.table("products").selectExpr(
"product_id AS other_id",
"category",
"price AS other_price",
)
cheaper = left.join(right, "category").filter("other_price < price")
cheaper.groupBy("product_id").count().orderBy("product_id").show(10)- Fetches its slice of both sides
- Sorts both slices by key
- Merges them in one forward pass
- Can write sorted runs to disk when memory runs short
- The planner's default for large equi-joins
- Fetches its slice of both sides
- Builds a hash table from the smaller slice
- Probes it once per row of the larger slice
- Needs the whole build slice in memory at once
- Chosen by a hint or by changing a default
How it gets into a plan
- You put a shuffle_hash hint on one side, as in drivers.hint("shuffle_hash"). For an inner join, the hinted side becomes the build side.
- You set spark.sql.join.preferSortMergeJoin from its default true to false, and the smaller side is estimated under autoBroadcastJoinThreshold times spark.sql.shuffle.partitions, 10MB times 200 = 2,000MB with defaults, and at least 3 times smaller than the other side.
The 2,000MB test averages out to 10MB per reducer, and that average assumes the build side's keys spread evenly over 200 partitions. Hash partitioning sends every row of a key to one task, so the estimate says nothing about the largest slice. To confirm the choice, look for ShuffledHashJoin [driver_id], [driver_id], Inner, BuildRight in the plan, with an Exchange under each side and no Sort above either.
When dropping the sort wins
Take 60GB of trips joined on driver_id to a 600MB drivers table with one row per driver, over 200 partitions. Each reduce task receives around 300MB of trips and 3MB of drivers. Sort-merge sorts both slices before its first match. The hash join builds a 3MB table and streams the 300MB through it unsorted. Shuffle bytes are the same either way, so the saving is the sort of 60GB of rows, spread over 200 tasks, on every run.
The memory bet
| Build side | Rows per key | Average slice | Largest slice | Result |
|---|---|---|---|---|
| `drivers`, 600MB | 1 | 3MB | about 3MB | Faster than sort-merge |
| `city_fares`, 1.6GB | one city holds 25% | 8MB | 400MB or more | The task holding that city fails |
In the second row the bet is lost. Every row of the large city hashes to one partition, so one task must build a hash table of at least 400MB while the other 199 build around 8MB each. A retry reads the same partition and fails the same way. After spark.task.maxFailures attempts, 4 by default, the job fails. Without the hint, sort-merge would have finished that task slowly, sorting the slice partly on disk.
A join hinted shuffle_hash on city_fares (1.6GB, 200 shuffle partitions) fails: task 137 runs out of memory on all 4 attempts while the other 199 tasks succeed. What is the cause, and what fixes it?
Spark reads 4 join hints, one per strategy: broadcast plans a broadcast hash join, merge a sort-merge join, shuffle_hash a shuffled hash join, and shuffle_replicate_nl a CartesianProduct. For broadcast and shuffled hash, the hinted side is the one built into a hash table. When the 2 sides carry different hints, broadcast wins over merge, merge over shuffle_hash, and shuffle_hash over shuffle_replicate_nl. A hint the join cannot honour, such as shuffle_hash on a condition with no equality, is dropped with a warning in the driver log.
A broadcast hash join drops the shuffle of the big side and sets up a different kind of traffic. The driver runs a separate job to collect the small side, builds a hash table from its rows, and ships that table to every executor. Torrent broadcast cuts it into 4MB blocks (spark.broadcast.blockSize) that executors fetch from the driver and from each other, which spreads the sending load. Each executor still receives the full table once, and all of its tasks share that copy.
Bytes on the wire
| Lookup table | Size | Broadcast to 400 executors | Shuffle both sides |
|---|---|---|---|
| `cities` | 2MB | 0.8GB | 60GB |
| `promos` | 120MB | 48GB | 60.1GB |
| `drivers` | 600MB | 240GB | 60.6GB |
| `riders` | 900MB | 360GB | 60.9GB |
Setting the 2 costs equal gives the break-even size: 60GB divided by 399, about 150MB. Below it, broadcasting a table moves fewer bytes than shuffling the trips; above it, more. Network is one axis. The shuffle also writes the trips to disk and sorts them, so a broadcast a little past break-even can still finish first. At 6 times past it, riders sends about 300GB more than the shuffle would.
A threshold raised to rescue one join
A storm usually starts with a threshold raised to rescue one join. Someone sets autoBroadcastJoinThreshold to 1GB so riders broadcasts, and every lookup table under 1GB broadcasts along with it. The pricing job joins trips to 8 of them: riders 900MB, drivers 600MB, payment_methods 400MB, vehicles 250MB, promos and fare_rules 120MB each, zones 8MB and cities 2MB, 2.4GB in all. Each executor holds all 8 hash tables at once, and the driver collects and builds each one before sending it.
Recognising a storm
- Price a broadcast as table size times executor count and compare it with the shuffle it replaces
- Filter and select columns on a lookup table before the join so fewer bytes are copied
- Hint broadcast on tables under the break-even size and keep the threshold at 10MB
- Recount broadcast bytes whenever the executor count changes
- Raise autoBroadcastJoinThreshold for the whole job to rescue one slow join
- Raise spark.sql.broadcastTimeout to hide a broadcast that is too large
- Run a broadcast join inside a loop of actions without counting the repeats
- Assume a table's size on disk equals the memory its hash table takes
A job joins a 250MB vehicles table to 40GB of ratings on 300 executors. Counting network bytes only, which strategy moves less?
On the practice tables, stores is small enough to broadcast. Run the cell, then change the hint to "merge" and run it again; the rows match. The plan is what changes. With broadcast, explain() shows a BroadcastExchange over the stores scan and no Exchange between the store_sales_raw scan and the join, so the network carries stores once per executor. With merge, an Exchange hashpartitioning(store_id, 200) sits under each side, and every sales row crosses the network once. On 400 executors, the first plan sends 400 copies of stores and the second sends the sales table once.
sales = spark.table("store_sales_raw")
stores = spark.table("stores")
by_store = sales.join(stores.hint("broadcast"), "store_id")
by_store.groupBy("store_id").sum("revenue").orderBy("store_id").show(10)Same question, 2 cost curves
| Measure | Spark join | Key-value lookups |
|---|---|---|
| Rows read | 2 billion, the whole history | 5,000 |
| Bytes read | 400GB | about 1MB |
| Cost grows with | table size | keys requested |
| Smallest possible latency | job startup plus a full scan | one round trip per key or batch of keys |
Signs the join belongs in a store
Spark builds, the store serves
Most of these cases still need Spark for the half that touches every row. A nightly job aggregates all trips per rider, a sort-merge join plus a groupBy over the full history, and writes one row per rider_id into a key-value store. The fare service and the support tool then read single keys. The join that reads everything runs once in batch, and the lookups that read one row run in the store.
Spark reads every trip once a night and writes one row per rider; each request reads a single key.
The reverse mistake
- ▸Most rows of both sides reach the output: join in Spark.
- ▸A few thousand keys from a huge table, in batch: prune with the table's layout, or query an index.
- ▸An answer per request or per event: precompute in Spark, serve from a key-value store.
- ▸Millions of keys per run: join a bulk snapshot in Spark, never per-row calls.
A fraud check must attach a card's 30-day spend to each incoming payment within 50 milliseconds. Spend comes from a 3-billion-row payment history. How should the work be split?
> Back on Uber's pricing team, the 9-hour nightly job is taken apart join by join. The surge join gains city_id and an hour bin, so a nested loop over 17.28 trillion pairs becomes a keyed join testing 1.44 billion. The threshold goes back to 10MB: promos and fare_rules, under the 150MB break-even, keep an explicit broadcast hint, while riders, drivers, payment_methods and vehicles move to shuffled joins, replacing 860GB of broadcast traffic with about 242GB of shuffles. The drivers join gets a shuffle_hash hint because each of its 200 slices holds about 3MB, and city_fares keeps sort-merge because one city holds 25% of its rows. The per-ride fare request leaves Spark entirely: the nightly job writes one row per rider to a key-value store, and the app reads one key per ride.
drivers and fatal on city_fares.BroadcastNestedLoopJoin or CartesianProduct and costs rows times rows; one equality term, even a binned hour, turns it back into a keyed join.Account for every shuffle, sort, pair and broadcast byte a join costs, and know when a join belongs outside Spark.
- Category
- Spark
- Difficulty
- advanced
- Duration
- 15 minutes
- Challenges
- 16 hands-on challenges
Topics covered: Inside Sort-Merge Join, Non-Equi Joins, Shuffle-Hash Join, The Broadcast Storm, When Not to Join in Spark
Lesson Sections
- Inside Sort-Merge Join
When neither side of an equi-join fits under the broadcast threshold, Spark plans a sort-merge join. It runs as 3 steps: shuffle both sides on the join key so equal keys meet on one task, sort each task's rows by key, then walk the 2 sorted runs side by side. Each step has its own cost and its own operator in the plan, so you can trace a slow sort-merge join to one of them before you change anything. The plan, operator by operator Counting stages and tasks The merge, step by step Each task in st
- Non-Equi Joins (concepts: Shuffle Optimization)
What Spark plans with no equality The animation broadcasts 3 surge windows and runs 4 trips through them in 2 tasks, with start times in minutes. No shuffle happens. Each task tests each of its trips against all 3 windows: 12 comparisons to produce 4 rows. Pricing a range join in pairs Binning a range into a key Time has no natural equality, so you build one. Truncate each trip's start to the hour, and give each window one row for every hour it overlaps, so a window from 13:59 to 14:01 appears u
- Shuffle-Hash Join
A shuffled hash join keeps the 2 shuffles of sort-merge and replaces its 2 sorts with a hash table. Each reduce task fetches its partition of both sides and loads the smaller slice into a hash table keyed on the join key. It then streams the larger slice through that table, probing once per row. Nothing waits for a sort, and no key order is needed. How it gets into a plan When dropping the sort wins The memory bet The saving holds only if every task's build slice, as a hash table, fits in the me
- The Broadcast Storm
Bytes on the wire One broadcast therefore puts about table size times executor count on the network. A shuffle-based join moves each side once: big side plus small side. Add executors and the first number grows while the second stays put. Here are lookup tables from a trip pricing job on 400 executors, each joined to 60GB of trips. A threshold raised to rescue one join Those bytes repeat. Each action runs the plan again, broadcasts included, so a job that writes the result and then counts it pay
- When Not to Join in Spark
Spark's join cost follows the bytes it reads. A sort-merge or broadcast join reads both sides in full, less whatever partition pruning removes, which suits work where most rows on both sides reach the output. When the work is fetching a few thousand rows by key from a table of billions, an index or a key-value store reads those rows and nothing else, and its cost follows the number of keys. Same question, 2 cost curves A support tool flags 5,000 trips today and needs each rider's history from a