Skip to content
Gold 8 min read 2 practice problems ↓

Data skew and salting

A job where 199 tasks finish in seconds and one runs for an hour has skew: one key holds far more data than the rest. This lesson shows how to spot it in the Spark UI, why it happens, and how salting spreads a hot key across many tasks.

Step 2 · Spark internals · Gold · Skew, lesson 1 of 2

Read first: Jobs, stages and tasks · Narrow vs wide transformations (skip if you know them)

In plain words first

At a supermarket, one checkout has a queue of 50 people because everyone wants that cashier; the other nine are empty. The shop is as slow as its longest queue.

Skew is one key (one checkout) getting most of the rows. Salting sends the people in that queue to several checkouts by adding a random number to the key, then adds the results back together.

The symptom

A stagestage: A group of steps Spark can run without moving data between machines. A new stage starts at every shuffle. Learn more → shows 199 of 200 taskstask: The work for one partition in one stage, run on one CPU core. Learn more → finished in seconds and one still running after an hour. In the stage detail, the max task duration and shuffleshuffle: Moving rows between machines so that all rows with the same key end up together. Needed by joins, groupBy and sorting, and usually the most expensive step of a job. Learn more → read size are orders of magnitude above the median. That one task may also spillspill: Writing data to local disk because it does not fit in memory. Slower, but the job keeps running. Learn more → heavily or die with an out-of-memory error.

Task metricMedianMax
Duration6 s58 min
Shuffle read120 MB48 GB
Spill (disk)031 GB

The cause

Hash partitioning sends every row of a key to the same partitionpartition: A chunk of a DataFrame's rows. Spark processes each partition as one task, so partitions decide how much work runs in parallel. Learn more →: that is what makes joins and aggregations correct. Real data is rarely uniform. Common culprits: null or empty keys (often millions of rows with customer_id = null), default values like "unknown" or 0, and genuinely popular entities, such as one huge customer or a viral product.

Tip: find the hot keys first: df.groupBy("key").count().orderBy(F.desc("count")).show(20). Often the top key is null, and the right fix is to filter or handle nulls separately rather than salt.

Try these first

  1. Handle null keys separately. Null keys never match in a join, so filter them out before the join and union them back afterwards if needed.
  2. Broadcastbroadcast join: A join where the small table is copied to every machine, so the big table never has to be shuffled. Learn more → the other side. If the table being joined is small enough, a broadcast join has no shuffle, so no skew.
  3. Let AQEAQE: Adaptive Query Execution: Spark re-plans a running query using the real data sizes it has measured. Learn more → split it. For sort-merge joinssort-merge join: Spark's default join for two large tables: both sides are shuffled and sorted by the key, then matched in one pass. Learn more →, AQE skew handling splits oversized partitions automatically (see AQE skew-join handling).
  4. Pre-aggregate. If the hot key only needs a total, aggregate before joining so the hot key becomes one row.

Salting a join

Step 1 · salt the big side

Add a random salt from 0 to N-1 to every row of the large, skewed table. Rows of the hot key now carry N different (key, salt) combinations.

The command

N = 16
big_s = big.withColumn("salt", (F.rand() * N).cast("int"))
CREATE TEMP VIEW big_salted AS
SELECT *, CAST(rand() * 16 AS INT) AS salt FROM big

Step 2 · replicate the small side

Every row of the other table must be able to meet every salt, so copy it N times, once per salt value.

The command

small_s = small.withColumn("salt", F.explode(F.sequence(F.lit(0), F.lit(N - 1))))
CREATE TEMP VIEW small_salted AS
SELECT s.*, salt
FROM small s
LATERAL VIEW explode(sequence(0, 15)) t AS salt

Step 3 · join on key + salt

Joining on both columns hashes the hot key into up to N partitions instead of one. Each task gets about 1/N of the hot key's rows.

The command

joined = big_s.join(small_s, ["key", "salt"]).drop("salt")
SELECT b.*, s.value
FROM big_salted b
JOIN small_salted s ON b.key = s.key AND b.salt = s.salt

Cost · the trade-off

The small side grows N times, and the join now shuffles that bigger table. Pick N from the skew: if the hot key is 50 times the median partition, N of 32 to 64 is reasonable. Salting only the hot keys (salt = 0 for everything else, and replicate only those keys) keeps the overhead small.

Salting an aggregation

AQE does not split skewed aggregations, so salting is the main tool here. Aggregate in two phases: first by (key, salt), which spreads the hot key across N tasks, then by key alone over the much smaller partial results.

PySparkSpark SQL
partial = (events
    .withColumn("salt", (F.rand() * 16).cast("int"))
    .groupBy("key", "salt").agg(F.sum("amount").alias("s"), F.count("*").alias("n")))
result = partial.groupBy("key").agg(F.sum("s").alias("total"), F.sum("n").alias("rows"))
SELECT key, SUM(s) AS total, SUM(n) AS rows
FROM (
  SELECT key, salt, SUM(amount) AS s, COUNT(*) AS n
  FROM (SELECT *, CAST(rand() * 16 AS INT) AS salt FROM events)
  GROUP BY key, salt)
GROUP BY key

This works for any aggregate that can be combined: sums, counts, min, max, and averages computed as sum divided by count. It does not work directly for exact distinct counts or medians.

Note: plain sums and counts are already partially aggregated before the shuffle, so skew hurts them less. Salting matters most for aggregations that cannot shrink early, such as collect_list, and for joins.

Try it yourself

Each example says what it shows, then the output from a real run and what to notice in it, so you can follow without running anything. To try one yourself, paste it into a local Spark session, with spark already created: each builds its own data.

Goal: Join on a key where one customer has most of the rows, without one task doing all the work.

Production patternPySpark · A reusable salted join for a known hot key
from pyspark.sql import DataFrame, functions as F


