Data Skew: Beginner
Watching a join pile rows onto a single task
The program below joins 6 orders to 3 customers on customer_id. Customer c7 placed 4 of the 6 orders. The first line sets spark.sql.autoBroadcastJoinThreshold to -1, which turns broadcasting off, so both tables are shuffled by key the way 2 large tables would be. Each table is read as 2 input partitions, and the shuffle writes 2 output partitions.
spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1)orders.join(customers, "customer_id").collect()
The same shape at 120 million rows
Now scale it up. A plays table holds 120 million rows, a row for every song played, and a nightly job joins it to a tracks table on track_id. Both tables are far too large to broadcast, so Spark shuffles both into 200 partitions, the default value of spark.sql.shuffle.partitions. If plays were spread evenly, each partition would hold 600,000 of them. On this day, a hit track drew 12 million plays.
| partition | plays |
|---|---|
| 0 | 600,000 |
| 1 | 600,000 |
| 87 | 600,000 |
| 199 | 600,000 |
| all 200 | 120,000,000 |
| partition | plays |
|---|---|
| 0 | 540,000 |
| 1 | 540,000 |
| 87 | 12,540,000 |
| 199 | 540,000 |
| all 200 | 120,000,000 |
- ▸Sizes: after the same shuffle, a few partitions hold many times the rows of the typical partition.
- ▸A key: the shuffle placed rows by a column's value, and rows sharing a value had nowhere else to go.
- ▸A shuffle: input partitions follow how the files were split, so the skew in this lesson begins where rows are exchanged by key.
play_id, which is unique for every row, the plays table lands in 200 even partitions. Shuffled by track_id, the same rows produce partition 87.A job shuffles a 100-million-row events table by user_id into 200 partitions. Which situation is data skew?
What the straggler looks like while it runs
In an interactive shell, Spark prints a progress line for each running stage. For the join stage it reads like [Stage 4:===================>(199 + 1) / 200]: 199 tasks done, 1 running, 200 in total. At minute 2 the line reaches (199 + 1) / 200 and then stops moving. The bar looks 99.5% full while 44 of the stage's 46 minutes are still ahead.
| task | rows read | duration |
|---|---|---|
| 0 | 540,000 | 2 min |
| 1 | 540,000 | 2 min |
| 87 | 12,540,000 | 46 min |
| 199 | 540,000 | 2 min |
| 196 others | 540,000 each | 2 min each |
Since Spark 3.2, Spark splits an oversized join partition by default when certain size conditions hold, a feature that dates from Spark 3.0. That feature and where it stops come in a later lesson; the timings here describe the join running without it.
Why the whole job waits on it
Rows cross a shuffle into the join stage and again into the totals stage. The totals stage starts only after all 200 join tasks finish, so task 87 alone decides when daily_royalties lands.
- Read many times the rows of its neighbours
- Slow again on every run, on any machine
- The same partition lags each time the data repeats its key mix
- Its rows share a single hot key
- Read about the same rows as its neighbours
- Normal speed when the job runs on other machines
- Slowness stays with a host across tasks and runs
- Its rows look like any other task's
When the straggler fails
A stage has 100 tasks with a median duration of 90 seconds and a median input of 60 MB. Which task fits the signature of a skew straggler?
Popularity: a few values take most of the activity
Activity piles onto a few winners: a hit song, a celebrity's account, a viral video, the largest seller on a marketplace, a company that runs 50,000 employees through a single account_id. Any key that names who or what produced a row inherits that shape. Columns like track_id, creator_id, seller_id and account_id deserve a hot-key check before any join or window on them.
Placeholders: every missing value becomes a single value
Upstream systems often fill a missing value with a default, such as 'unknown', '', 0, -1 or '1970-01-01'. A website that logs every logged-out visitor as user_id = 0 has made 0 its busiest user, often by a wide margin. Placeholders are the sneakiest source because they stand for no real entity, so a team reasoning about real customers skips past them. A missing key stored as NULL gathers into a single group in the same way, and it gets its own lesson later.
Few distinct values: the key cannot fill the partitions
A device column with 4 values (ios, android, web, tv) can fill at most 4 of the 200 shuffle partitions, and fewer when 2 values hash to the same partition. At least 196 tasks receive no rows at all, and the busy ones are as unequal as the device mix: if 70% of rows come from ios, a single task does 70% of the work. Columns such as country, status, plan and event_type carry the same risk.
Bursts and machines: spikes in time and in traffic
Time keys run hot on the days that matter: a launch date, the hour a campaign goes out, the evening of a championship final. Machine traffic does the same to identity keys, since a load-testing rig or a scraping bot can send millions of events under a single device_id or ip_address. These keys look balanced on an ordinary day and spike on the day the job most needs to finish.
| column | likely hot value | source |
|---|---|---|
| track_id | the day's biggest hit | popularity |
| user_id | 0 for logged-out visitors | placeholder |
| country | the largest market | few distinct values |
| event_date | launch day | burst in time |
| device_id | a load-testing rig | machine traffic |
| play_id | none: each value appears once | unique key |
Your next job shuffles a 50-million-row orders table into 200 partitions. Which key is the strongest hot-key suspect?
Measuring before you run
Read the top rows against the even share of 600,000. A top count in the millions, like the hit track's, means a single partition will dwarf the rest and a straggler is coming. A top count of 3,000 means track_id is safe to shuffle on.
Run the same check on the practice order_items table. The cell lists the 5 products with the most order lines. Then change both product_id references to user_id and see whether customers concentrate order lines more than products do.
key_counts = (
order_items.where("product_id IS NOT NULL")
.groupBy("product_id")
.count()
.orderBy("count", ascending=False)
)
key_counts.show(5)Each line of the count does one job. groupBy names the key column whose values you are testing. count() turns each group into a single row holding the key and its number of rows, in a column named count. orderBy with ascending=False puts the biggest counts first, and that matters because show(5) prints only the first rows: sorted the default ascending way, those first rows are the rarest keys, and the hot one hides at the bottom.
A teammate checks user_id on a 40-million-row events table with the count below. The output lists 5 users with 1 row each. What does that tell them?
| operation | shuffles by the key? | effect of a hot key |
|---|---|---|
| `filter`, `select`, `withColumn` | no | none: each task keeps its own input partition |
| join to a table under 10MB (broadcast) | no, the large side stays put | none |
| `count()` on the whole DataFrame | no key involved | none |
| `groupBy(k)` with `sum`, `count`, `avg` | yes | softened: a summary per input partition travels |
| `groupBy(k)` with `collect_list` | yes | full: every value reaches the hot task |
| join of 2 large tables (sort-merge) | yes, both sides | full, plus extra output rows when keys repeat |
| window with `partitionBy(k)` | yes | full: every row reaches the hot task |
Untouched: steps with no key shuffle
Narrow steps like filter and withColumn run on each input partition where it sits, so key frequencies never come into play. A broadcast join is narrow on its large side: every executor receives a full copy of the small table, and each task joins the large-side rows it already holds. Here is the orders and customers join from the first section without the conf line. Deleting that line does not undo a setting that already ran: the threshold is back at its 10MB default only in a fresh session or after spark.conf.unset("spark.sql.autoBroadcastJoinThreshold"). At the default, the customers table is far under the threshold, so Spark broadcasts it.
orders.join(customers, "customer_id").collect()
No order rows move. Each of the 2 input tasks holds 2 of the c7 orders and matches them against its own copy of customers, so c7's popularity stays spread exactly as the input split spread it. Writing the join as orders.join(F.broadcast(customers), "customer_id") asks for the broadcast by name, whatever the threshold is set to. A hot key in a broadcast join costs nothing extra, which is one more reason to broadcast whenever the small side fits.
orders has 80 million rows, and a single customer_id owns 10 million of them. customers is 3MB. What does the hot customer do to this join?
Softened: sums, counts and averages
A groupBy("track_id").count() on plays does shuffle by the hot key, but Spark first counts each key inside every input partition and ships only those partial counts. If plays is read as 960 input partitions, the hit track reaches its task as at most 960 small rows, which that task adds up in moments. The same holds for sum, avg, min and max. That pre-totaling is why the per-key count from the previous section stays cheap; how it works is a later lesson's subject.
Hit in full: joins, windows and row lists
When both sides of a join are too large to broadcast, Spark shuffles both by the join key and joins them partition by partition, a strategy called sort-merge join. Every one of the hit track's 12 million plays travels to partition 87. The damage multiplies when the key repeats on both sides: joined to a track_credits table with 40 rows for the hit track (writers, producers, performers), those 12 million plays become 480 million output rows, all produced by task 87. That is the duplicate-key blowup from the joins lesson, concentrated on a single task.
A window partitioned by a key gathers every row of that key into a single task too, because the window function needs all of them in order. The program below numbers each play of a track by time:
collect_list behaves the same way: its result keeps every value, so every value reaches the hot key's task, and no partial total can shrink a list.
plays has 120 million rows and a hit track_id. tracks and track_credits are both far above the broadcast threshold. Which line does the hit track slow the most?
| minutes | busy slots | idle slots |
|---|---|---|
| 0 to 2 | 200 | 0 |
| 2 to 46 | 1 | 199 |
Why more hardware leaves the stage at 46 minutes
| cluster | slots | stage time | slot-minutes paid |
|---|---|---|---|
| 50 executors x 4 cores | 200 | 46 min | 9,200 |
| 100 executors x 4 cores | 400 | 46 min | 18,400 |
| 50 executors x 8 cores | 400 | 46 min | 18,400 |
| 50 executors x 4 cores, balanced keys | 200 | about 2.2 min | about 444 |
- ▸Are most tasks of the slow stage finished while a few still run?
- ▸Did the long tasks read far more rows than the typical task?
- ▸Which key does that stage shuffle by, and how many rows does its biggest value own?
- ▸If the answers point to a hot key, extra hardware raises the bill and leaves the runtime where it is.
- Count rows per key before shuffling a new table by that key
- Compare the slowest task's input rows with a typical task's before tuning
- Broadcast the small side of a join whenever it fits under the threshold
- Treat placeholder values like 0 and 'unknown' as suspects in every key column
- Add executors to speed up a stage that is waiting on a single task
- Read 199 of 200 tasks done as a stage that is almost finished
- Rerun a skew failure and expect the retry to succeed
- Assume a balanced input read stays balanced after a shuffle
To bring the 46-minute join stage under 10 minutes, a teammate proposes moving the job from 50 executors to 150, each with 4 cores. What happens?
> A retailer's holiday clickstream job reads 900 million page views. It joins them to a 4MB page catalog, numbers each visitor's views with a window partitioned by user_id, and totals spend per user. Every logged-out visitor carries user_id = 0, and a price-scraping bot sent 30 million views under a single id. The job ran fine in October and stalls on the holiday weekend.
user_id = 0 placeholder and the bot are the hot keys, and a per-key count run before the holiday would have shown both.user_id sends every view of user 0 to a single task, which becomes the straggler with an oversized input.How a single hot key can stall a 200-task Spark stage, and how to spot it before the job runs.
- Category
- Spark
- Difficulty
- beginner
- Duration
- 12 minutes
- Challenges
- 14 hands-on challenges
Topics covered: What Skew Is, The Straggler Task, Where Hot Keys Come From, Which Operations Skew Hurts, Why Skew Wastes the Cluster
Lesson Sections
- What Skew Is (concepts: Data Skew)
Data skew means the partitions coming out of a shuffle differ wildly in size: most hold a normal share of rows, and a few hold many times more. The cause is the rule a shuffle uses to place rows. Spark hashes the key column, divides the hash by the number of shuffle partitions, and sends the row to the partition named by the remainder. Two rows with the same key always produce the same remainder, so they always land together. When every key owns a similar number of rows, the partitions come out
- The Straggler Task (concepts: Data Skew)
A straggler is a task still running long after the rest of its stage has finished. A stage is the group of tasks that run between 2 shuffles, each doing the same work on a different partition, and skew is the most common way a stage ends up with a straggler. In the plays join, task 87 received the 12,540,000-row partition. The other 199 tasks each read 540,000 rows and finish in about 2 minutes, while task 87 works through 23 times as many rows at the same pace and needs about 46 minutes. These
- Where Hot Keys Come From (concepts: Data Skew)
A key runs hot when it owns far more rows than the table's row count divided by the number of shuffle partitions. For plays, that even share is 120 million divided by 200, or 600,000, and the hit track's 12 million is 20 times it. You can find suspects before any job runs by asking what each value of the key column stands for and how the world produces it. Hot keys come from 4 sources again and again. Popularity: a few values take most of the activity Placeholders: every missing value becomes a
- Which Operations Skew Hurts (concepts: Data Skew)
A hot key does damage only at a step that sends rows to partitions by that key. For any line of code, ask whether the step shuffles by the key, and whether every row of the key travels to the receiving task or only a summary of those rows. The table sorts the common operations by those answers. Untouched: steps with no key shuffle Softened: sums, counts and averages Hit in full: joins, windows and row lists
- Why Skew Wastes the Cluster (concepts: Data Skew)
The plays join runs on 50 executors with 4 cores each, which gives 200 slots. Each of the stage's 200 tasks takes a slot at minute 0. From there, the cluster's time splits like this: Count cost in slot-minutes, 1 slot held for 1 minute. On a fixed-size cluster, which this job runs on, the executors stay allocated for all 46 minutes, so the job pays for 200 slots times 46 minutes, or 9,200 slot-minutes. The work actually done is 199 tasks at 2 minutes plus 1 task at 46, which comes to 444 slot-mi