IntermediateSpark · 14 min · 15 challenges

Data Skew: Intermediate

You're a data engineer at Instagram, and the nightly job that joins every follow edge to the account being followed has stalled at 199 of 200 tasks. The last task holds every edge pointing at Cristiano Ronaldo, the most-followed person on the platform. Doubling the partition count changes nothing. This lesson shows you how to measure that key, split it, and finish the stage on time.

Measuring Skew

Daily Life
Interviews
Skew lives in the data before Spark touches it: a few values of the join or grouping key carry far more rows than the rest. The shuffle turns that imbalance into task time, because hash partitioning sends every row of a key to the same reducer. The most useful measurement is therefore a row count per key, taken on the side that will be shuffled and ranked from heaviest down.

Rank the keys by row count

The cell below ranks order_items by product_id. A groupBy already gathers every missing key into a group of its own. The cast and coalesce give that group the string label NULL and give every key 1 type, so the missing value ranks, sorts and displays like any other key. Each key's share divides its rows by the table's total, which the first count() fetches as a job of its own. Run it and read the top row: that value sets the minimum load of whichever task receives it.

from pyspark.sql import functions as F

items = spark.table("order_items")
total = items.count()

key_counts = (
    items
    .withColumn("key", F.coalesce(F.col("product_id").cast("string"), F.lit("NULL")))
    .groupBy("key")
    .agg(F.count("*").alias("rows"))
    .withColumn("share", F.round(F.col("rows") / total, 4))
)

key_counts.orderBy(F.desc("rows"), "key").limit(10).show()

This measurement stays cheap on a huge table. count combines before the shuffle, so each map task sends a single partial count per key it saw, never the rows themselves. Because limit(10) follows the orderBy, Spark also keeps a running top 10 in each partition instead of range-shuffling every key, and the ranking job runs with only the shuffle that groupBy needs.

From a count to a verdict

A row count becomes a verdict when you compare it with what a task normally receives. Take a follows table of 300M rows, shuffled into 200 partitions on followee_id. Spread evenly, each task would get 1.5M rows: the even share. Any key holding more than the even share is hot, because its task can't finish before it has processed that key's rows, however the other keys fall.

followee_idrowsshareverdict
acct_100130,000,00010.0%hot: 20 times the even share
NULL12,000,0004.0%hot: 8 times the even share
acct_20022,400,0000.8%hot: 1.6 times the even share
acct_30031,100,0000.37%below the 1.5M even share
3
hot values among 300M rows
14.8%
of all rows held by those 3 values

Run the count on both sides of a join. A key that is hot on both sides compounds: if the 30M follows rows of acct_1001 met 5 matching rows on the other side, the join would emit 150M rows, every one built on that key's task. That is the duplicate-key blowup and skew at once, and only per-key counts on each side reveal it before the job runs.

The ranking names the exact values to fix, which the running job cannot. Once the stage runs, the straggler shows up as a single task reading far more shuffle data than its peers, but that figure is a partition's total: the hot key mixed with every other key that hashed alongside it. The per-key count tells you which value it is and how many rows it brings.

Measure what each task will get

from pyspark.sql import functions as F
per_task = (
follows
.repartition(200, "followee_id")
.groupBy(F.spark_partition_id().alias("task"))
.count()
.orderBy(F.desc("count"))
)

This version answers the task-level question directly. It hashes followee_id into the same 200 partitions the join would use, then counts the rows that landed in each. Its top row is the straggler's load, neighbours included, before the real job ever runs. It pays for that with a full shuffle of the table, so run the per-key ranking first and reach for this one when you need partition totals.

Multiple Choice

A join shuffles 400M rows into 400 partitions. The per-key count of its join key returns these top values: k1 with 9M rows, k2 with 3M, k3 with 800K and k4 with 600K. Which values are hot?

Salting a Hot Key

Daily Life
Interviews

A hot key has a single hash value, so it has a single destination. Salting gives it several. Add a salt column holding a number from 0 to N-1 to every row of the big side, then join on the key and the salt together. The 30M rows of acct_1001 now form N separate join keys, and each of those hashes to a partition independently of the others.

The small side has to keep up. A follows row salted 7 can only match an account row that also carries salt 7, so every small-side row is copied N times, once per salt value. The join's output stays the same: each big-side row still meets exactly 1 copy of its partner.

orders, salt = order_id % 3
order_idcustomer_idsalt
1c71
2c72
3c70
5c72
6c70
7c71
customers, copied once per salt
customer_idnamesalt
c7Dee0
c7Dee1
c7Dee2
c1Ana0
c1Ana1
c1Ana2

