Part 9 · Query execution · Chapter 33
Shuffle, joins and skew
How an exchange hashes rows to reducers and writes map output files, how JoinSelection chooses among broadcast hash, shuffled hash, sort-merge and nested loop joins, and how AQE re-plans joins, coalesces partitions and splits skewed ones at runtime.
After this chapter you should be able to:
- Explain how a hash-partitioned exchange assigns rows and lays out its map output.
- Predict the join strategy and build side Spark picks, with and without hints.
- Explain what AQE changes after a shuffle stage runs: join strategy, partition coalescing and skew splits.
Chapters 30 to 32 covered how a scan reads a table and how an engine runs over a batch. A join of two large tables needs one more thing: rows with equal keys must end up on the same executor. That is the shuffle. This chapter follows Spark 4.0.1 from the hash that picks a reducer, to the files the map side writes, to the rules that pick a join, and to what Adaptive Query Execution (AQE) changes once it has seen the real sizes.
The simulator in src/sim/spark/joins.ts ports these pieces: Spark’s Murmur3 hash, SortShuffleManager’s choice of writer, JoinSelection, DynamicJoinSelection, OptimizeSkewedJoin and ShufflePartitionsUtil. Its tests pin the worked examples from Spark’s own scaladoc.
The exchange and hash partitioning
A sort-merge or shuffled hash join requires each child to be clustered on the join keys. When a child is not, EnsureRequirements puts a ShuffleExchangeExec under it, with distribution.createPartitioning(numPartitions). For a join that is hashpartitioning(keys, spark.sql.shuffle.partitions), and the default is 200.[EnsureRequirements.scala][SQLConf: shuffle.partitions]
The reducer of a row is an ordinary Catalyst expression:
// HashPartitioning
def partitionIdExpression: Expression = Pmod(
new CollationAwareMurmur3Hash(expressions), Literal(numPartitions)
)
[partitioning.scala]
Murmur3Hash uses seed 42. With several keys, each key’s hash is the seed of the next, and a null leaves the running hash unchanged. Ints go through Murmur3_x86_32.hashInt, longs through hashLong, and strings through hashUnsafeBytes, the pre-2.3 variant that mixes each trailing byte separately. The source keeps it “for backward compatibility”.[hash.scala: eval][Murmur3_x86_32.java] The simulator reproduces the example in hash()’s documentation: hash('Spark', array(123), 2) is -1321691492.[hash.scala: example]
Both sides of the join use the same expression with the same number of partitions. That is the whole guarantee: equal keys get equal partition ids. The exchange computes the id per row, pairs it with the row, and hands an RDD[(Int, InternalRow)] to a ShuffleDependency whose partitioner, PartitionIdPassthrough, just returns that id.[ShuffleExchangeExec.scala]
Q1. How does a hashpartitioning(key, 200) exchange decide which reducer a row goes to?
Map output files
Each map task writes one data file and one index file. IndexShuffleBlockResolver describes the layout: “Data of shuffle blocks from the same map task are stored in a single consolidated data file. The offsets of the data blocks in the data file are stored in a separate index file.”[IndexShuffleBlockResolver.scala] The index holds lengths.scanLeft(0L)(_ + _), which is numPartitions + 1 longs.[writeMetadataFileAndCommit] To serve reducer r, getBlockData seeks to r * 8 in the index, reads the start and end offsets, and returns that segment of the data file.[getBlockData]
1, Spark reads index entries 1 and 2. It fetches the data starting at byte 180 and ending just before byte 300.[Spark index reader] How the data file gets written depends on the writer that SortShuffleManager.registerShuffle picks:
if (SortShuffleWriter.shouldBypassMergeSort(conf, dependency)) {
// no map-side combine and numPartitions <= spark.shuffle.sort.bypassMergeThreshold (200)
new BypassMergeSortShuffleHandle(...)
} else if (SortShuffleManager.canUseSerializedShuffle(dependency)) {
// relocatable serializer, no map-side combine, <= 16777216 partitions
new SerializedShuffleHandle(...)
} else {
new BaseShuffleHandle(shuffleId, dependency)
}
[SortShuffleManager.scala]
[SortShuffleWriter.shouldBypassMergeSort]
[bypassMergeThreshold]
- BypassMergeSortShuffleWriter writes one file per reducer and concatenates them at the end. The comment explains the trade: it avoids serializing and deserializing twice to merge spills, at the cost of “having multiple files open at a time”.
- UnsafeShuffleWriter (the serialized path) serializes each record on arrival and sorts 8-byte pointers that pack the partition id with a record address, so the sort array stays cache-friendly and spills merge without deserializing.[canUseSerializedShuffle]
- SortShuffleWriter handles the rest, such as RDD shuffles with map-side combine.
Spark SQL never asks for map-side combine (partial aggregation is its own operator), and its row serializer supports relocation. So for SQL the partition count alone decides. At the default 200 partitions an exchange uses the bypass writer; at 201 it uses the serialized writer. ShuffleExchangeExec relies on the same thresholds when it decides whether rows must be copied before the shuffle.[needToCopyObjectsBeforeShuffle]
Reducers fetch these segments from the executors that wrote them. With spark.shuffle.service.enabled (default false), an external shuffle service on each node serves the files instead, so they outlive the executor that wrote them.[config: shuffle.service.enabled]
Q1. A SQL exchange has 200 partitions. Which shuffle writer does SortShuffleManager pick?
Q2. How does a reducer find its data inside one map task's output?
How JoinSelection picks a strategy
JoinSelection is a planner strategy. For a join with equi-join keys and no hints, it tries five constructors in a fixed order and takes the first that returns a plan:
def createJoinWithoutHint() = {
createBroadcastHashJoin(false)
.orElse(createShuffleHashJoin(false))
.orElse(createSortMergeJoin())
.orElse(createCartesianProduct())
.getOrElse {
// This join could be very slow or OOM
...
Seq(joins.BroadcastNestedLoopJoinExec(...))
}
}
[SparkStrategies.scala: JoinSelection]
These are rules over stats.sizeInBytes, not a cost model. Each step has its conditions in JoinSelectionHelper:[joins.scala: JoinSelectionHelper]
- Broadcast hash join. A side can be broadcast when its estimated size is at most
spark.sql.autoBroadcastJoinThreshold(10 MB; −1 disables it) and the join type can build that side.canBuildBroadcastLeftallows inner-like and right outer joins.canBuildBroadcastRightallows inner-like, left outer, left semi, left anti and existence joins. If both sides qualify,getSmallerSidepicks the smaller, and the right side on a tie.[SQLConf: autoBroadcastJoinThreshold][getBuildSide] - Shuffled hash join. Without hints, this needs
spark.sql.join.preferSortMergeJointo be false (the default is true), a build side smaller thanautoBroadcastJoinThreshold × numShufflePartitions(so one partition of it should fit in a hash map), and that side timesspark.sql.shuffledHashJoinFactor(3) no larger than the other side.[canBuildLocalHashMapBySize, muchSmaller][SQLConf: preferSortMergeJoin][SQLConf: shuffledHashJoinFactor] Shuffled hash join can build either side of inner and outer joins, including full outer. - Sort-merge join, if the keys are orderable.
- Cartesian product, for inner-like joins.
- Broadcast nested loop join, building the smaller side unless a hint forces one.
Both hash joins also require keys whose types are binary-stable. A string with a non-binary collation can compare equal with different bytes, so hashJoinSupported turns hash joins off for it.
The build-side rules follow from outer join semantics. A left outer join must emit every left row exactly once, with nulls when nothing matches. If the left side were broadcast, each executor would hold all of it and could not know whether another executor found a match. The streamed side can always be split across tasks; the build side’s unmatched rows can only be tracked when the whole build side for a key is in one task. A shuffled join has that property, which is why shuffled hash join can build the left side of a left outer join and broadcast hash join cannot.
Joins without equi keys go down a shorter path: broadcast nested loop join if a side is under the threshold (with a preferred build side per join type), else a cartesian product for inner joins, else broadcast nested loop join anyway.[JoinSelection: non-equi]
Q1. With no hints and default settings, in what order does JoinSelection try strategies for an equi-join?
Q2. small_orders LEFT OUTER JOIN customers, where small_orders is 5 MB and customers is 50 GB. Can Spark broadcast small_orders?
Q3. Without hints, what must hold for JoinSelection to choose a shuffled hash join that builds the right side? (Select all.) (select all that apply)
Hints
BROADCAST, MERGE (SHUFFLE_MERGE), SHUFFLE_HASH and SHUFFLE_REPLICATE_NL attach to one side of the join. When any hint is present, JoinSelection first tries the hinted strategies, in this order, and falls back to the rules above when none applies:
createBroadcastHashJoin(true)
.orElse { if (hintToSortMergeJoin(hint)) createSortMergeJoin() else None }
.orElse(createShuffleHashJoin(true))
.orElse { if (hintToShuffleReplicateNL(hint)) createCartesianProduct() else None }
.getOrElse(createJoinWithoutHint())
[SparkStrategies.scala]
With onlyLookingAtHint = true, size does not matter: a BROADCAST hint broadcasts a 50 GB side. What still matters is the join type. A BROADCAST hint on the left side of a left outer join yields no build side, checkHintBuildSide reports the hint as not supported, and planning continues without it. Two more strategy values, NO_BROADCAST_HASH and PREFER_SHUFFLE_HASH, are not user hints; AQE adds them, as the next sections show.
Q1. You add /*+ BROADCAST(a) */ to a LEFT OUTER JOIN b. What happens?
Sort-merge join
SortMergeJoinExec requires each child to be clustered on its keys and sorted ascending on them, so EnsureRequirements adds a SortExec above each exchange.[SortMergeJoinExec.requiredChildOrdering] The join itself is SortMergeJoinScanner. For an inner join, findNextInnerJoinRows skips streamed rows with a null key, then advances whichever side has the smaller key until the keys are equal. On a match it calls bufferMatchingRows, which copies every buffered-side row with that key into bufferedMatches, and each following streamed row with the same key reuses the group:[SortMergeJoinScanner]
var comp = keyOrdering.compare(streamedRowKey, bufferedRowKey)
do {
if (streamedRowKey.anyNull) {
advancedStreamed()
} else {
comp = keyOrdering.compare(streamedRowKey, bufferedRowKey)
if (comp > 0) advancedBufferedToRowWithNullFreeJoinKey()
else if (comp < 0) advancedStreamed()
}
} while (streamedRow != null && bufferedRow != null && comp != 0)
Memory use is the largest group of buffered rows with one key, and that buffer can spill. This is why sort-merge join is the default for two large inputs: it never needs a whole partition in a hash table. The sort is the price. A shuffled hash join skips the sort but builds a hash map of its whole build partition, which is why its size conditions are stricter.
Adaptive query execution
AQE (spark.sql.adaptive.enabled, default true) cuts the plan into query stages at exchanges, runs the stages whose inputs are ready, and re-optimizes the rest of the plan with the statistics those stages produced.[SQLConf: adaptive.enabled] Three things can change around a join.
Join strategy. The logical re-optimization runs DynamicJoinSelection, then the planner runs JoinSelection again with runtime sizes.[AQEOptimizer] For runtime statistics, canBroadcastBySize uses spark.sql.adaptive.autoBroadcastJoinThreshold, which falls back to the static threshold when unset.[SQLConf: adaptive.autoBroadcastJoinThreshold] A side estimated at 2 GB whose shuffle wrote 8 MB becomes a broadcast build side, and the sort-merge join turns into a broadcast hash join. DynamicJoinSelection adds hints from the shuffle statistics:[DynamicJoinSelection.scala]
NO_BROADCAST_HASHwhen fewer than 20% of a side’s partitions are non-empty (nonEmptyPartitionRatioForBroadcastJoin). A shuffle join is faster there, since “many tasks complete immediately since one join side is empty”. For left outer, right outer and left anti joins the rule is reversed, because an empty null-filled side cannot short-circuit.[SQLConf: nonEmptyPartitionRatio]PREFER_SHUFFLE_HASHwhen every partition of a side is at mostspark.sql.adaptive.maxShuffledHashJoinLocalMapThresholdand the advisory partition size is not above it. The default is 0, so this is off unless you set it.[SQLConf: maxShuffledHashJoinLocalMapThreshold]- Both together become
SHUFFLE_HASH.
These hints are only added to a side that has no user strategy hint.
Partition coalescing. CoalesceShufflePartitions reads the stages’ bytesByPartitionId and packs contiguous partitions into one task each. coalescePartitions walks the indices, summing the size of partition i across all shuffles of the join, and starts a new group when adding the next partition would pass the target size. A group below minPartitionSize (1 MB) is merged into its smaller neighbour.[ShufflePartitionsUtil.coalescePartitions] The target is advisoryPartitionSizeInBytes (64 MB), capped by total size divided by the minimum partition count and floored at the minimum size.[coalescePartitions][SQLConf: advisoryPartitionSizeInBytes] With spark.sql.adaptive.coalescePartitions.parallelismFirst (default true) that minimum is the cluster’s default parallelism, which keeps tasks from dropping below the cores available. With it false, the minimum is 1, and only the 64 MB target applies.[CoalesceShufflePartitions.scala][SQLConf: parallelismFirst] Coalescing moves no data. Each task reads a range of reducer ids from every map output. The simulator reproduces the source’s example: partitions of 110, 30, 170, 15 and 35 MiB across two shuffles, with a 128 MiB target, become four tasks.
Skew splits, covered next. The order matters. OptimizeSkewedJoin is a preparation rule that runs on the plan right after EnsureRequirements. CoalesceShufflePartitions is a stage optimizer rule that runs afterwards, keeps the skew specs intact and coalesces only around them.[AdaptiveSparkPlanExec rules][coalescePartitionsWithSkew]
Q1. A join was planned as sort-merge because the right side was estimated at 2 GB. Its shuffle stage writes 8 MB. What can AQE do?
Q2. What does CoalesceShufflePartitions do with 200 shuffle partitions of 3 MB each, with parallelismFirst = false?
Skew joins
With a hot key, one reducer gets far more data than the rest, and the stage waits for that one task. OptimizeSkewedJoin handles this for sort-merge and shuffled hash joins whose two inputs are materialized shuffle stages.[OptimizeSkewedJoin.scala] For each side, it computes:
def getSkewThreshold(medianSize: Long): Long = {
conf.getConf(SQLConf.SKEW_JOIN_SKEWED_PARTITION_THRESHOLD).max(
(medianSize * conf.getConf(SQLConf.SKEW_JOIN_SKEWED_PARTITION_FACTOR)).toLong)
}
private def targetSize(sizes: Array[Long], skewThreshold: Long): Long = {
val advisorySize = conf.getConf(SQLConf.ADVISORY_PARTITION_SIZE_IN_BYTES)
val nonSkewSizes = sizes.filter(_ <= skewThreshold)
if (nonSkewSizes.isEmpty) {
advisorySize
} else {
math.max(advisorySize, nonSkewSizes.sum / nonSkewSizes.length)
}
}
With the defaults, a partition is skewed when it is larger than 256 MB and larger than 5 times the median. The median is Utils.median, which takes the mean of the middle two for an even count.[SQLConf: skewJoin][Utils.median]
A skewed partition is split by map task, not by key. createSkewPartitionSpecs reads the size each map task wrote for that reducer and groups consecutive map tasks with splitSizeListByTargetSize. A group closes when the next map output would pass the target, and a group is merged into the previous one when the two together are under 1.2 times the target or either is under 0.2 times it.[splitSizeListByTargetSize][createSkewPartitionSpecs] Each group becomes a PartialReducerPartitionSpec(reducerId, startMapIndex, endMapIndex, dataSize). The matching partition on the other side is read in full once per split. When both sides of a partition are skewed, the tasks are the cartesian product of the two sets of splits. The scaladoc’s example: four partitions with L2, L4, R3 and R4 skewed and split in two become nine tasks. The simulator reproduces that list in order.
Only some sides may be split. canSplitLeftSide allows inner, cross, left semi, left anti and left outer joins; canSplitRightSide allows inner, cross and right outer. Replicating a side across tasks is safe only if that side’s unmatched rows are never emitted. In a right outer join, splitting the left side would copy each right partition into several tasks, and every task would emit the unmatched right rows. A full outer join can split neither side.
If the split would make the plan need extra shuffles, the rule gives up and returns the original plan, unless spark.sql.adaptive.forceOptimizeSkewedJoin is set.[OptimizeSkewedJoin.apply]
Before AQE, the common fix was salting: add a random suffix to the hot key on the large side, replicate the matching rows on the small side once per suffix, and join on the salted key. It still works for cases AQE does not cover, such as a skewed full outer join or a skewed aggregation, but it is query surgery and needs to know the hot keys.
Q1. In SortMergeJoinScanner, what does the scanner keep in memory while it joins?
Q2. With default settings, when does OptimizeSkewedJoin treat a shuffle partition as skewed?
Q3. How does AQE split a skewed partition of the left side of an inner join?
Q4. Why can AQE not split the left side of a right outer join?
Try it
One map task of an exchange. Type join keys and choose the partition count. Each key is hashed with Spark’s Murmur3 and assigned pmod(hash, n). The data file groups the records by partition id, and the index file has n + 1 offsets. Switch between 200 and 201 partitions to see the writer change.
Whole numbers hash as INT, anything else as a UTF-8 STRING. Write path for 4 partitions: BypassMergeSortShuffleWriter (at most spark.shuffle.sort.bypassMergeThreshold = 200 partitions: one file per partition, concatenated).
| key | murmur3(key, 42) | pmod(hash, 4) |
|---|---|---|
| 17 | -1355542311 | 1 |
| 42 | 29417773 | 1 |
| 3 | -1823081949 | 3 |
| 99 | -554831819 | 1 |
| 42 | 29417773 | 1 |
| 8 | -132918897 | 3 |
| 1001 | -396384284 | 0 |
| 3 | -1823081949 | 3 |
| 56 | -1736903644 | 0 |
| 'berlin' | 1041693843 | 3 |
| 'oslo' | 346815364 | 0 |
| 7 | 1079293707 | 3 |
| 42 | 29417773 | 1 |
| 64 | 2015291073 | 1 |
Index file: 5 longs [0, 72, 216, 216, 336]. Reducer r reads bytes [offsets[r], offsets[r+1]) of this file; an empty partition has two equal offsets.
The join strategy chooser. The left column is JoinSelection on estimates, with every rule it tried. The right column runs AQE’s re-plan if the plan has a shuffle. Try:
- 50 GB inner join 3 GB: sort-merge. Then set the right side’s runtime size to 8 MB: AQE turns it into a broadcast hash join. Set it to “8 MB in 10 of 200 partitions”:
DynamicJoinSelectionaddsNO_BROADCAST_HASHand the sort-merge join stays. - Make the left side 1 MB and the join left outer: it still shuffles, because a left outer join cannot broadcast its left side. Right outer broadcasts it.
- Turn off
preferSortMergeJoinwith 50 GB and 1 GB: shuffled hash join, building the right side. At 3 GB it is over 10 MB × 200, so it is sort-merge again. - Put
BROADCASTon the 50 GB side: the hint wins over size.
SortMergeJoin [key], inner
:- Exchange hashpartitioning(key, 200)
: +- Sort [key ASC]
: +- Scan left (50 GB)
+- Exchange hashpartitioning(key, 200)
+- Sort [key ASC]
+- Scan right (3 GB)- No broadcast hash join: the left side is 50 GB, over 10 MB; the right side is 3 GB, over 10 MB.
- No shuffled hash join: spark.sql.join.preferSortMergeJoin is true and no side has PREFER_SHUFFLE_HASH.
- Sort-merge join: the keys are orderable, so both sides are shuffled on the keys and sorted.
SortMergeJoin → BroadcastHashJoin (build right)
- Broadcast hash join: the right side is 8 MB (runtime), at most autoBroadcastJoinThreshold 10 MB.
Skew. orders JOIN customers after both shuffles ran, with 24 partitions and 8 map tasks per side. Raise the share of orders on one customer and watch partition 5 cross the threshold, split into map ranges, and the rest coalesce around it. Switch to a right outer or full outer join: the orders side can no longer be split.
Median 25.4 MB; threshold = max(256 MB, 5 × median) = 256 MB. Split target = max(64 MB, mean of the non-skewed partitions) = 64 MB. Skewed: left p5, right none.
Join tasks after skew split and coalescing: 21 (was 24)Each split of the orders partition reads a range of map outputs and is paired with the whole matching customers partition, which is read once per split. Coalescing uses minNumPartitions = 1 here (parallelismFirst = false); by default Spark keeps at least the cluster's default parallelism.
History
The configuration entries record when each piece arrived, in their .version(...) fields at the pinned commit. spark.sql.autoBroadcastJoinThreshold and spark.sql.shuffle.partitions date from Spark 1.1.0, and spark.shuffle.sort.bypassMergeThreshold from 1.1.1.[SQLConf][config package] The serialized sort path was proposed in SPARK-4550 and its optimizations are described in SPARK-7081, as the SortShuffleManager scaladoc notes.[SortShuffleManager.scala] spark.sql.join.preferSortMergeJoin arrived in 2.0.0.[SQLConf] Skew join handling, partition coalescing and the advisory partition size arrived with Spark 3.0.0’s adaptive execution. The spark.sql.adaptive.enabled entry itself is marked 1.6.0.[SQLConf: skewJoin][SQLConf: adaptive.enabled] The adaptive broadcast threshold and the local map threshold for shuffled hash join came in 3.2.0, and spark.sql.shuffledHashJoinFactor in 3.3.0.[SQLConf][SQLConf]
Summary
- A hash exchange assigns each row
pmod(murmur3(keys, seed 42), n), the same on both sides of a join. - Each map task writes one data file grouped by partition id plus an index of
n + 1offsets. Reducers fetch byte ranges. SQL exchanges use the bypass writer at 200 partitions or fewer and the serialized writer above that. JoinSelectiontries broadcast hash, shuffled hash, sort-merge, cartesian and broadcast nested loop, in that order, on size estimates. The join type limits which side can be built: outer joins cannot broadcast the side whose unmatched rows they keep.- Hints are tried first and bypass size checks, but not join-type rules.
- Sort-merge join buffers only the rows of the current key on one side, so it scales to two large inputs; shuffled hash join trades the sort for a hash map of the build partition.
- AQE re-plans after shuffle stages run: it can turn a sort-merge join into a broadcast hash join, coalesce small partitions toward 64 MB, and split partitions larger than 256 MB and 5 × the median into ranges of map outputs, on the sides the join type allows.
Concepts in this chapter
Explained here
Primary sources
Review this chapter
This chapter has 13 quiz questions.