Data Skew in Spark: Detect It and Fix It
Find the hot key behind a stage that never finishes, then fix it with AQE skew joins, key cleanup, hot-key isolation or salting, in that order.
TL;DR
- Skew means a few partitions hold far more data than the rest. A stage takes as long as its slowest task, so one hot key can turn a 2-minute stage into a 40-minute one.
- Detect it in the Spark UI: compare Max to Median in a stage's summary metrics. Max duration or shuffle read 5–10× the median is skew.
- Find the key with a
groupBy(key).count()on the join or grouping column. It's very oftenNULL,'UNKNOWN',-1or a single giant customer. - Fix in this order: let AQE split skewed joins → clean up bad keys → isolate the hot keys (often with a broadcast) → salt. Salting works but costs the most, in code and in data.
- AQE only fixes skew in shuffle joins. Skewed aggregations, windows,
MERGEsources and partitioned writes need you.
The problem
NorthBridge's loyalty pipeline joins 2.1 billion sales lines to the customer dimension every night. One evening it went from 25 minutes to 3 hours.
The Spark UI showed stage 14 with 1,999 tasks finished in about two minutes and one task still running. That task had read 41 GB of shuffle data; the median task had read 180 MB.
The cause: a POS software update had started sending customer_id = 'UNKNOWN' for every guest checkout, about 30% of all sales. In a hash shuffle, every row with the same key goes to the same partition. 600 million rows, one task.
Key concepts
| Concept | What it means | Why it matters here |
|---|---|---|
| Skew | Uneven data across partitions | Stage time is the max, not the average |
| Hot key | A key value with a disproportionate share of rows | The usual cause of join and aggregation skew |
| Hash partitioning | Rows go to hash(key) % n |
Identical keys always land together; more partitions don't help |
| AQE skew join | Splitting an oversized join partition into several tasks at runtime | Automatic fix for most join skew |
| Salting | Adding a random suffix to a hot key to spread it | Manual fix when AQE can't help |
| Partial aggregation | Pre-aggregating on the map side before the shuffle | Why skewed sum/count often don't hurt |
One task holding the hot key decides how long the whole stage takes.
Step 1 — Confirm it's skew
Open the slow stage: Spark UI → Stages → stage → Summary Metrics.
| Metric | Min | 25th | Median | 75th | Max |
|---|---|---|---|---|---|
| Duration | 1.1 min | 1.6 min | 1.9 min | 2.2 min | 2.9 h |
| Shuffle Read Size | 140 MB | 168 MB | 180 MB | 195 MB | 41 GB |
| Spill (Disk) | 0 | 0 | 0 | 0 | 38 GB |
What tells you it's skew and not something else:
- Max ≫ median on both duration and shuffle read. If all tasks are equally slow, it's not skew; it's too few partitions, too little memory or slow code.
- The event timeline shows one long bar while every other executor sits idle.
- Spill only on the max task. The big partition doesn't fit; the others do.
If max duration is high but shuffle read is even, look for a different cause: one slow node, a huge row (a giant array), or an expensive UDF on specific values. The walkthrough is in Reading the Spark UI.
Step 2 — Find the hot keys
# Databricks Runtime 16.4 LTS+, PySpark
from pyspark.sql import functions as F
sales = spark.table("northbridge.silver.sales_lines")
total = sales.count()
hot = (sales.groupBy("customer_id").count()
.withColumn("pct", F.round(F.col("count") / F.lit(total) * 100, 2))
.orderBy(F.desc("count"))
.limit(20))
hot.show(truncate=False)+-----------+---------+-----+
|customer_id|count |pct |
+-----------+---------+-----+
|UNKNOWN |634210977|30.04|
|NULL | 8122012| 0.38|
|C-0041877 | 412311| 0.02|
...Do the same for every key the slow stage shuffles on: join keys on both sides, groupBy columns, window partitionBy columns, and the partitionBy columns of the write.
For a quick look at how a shuffle would distribute rows:
(sales.repartition(2000, "customer_id")
.groupBy(F.spark_partition_id().alias("pid")).count()
.orderBy(F.desc("count"))
.show(5))Step 3 — Let AQE split skewed joins
For sort-merge and shuffle hash joins, AQE detects skewed partitions after the shuffle and splits them into several tasks, duplicating the matching partition from the other side for each piece.
A partition is treated as skewed when both are true:
size > spark.sql.adaptive.skewJoin.skewedPartitionFactor (5) × median partition size
size > spark.sql.adaptive.skewJoin.skewedPartitionThresholdInBytes (256 MB)# Defaults on Spark 3.2+ and Databricks; shown for reference
spark.conf.get("spark.sql.adaptive.skewJoin.enabled") # true
spark.conf.get("spark.sql.adaptive.skewJoin.skewedPartitionFactor") # 5
spark.conf.get("spark.sql.adaptive.skewJoin.skewedPartitionThresholdInBytes") # 256MBCheck it worked in the SQL tab: the join's AQEShuffleRead shows number of skewed partitions and number of skewed partition splits, and the join node is marked isSkewJoin=true.
Why it sometimes doesn't kick in:
| Reason | What to do |
|---|---|
| It's a broadcast join, aggregation or window, not a shuffle join | Steps 4–6 |
| Join type can't split that side: left outer, left semi and left anti only split the left side; right outer only the right; full outer neither | Isolate the hot key (Step 5) |
| The hot partition is under 256 MB, or the median is also big | Lower the threshold or factor for this job |
| Splitting would add an extra shuffle, so AQE declines | spark.sql.adaptive.forceOptimizeSkewedJoin=true if the trade is worth it |
| A single key is bigger than everything else combined | AQE splits by map output blocks, so it helps, but the duplicated other side may get large; consider Step 5 |
For NorthBridge's case (sales LEFT JOIN customers), the skewed side was the left, so AQE could split it. Runtime came down to 35 minutes. Good, but the real problem was still upstream.
Step 4 — Fix the key itself
Most hot keys aren't real business entities. They're defaults: NULL, '', 'UNKNOWN', 0, -1, 'N/A'. Ask whether those rows need to go through the join at all.
is_guest = F.col("customer_id").isNull() | F.col("customer_id").isin("UNKNOWN", "", "-1")
known = sales.where(~is_guest)
guests = sales.where(is_guest)
customers = spark.table("northbridge.silver.customers")
enriched_known = known.join(customers, "customer_id", "left")
enriched_guests = (guests
.withColumn("customer_id", F.lit(None).cast("string"))
.join(customers.limit(0), "customer_id", "left")) # same columns, all NULL
result = enriched_known.unionByName(enriched_guests)Guest rows skip the shuffle join entirely and get the dimension's columns as NULL (or map them to the -1 "unknown" member of your dimension; see Surrogate Keys in the Lakehouse).
A note on NULL: for inner joins, Spark adds an isnotnull(key) filter automatically, so NULL keys never reach the shuffle. For outer joins they're kept, and they all hash to the same partition. A left join with millions of NULL keys is a classic hidden skew.
And fix the source. A one-line change in the POS feed to send a real guest ID, or a bronze-to-silver rule that maps defaults to a known member, removes the problem for every downstream job.
Step 5 — Isolate hot keys that are real
Sometimes the hot key is legitimate: one marketplace seller with 40% of orders, one huge B2B customer. Split the hot keys out and handle them with a different join strategy.
hot_keys = [r.customer_id for r in hot.where("pct > 1").collect()] # small list, driver-safe
big_hot = sales.where(F.col("customer_id").isin(hot_keys))
big_rest = sales.where(~F.col("customer_id").isin(hot_keys))
small_hot = customers.where(F.col("customer_id").isin(hot_keys)) # a few rows
joined = (big_rest.join(customers, "customer_id", "left")
.unionByName(big_hot.join(F.broadcast(small_hot), "customer_id", "left")))The hot rows join against a tiny broadcast table, so they're spread across all the tasks that already hold them; no shuffle by key. The rest goes through a normal, now-balanced shuffle join. More on broadcast in Broadcast vs Sort-Merge vs Shuffle Hash Join.
Step 6 — Salt (when nothing else works)
Salting spreads one key across N partitions by adding a random number to it. The other side must then contain every salt value for that key, so it's multiplied by N.
Salting a join, hot keys only
N = 16 # roughly: hot partition size / target partition size
big_s = sales.withColumn(
"salt",
F.when(F.col("customer_id").isin(hot_keys), (F.rand(seed=42) * N).cast("int"))
.otherwise(F.lit(0)))
small_s = (customers
.withColumn("salts",
F.when(F.col("customer_id").isin(hot_keys), F.sequence(F.lit(0), F.lit(N - 1)))
.otherwise(F.array(F.lit(0))))
.withColumn("salt", F.explode("salts"))
.drop("salts"))
joined = big_s.join(small_s, ["customer_id", "salt"], "left").drop("salt")Only hot keys are multiplied. Salting every key multiplies the whole dimension by N, which is usually a worse problem than the skew.
Salting an aggregation
For sum, count, min and max, Spark already does partial aggregation on the map side, so each task sends one row per key into the shuffle. Skew rarely hurts these.
It does hurt aggregations that can't be pre-reduced: collect_list, collect_set, percentile, exact distinct counts. Two-stage aggregation fixes them:
# Exact distinct customers per store, where one store has 40% of rows
stage1 = (sales.select("store_id", "customer_id")
.distinct()) # shuffle by (store_id, customer_id): spread out
result = stage1.groupBy("store_id").count() # one row per pair → small, cheapThe first shuffle uses a composite key, so the hot store's rows are spread across many partitions.
Skewed windows
Window.partitionBy("store_id") puts every row of the hot store in one task, and AQE doesn't split windows. Options: partition the window more finely if the logic allows (store_id, sale_date), compute the hot key separately, or pre-aggregate before the window. See PySpark Window Functions.
Skewed writes
df.repartition("sale_date").write.partitionBy("sale_date") sends Black Friday to one task. Use the REBALANCE hint so AQE can split oversized partitions, or repartition("sale_date", salt) with a small salt. Better still, cluster instead of partition; see Liquid Clustering vs Partitioning vs Z-Order.
The result
NorthBridge mapped guest checkouts to the dimension's unknown member in silver and stopped sending them through the join. AQE handled the remaining minor skew. Stage 14 went from 2.9 hours for the slowest task to 2.4 minutes; the job went back to 24 minutes. Nobody had to salt anything.
From production: gotchas and lessons
-
Symptom: A
MERGEinto a Delta table ran one task for 40 minutes. Cause: The source batch had 8 million rows for one default key, all matching the same target files. Fix: Filter or route the default keys before theMERGE, and deduplicate the source. See Delta Lake MERGE patterns. -
Symptom: Salting fixed the slow task but the job got slower overall. Cause: Every key was salted with N=100, so a 20 GB dimension became 2 TB. Fix: Salt only the hot keys, and size N from the hot partition, not by habit.
-
Symptom: More shuffle partitions made no difference. Cause: Hash partitioning sends a key to exactly one partition, however many there are. Fix: More partitions fix uneven distribution of many keys. They never fix one hot key.
-
Symptom: AQE's skew join kicked in, but the task processing the split pieces ran out of memory. Cause: The other side of the join for that key was also huge, and it's duplicated for every split. Fix: Isolate that key and handle it separately, or aggregate both sides before joining.
-
Symptom: A
left_antijoin was skewed and AQE did nothing. Cause: The skew was on the right side; AQE only splits the left side of left-anti joins. Fix: Deduplicate the right side's keys first (anti joins only need distinct keys), which usually removes the skew entirely.
Performance and cost notes
Skew is expensive in a way the job duration hides: while one task runs, every other core on the cluster is idle but billed. A 2.9-hour straggler on a 40-node cluster costs 40 nodes × 2.9 hours.
Fixes ranked by cost: AQE (free), key cleanup (one-time code, saves every run), isolation (some code, little extra data), salting (more code, more data, more shuffle). Pick the cheapest one that works.
When not to use this
Don't salt pre-emptively. Mild imbalance (max 2–3× the median) is normal and not worth complexity. And don't treat skew as a Spark problem when it's a data quality problem: a default key carrying 30% of rows is a bug in the source.
Checklist
- Stage summary: max vs median for duration and shuffle read
- Hot keys found with
groupBy(key).count()on every shuffle key - AQE skew join on;
isSkewJoinchecked in the SQL tab -
NULL/ default keys filtered, mapped or routed before outer joins - Real hot keys isolated and broadcast where possible
- Salting limited to hot keys, with N sized from the data
- Windows, aggregations and writes checked, not just joins
Practice
- Try: PySpark Interview Questions: 50 Coding and Scenario Problems
- Try: Delta Lake Interview Questions: 25 Scenario Problems
- Build it yourself: generate 100 million rows where 30% share one key, join them to a 1 million row dimension, and try each fix in turn. Record the max task duration for each.
Further reading
Keep going
Reading the Spark UI: Stages, Tasks, Spill and Skew
A practical route through the Spark UI: map a slow query to its stage, read the summary metrics, and recognise skew, spill, tiny files and GC pressure.
Why AQE Coalesces Shuffle Partitions (and When It Can't Help)
How Adaptive Query Execution merges small shuffle partitions at runtime, the settings that control it, and the cases where you still have to tune.
Broadcast Join vs Sort-Merge Join vs Shuffle Hash Join: How Spark Chooses
How each Spark join strategy moves data, the rules Spark uses to pick one, how AQE changes the choice at runtime, and when to step in with a hint.
One practical note a week
Get new articles, problems and guides in your inbox.
Thanks! You're on the list. (Local demo — no email provider is wired up yet.)