The tables above show the c7 rows of each side and the copies of c1. The animation runs the whole join on 9 orders, 6 of them for customer c7, with 3 shuffle partitions and broadcasting switched off so both sides shuffle. The salt order_id % 3 splits c7 into 3 keys of 2 rows each: orders 3 and 6 carry salt 0, orders 1 and 7 salt 1, orders 2 and 5 salt 2. The 4 customers become 12 rows. Watch where the 3 c7 keys land.

spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1)
salted_orders = orders.withColumn("salt", F.col("order_id") % 3)
salted_customers = customers.withColumn("salt", F.explode(F.array(F.lit(0), F.lit(1), F.lit(2))))
salted_orders.join(salted_customers, ["customer_id", "salt"]).collect()
orders9 rows
order_id
customer_id
1
c7
2
c7
3
c7
4
c2
5
c7
6
c7
7
c7
8
c3
9
c1
customers4 rows
customer_id
name
c1
Ana
c2
Ben
c3
Chen
c7
Dee
Preparing the animation

Each (customer_id, salt) pair hashes on its own, so the 3 c7 keys are free to reach different tasks, and 2 of them can still share one: salting spreads a key across up to N tasks, never a guaranteed N. Salting adds no shuffle either. The plan still has 1 exchange per side, hashing on 2 columns instead of 1. The output holds the same 9 rows the unsalted join returns; drop salt once the join is done.

Loading the challenge

Choosing N

Pick N so each salted piece is about the size of an ordinary task. With section 0's numbers, acct_1001 holds 30M rows against a 1.5M-row even share, so N = 30M / 1.5M = 20, and each piece carries roughly what every other task carries. The bill arrives on the small side: an accounts table of 50M rows, copied 20 times, enters the shuffle 20 times larger.

1B
account rows entering the shuffle
That copy cost makes salting a second resort. If the small side fits under the broadcast threshold, broadcast it instead: the big side never shuffles, so no task ever collects a key. Salt when the small side is too big to broadcast and the hot key is too big for a single task. Section 2 copies only the hot keys' partners instead of the whole table.

Every salt needs a partner

A salted join returns the right rows only when the small side carries every salt the big side can produce. If the big side computes order_id % 20 while the small side is copied over 0 to 18, every row salted 19 finds no partner, and an inner join drops it without an error. Build both sides from the same N. Derive the salt from a column with many distinct values, such as a unique id, so a row gets the same salt on every run, and never from the join key, which would hand every row of the hot key the same salt.

Multiple Choice

This salted join runs without an error. What happens to the order rows whose order_id % 8 equals 7?

salted_orders = orders.withColumn("salt", F.col("order_id") % 8)
salted_customers = customers.withColumn(
"salt", F.explode(F.array(*[F.lit(i) for i in range(7)]))
)
joined = salted_orders.join(salted_customers, ["customer_id", "salt"])

The cell salts a join of order_items to products with N = 4. The products table is tiny, so the cell turns broadcasting off to get the sort-merge join a 50M-row table would get. The output counts joined rows per salt value.

from pyspark.sql import functions as F

spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1)
N = 4

items = spark.table("order_items")
products = spark.table("products")

salted_items = items.withColumn("salt", F.col("item_id") % N)
salted_products = products.withColumn(
    "salt", F.explode(F.array(*[F.lit(i) for i in range(N)]))
)

joined = salted_items.join(salted_products, ["product_id", "salt"])
joined.groupBy("salt").count().orderBy("salt").show()

Isolating Hot Keys

Daily Life
Interviews
Salting copies the whole small side N times to rescue a few keys. When the measurement names only a handful of hot values, split the big side by those values instead and send each part down its own path. The hot rows join through a broadcast of the few small-side rows that match them, and the rest join as before, with no key left that is too big for its task.
300M rows
follows
50M rows
accounts
collect() to the driver
measure hot keys
isin(hot_keys)
hot follows
~isin(hot_keys)
other follows
2 rows
hot accounts
broadcast
no shuffle
broadcast join
both sides shuffled
sort-merge join
PARTITIONS200
no shuffle
unionByName
result
joined follows

The measuring job's hot list decides each row's path. Hot follows meet 2 broadcast accounts where they were read; every other follow takes the sort-merge join, and the union stacks both results.