def salted_join(big: DataFrame, small: DataFrame, key: str, buckets: int) -> DataFrame:
    """Join on key, spreading each key of big over up to buckets tasks."""
    salt = spark.range(buckets).withColumnRenamed("id", "_salt")
    big_salted = big.withColumn("_salt", (F.rand(seed=42) * buckets).cast("long"))
    return big_salted.join(small.crossJoin(salt), [key, "_salt"]).drop("_salt")


clicks = spark.range(0, 300_000).withColumn(
    "customer", F.when(F.col("id") % 10 < 9, 0).otherwise(F.col("id") % 1000))
customers = spark.range(0, 1000).selectExpr("id AS customer", "id % 5 AS segment")

# as if both sides were large
spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1)
joined = salted_join(clicks, customers, "customer", buckets=16)
(joined.groupBy("segment").count()
       .write.mode("overwrite").parquet("lab/skew/clicks_by_segment"))
spark.read.parquet("lab/skew/clicks_by_segment").orderBy("segment").show()

Output from a real run

+-------+------+
|segment| count|
+-------+------+
|      0|270000|
|      4| 30000|
+-------+------+

What to notice:

  • Segment 0 has 270,000 clicks: customer 0 is the hot key (90% of rows). The rest are customers ending in 9, all in segment 4.
  • The counts are what a plain join gives. The salt changes how the work is split, not the answer.
  • Try AQE's skew handling first; salt when AQE cannot split it (an aggregation, some join types) or you know the hot keys in advance.

Goal: See the skew partition by partition, and how adding a salt spreads it.

ExplorePySpark · See the skew per partition, and how a salt spreads it
from pyspark.sql import functions as F

spark.conf.set("spark.sql.adaptive.enabled", "false")     # show raw skew
spark.conf.set("spark.sql.shuffle.partitions", "8")
# 90% of rows share one key: a hot customer.
events = spark.range(0, 200_000).withColumn(
    "customer", F.when(F.col("id") % 10 < 9, F.lit(0)).otherwise(F.col("id") % 1000))


def rows_per_partition(df):
    counts = df.groupBy(F.spark_partition_id().alias("p")).count().orderBy("p")
    return [r["count"] for r in counts.collect()]


print("by customer:", rows_per_partition(events.repartition("customer")))
salted = events.withColumn("salt", (F.rand(seed=7) * 8).cast("int"))
print("by customer + salt:", rows_per_partition(salted.repartition("customer", "salt")))

Output from a real run

by customer: [1800, 3400, 2800, 2800, 1400, 182400, 2000, 3400]
by customer + salt: [25311, 70712, 47147, 2126, 2321, 25149, 2457, 24777]

What to notice:

  • By customer alone, one partition holds 182,400 of the 200,000 rows: the hot customer's rows all go to one task.
  • With the salt added, the largest partition is 70,712: the hot key is spread over several tasks. Not perfectly even, but no task does nearly everything.

Common mistakes

  • Salting without finding the hot keys — Often the hot key is null, and filtering it is the whole fix.
  • Salting both sides randomly — Random salts on both sides would almost never match. Randomise one side, replicate the other.
  • Picking a huge N — The replicated side grows N times; keep N proportional to the skew.

Key takeaways

  • Skew means one key, and so one task, gets a disproportionate share of rows.
  • The Spark UI shows it as a huge gap between median and max task metrics.
  • Handle null keys, broadcast or rely on AQE before salting.
  • Salting a join: random salt on the big side, replicate the small side; for aggregations, aggregate twice.

Interview prep

THE QUESTION

"One task in a join stage takes an hour. Walk me through your approach."

Confirm skew in the stage task metrics (max vs median shuffle read). Find the hot keys with a groupBy count. Check for null or default keys and handle them separately. Then: broadcast if the other side is small, rely on AQE skew-join splitting, and only then salt: random salt on the big side, replicate the small side across salts, join on key and salt. Mention the cost of replication.

Avoid: jumping straight to salting. First confirm skew in the Spark UI, then try the cheaper fixes: AQE skew join, broadcasting, filtering null or junk keys.

Follow-ups · answer out loud, then open

Follow-up"What exactly do you do to the two sides when you salt a join?"
Add a random salt from 0 to N-1 to each row of the skewed (large) side, and replicate each row of the other side N times, once per salt value. Join on the key plus salt. The hot key is spread over N tasks. Salt only the hot keys if you can, to avoid replicating the whole smaller table.
Scenario"Most rows in a join have customer_id null, and one task runs for an hour. What is the fix?"
Null keys never match in an equi-join, but they are all hashed to the same partition and still shuffled. Filter them out before the join and union them back afterwards if the join is an outer join. No salting needed.
Trap"Salting is free: just pick a large N like 1,000."
The non-skewed side is replicated N times, so N multiplies its size and the shuffle. Pick N from the skew ratio (the hot key's size divided by a target partition size), and salt only the hot keys if possible.

Check yourself

3 questions

In a salted join, what happens to the smaller table?

Show the answer

It is replicated once per salt value. Each row must meet every possible salt from the big side, so it is copied N times.

Which skew can AQE NOT split automatically?

Show the answer

A skewed groupBy aggregation. AQE skew handling targets sort-merge joins; aggregations need salting or other fixes.

The hottest join key is null. What is the simplest fix?

Show the answer

Filter null keys before the join and handle them separately. Null keys never match in an equality join, so they can be removed before shuffling.

Practise this

Problems that use this, graded on hidden tests

Keep going

Up next · Skew · lesson 2 of 2 · 6 min read
AQE skew-join handling
How Spark detects oversized partitions in sort-merge joins and splits them automatically.

Related lessons

Previous: The small file problem

Primary sources: Performance tuning