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

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.

OperatorWhere it runsWhat it costs
`Scan` and `Filter isnotnull(user_id)`Map stage, one per sideReads the input and drops NULL keys, which can never satisfy an equality
`Exchange hashpartitioning(user_id, 200)`Stage boundaryEvery 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 stageEach 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 sortsOne 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

Each task in stage 3 holds 2 sorted iterators and treats them differently. The left side streams, one row at a time. The right side is buffered by key. When the left cursor reaches a new key, the right cursor skips smaller keys and copies every right row with an equal key into a buffer. Each left row with that key emits one joined row per buffered row. When the left key changes, the buffer is cleared and refilled.

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()
clicks
user_idpage
u1home
u2search
u1cart
u3home
purchases
user_iditem
u1lamp
u4desk
u1chair
u2pen
u1mug
user_idclicks rowspurchases rowsjoined rows
u1236
u2111
u3100
u4010
total457

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?

spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1)
clicks_by_user = clicks.repartition(200, "user_id")
joined = clicks_by_user.join(purchases, "user_id")
joined.groupBy("user_id").count().collect()

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.

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.

About this lesson

This section is part of the Joins: Advanced lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.