from pyspark.sql import functions as F
hot_rows = (
follows
.filter(F.col("followee_id").isNotNull())
.groupBy("followee_id")
.count()
.filter(F.col("count") > 1_500_000)
.collect()
)
hot_keys = [row["followee_id"] for row in hot_rows]
hot_part = (
follows.filter(F.col("followee_id").isin(hot_keys))
.join(
F.broadcast(accounts.filter(F.col("account_id").isin(hot_keys))),
F.col("followee_id") == F.col("account_id"),
)
)
rest_part = (
follows.filter(~F.col("followee_id").isin(hot_keys))
.join(accounts, F.col("followee_id") == F.col("account_id"))
)
result = hot_part.unionByName(rest_part)

The collect() runs the measuring job first, on its own, and returns 2 ids, acct_1001 and acct_2002; the isNotNull filter keeps NULL out of the list, and section 3 handles it. The hot path broadcasts the 2 matching accounts to every executor, so the 32.4M hot follows join on the tasks that read them, spread however the input was split, and no task gathers a key. The rest path is the original sort-merge join over every other follow, and its largest key is now acct_3003 at 1.1M rows, under the 1.5M even share.

The hot path broadcasts only because of the F.broadcast hint. Without column statistics, Spark estimates a filtered table at its unfiltered size, so it sees all 50M accounts instead of 2 rows and plans a sort-merge join. The hint states what the measuring job already proved.

Count the plan's shuffles: 2, a shuffle for each side of the rest join. The hot path adds a broadcast and no exchange, and unionByName stacks the 2 results without moving a row. The new costs are the measuring job and a second scan of follows, because each filter reads the table on its own. Both are even passes with no straggler.

Multiple Choice

In the isolation code above, accounts holds 50M rows, far over the broadcast threshold, and hot_keys holds 2 ids. How many shuffle exchanges does the plan for result contain?

✓Salting the join
  • Copies every small-side row N times
  • A single plan for every key, with no list to maintain
  • Spreads a hot key over up to N tasks
  • Works when a hot key's partners are too many to broadcast
✗Isolating hot keys
  • Copies nothing and broadcasts only the hot keys' partners
  • Needs a measuring job to build the hot list
  • Hot rows join where they were read, with no shuffle
  • Scans the big side twice, once per path

Keep the hot list fresh

Measure the hot list on every run instead of pasting ids into the code. Hot keys move: a celebrity joins, an account goes viral, a promotion makes a single product the week's top seller. A hardcoded list goes stale in silence, and the next new hot key lands back on a single task. The measuring job stays cheap because its counts combine before the shuffle.
When a hot key's partners are too many to broadcast, as when both sides of a many-to-many join are hot, keep the split and salt only the hot path. The copies then cover the hot keys' partner rows alone, a small set of rows copied N times instead of the whole small side.
Multiple Choice

An isolation job runs with a hot list pasted into the code last month: [acct_1001, acct_2002]. This week acct_5005 goes viral and gains 25M follows. What happens to its rows on tonight's run?

Null-Key Skew

Daily Life
Interviews

In section 0's ranking of follows, the second-hottest value was NULL, with 12M rows. Missing keys pile up because a single cause creates them in bulk: follows of deleted accounts, events from logged-out visitors, orders written before the customer id was captured. Every null hashes to the same value, so a shuffle on that column sends all of them to a single partition.

Inner joins drop them, left joins keep them

A null key can never satisfy an equality, so an inner join has nothing to find for it. Catalyst knows this: during logical optimization it adds an isnotnull filter on each join key, and null-keyed rows are discarded before the shuffle. A left join cannot discard them. It must return every left row, matched or not, so its null-keyed rows travel through the exchange and pile onto a single reducer that will match none of them.

The animation runs a left join of 7 orders to 3 customers with broadcasting off and 2 shuffle partitions. Four of the 7 orders have no customer_id. Watch the 4 null rows: they leave their input tasks for the same reducer, and each comes out with a null name.

spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1)
orders.join(customers, "customer_id", "left").collect()
orders7 rows
order_id
customer_id
1
c1
2
NULL
3
c2
4
NULL
5
NULL
6
c3
7
NULL
customers3 rows
customer_id
name
c1
Ana
c2
Ben
c3
Chen
Preparing the animation

At scale that reducer holds the 12M null follows plus its share of real keys, and the work is pure overhead: each output row is the input row with nulls appended. A groupBy on the same column also builds a null group, but a combining aggregate such as count keeps it to a partial per map task, so the left join is where null skew costs the most.

Send the nulls around the join

from pyspark.sql import functions as F
has_key = orders.filter(F.col("customer_id").isNotNull())
no_key = orders.filter(F.col("customer_id").isNull())
joined = has_key.join(customers, "customer_id", "left")
result = joined.unionByName(no_key, allowMissingColumns=True)

The null rows skip the join altogether. unionByName with allowMissingColumns=True, available since Spark 3.1, fills the customer columns with nulls for them, which is what the left join would have produced. Only keyed rows can enter an exchange, and the reducer that used to collect every null now gets an ordinary share.

Sentinel values such as '', 'unknown', 0 or -1 behave like a real key. Catalyst infers only isnotnull, so an inner join shuffles every sentinel row to the same task whether it finds a partner, and a matching placeholder row in the dimension also multiplies the output on that task. Count them like any hot key and isolate them. The isolation filter from section 2 also drops nulls: ~F.col("followee_id").isin(hot_keys) evaluates to null on a null key, and filter discards null. In an inner join that loses nothing; in a left join the rest path needs F.col("followee_id").isNull() | ~F.col("followee_id").isin(hot_keys) to keep those rows.

TIP
To see Catalyst drop null keys, call explain() on an inner join and find isnotnull(customer_id) in the Filter on each side. On a left join that filter appears on the right side only, a sign that the left side's nulls will shuffle.
Multiple Choice

A job left-joins page_views to users on user_id with 400 shuffle partitions, and 40% of page views have a null user_id. Which rewrite returns the same rows while shuffling none of the null-keyed page views?

Before choosing a fix, measure how much of the key is missing. The cell computes it as a single global aggregate: 1 row holding the total, the null count and the null share, with no row per region and no separate count() job to divide by.

from pyspark.sql import functions as F

orders = spark.table("orders")
missing = F.col("region").isNull().cast("int")

orders.agg(
    F.count("*").alias("rows"),
    F.sum(missing).alias("null_region_rows"),
    F.round(F.avg(missing), 3).alias("null_share"),
).show()

Why More Partitions Won't Help

Daily Life
Interviews

Raising spark.sql.shuffle.partitions is the right fix when every task is too big because the data is big. It is the wrong fix for a hot key, and the reason is a single line of arithmetic. Hash partitioning places a row in partition pmod(hash(key), P). A key has a single hash, so for every P it maps to a single partition, and every row carrying it goes there. Raising P divides the other keys more finely and leaves the hot key whole.

shuffle partitionseven share per taskhot task, at leasthot task vs even share
2001.5M rows30M rows20x
2,000150K rows30M rows200x
20,00015K rows30M rows2,000x

A stage ends when its slowest task ends. At 200 partitions the hot task holds the 30M rows of acct_1001 plus its share of the other 270M, around 1.35M more. At 2,000 partitions that share falls to about 135K, so the straggler loses roughly 4% of its rows while the stage now schedules 10 times as many tasks. The stage barely speeds up.

The animation replays section 1's 9 orders without the salt, at 6 shuffle partitions, twice the 3 used there. The 6 orders for c7 still meet on a single task. The other 3 orders land wherever their keys hash, and at least 2 of the 6 tasks receive nothing at all.

spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1)
spark.conf.set("spark.sql.shuffle.partitions", 6)
orders.join(customers, "customer_id").collect()
orders9 rows
order_id
customer_id
1
c7
2
c7
3
c7
4
c2
5
c7
6
c7
7
c7
8
c3
9
c1
customers4 rows
customer_id
name
c1
Ana
c2
Ben
c3
Chen
c7
Dee
Preparing the animation
Multiple Choice

A sort-merge join's stage runs 41 minutes, 40 of them spent waiting on a single task. A teammate raises spark.sql.shuffle.partitions from 200 to 1,000, and the stage now runs 40 minutes. What explains the result?

Pick the fix from the measurement

What the measurement showsThe fix
The small side fits under the broadcast ceilingBroadcast it, so the big side never shuffles
A handful of hot keys with few partner rowsIsolate them on a broadcast path and union back
Hot keys whose partners are too many to broadcastSalt the join, with N = hot rows / even share
NULL is the hot value in a left joinRoute the null rows around the join
A hot key in a sum or count aggregationOften nothing: partial results shrink it before the shuffle
No hot key, but every task is too bigRaise spark.sql.shuffle.partitions

A groupBy with sum or count combines before the shuffle, so the hot key's reducer receives at most a partial result from each map task: 30M rows read by 200 map tasks arrive as no more than 200 partials. Skew bites the aggregations whose partial result doesn't shrink, such as collect_list, which ships every value it gathers.

Multiple Choice

A left join of events (2B rows, 1,000 shuffle partitions) to a 20GB devices table is stuck on a straggler. The per-key count of device_id returns NULL at 300M rows and dev_0, a placeholder id, at 40M rows; every other value is under 2M. Which plan fixes it without changing the output?

The capstone puts sections 0 to 2 together on the practice data. It measures the 2 heaviest product_id values in transactions, sends their rows down a broadcast path, joins the rest with a sort-merge join, and counts the rows each path produced. Broadcasting is switched off so the rest path really shuffles, and the F.broadcast hint overrides that setting on the hot path. On a table this small, hot only means heaviest, but the plan is the one you would ship.

from pyspark.sql import functions as F

spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1)

txns = spark.table("transactions")
products = spark.table("products")

top = (
    txns.filter(F.col("product_id").isNotNull())
    .groupBy("product_id")
    .count()
    .orderBy(F.desc("count"), "product_id")
    .limit(2)
    .collect()
)
hot_keys = [row["product_id"] for row in top]
is_hot = F.col("product_id").isin(hot_keys)

hot_part = txns.filter(is_hot).join(F.broadcast(products.filter(is_hot)), "product_id")
rest_part = txns.filter(~is_hot).join(products, "product_id")

result = hot_part.unionByName(rest_part)
result.groupBy(is_hot.alias("hot_path")).count().orderBy("hot_path").show()
PUTTING IT ALL TOGETHER

> Back at Instagram, the follows job left-joins every follow edge to the profile of the account being followed. Measuring followee_id shows 2 values far above the even share: the account of Cristiano Ronaldo, the most-followed person on the platform, and NULL, left behind by edges that point at deleted accounts. The fix that ships routes the null edges around the join, sends Ronaldo's edges through a broadcast of his single profile row, joins everything else as before, and unions the 3 parts.

The per-key count from section 0 names Ronaldo's account and NULL as the hot values, by comparing each with the even share of total rows over shuffle partitions.
The null edges take the route from section 3, because a left join would shuffle all of them to a single task even though none can match a profile.
Ronaldo's edges take the isolated path from section 2, joining a broadcast profile row where they were read, so no task gathers them and the profile table is never copied.
Had his edges met too many partner rows to broadcast, the salt from section 1, applied to that path alone, would spread them across up to N tasks.
Section 4 explains why the first attempt, doubling the partition count, changed nothing: each hot value keeps a single partition at any count.
KEY TAKEAWAYS
Measure skew as rows per key on the side being shuffled. A key is hot when it holds more rows than the even share: total rows over shuffle partitions.
Salting turns a hot key into N join keys, spread over up to N tasks, by copying the small side N times. Choose N as hot rows over the even share, and give the small side every salt.
Isolating sends a handful of measured hot keys through a broadcast join and the rest through the normal join, then unions the parts without copying anything.
Inner joins drop null keys before the shuffle; left joins shuffle them onto a single task, so route them around the join and add the missing columns back.
A key has a single hash and so a single partition at any count: more shuffle partitions shrink every task except the straggler.

Find the keys behind a straggler, then salt, isolate or defuse them, since more partitions never split a hot key.

Category
Spark
Difficulty
intermediate
Duration
14 minutes
Challenges
15 hands-on challenges

Topics covered: Measuring Skew, Salting a Hot Key, Isolating Hot Keys, Null-Key Skew, Why More Partitions Won't Help

Lesson Sections

  1. Measuring Skew (concepts: Data Skew)

    Skew lives in the data before Spark touches it: a few values of the join or grouping key carry far more rows than the rest. The shuffle turns that imbalance into task time, because hash partitioning sends every row of a key to the same reducer. The most useful measurement is therefore a row count per key, taken on the side that will be shuffled and ranked from heaviest down. Rank the keys by row count From a count to a verdict The ranking names the exact values to fix, which the running job cann

  2. Salting a Hot Key (concepts: Salting Strategy)

    Choosing N That copy cost makes salting a second resort. If the small side fits under the broadcast threshold, broadcast it instead: the big side never shuffles, so no task ever collects a key. Salt when the small side is too big to broadcast and the hot key is too big for a single task. Section 2 copies only the hot keys' partners instead of the whole table. Every salt needs a partner

  3. Isolating Hot Keys (concepts: Data Skew)

    Salting copies the whole small side N times to rescue a few keys. When the measurement names only a handful of hot values, split the big side by those values instead and send each part down its own path. The hot rows join through a broadcast of the few small-side rows that match them, and the rest join as before, with no key left that is too big for its task. Keep the hot list fresh Measure the hot list on every run instead of pasting ids into the code. Hot keys move: a celebrity joins, an accou

  4. Null-Key Skew (concepts: Data Skew)

    Inner joins drop them, left joins keep them Send the nulls around the join

  5. Why More Partitions Won't Help (concepts: Data Skew)

    Pick the fix from the measurement