Zero Labs
Industry News / AI

Part VII - Data Skew in Spark — Why 199 Tasks Finish in 40 Seconds and One Runs for 3 Hours

Source · Towards AI By chakshu_salgotra

From the publisher’s feed, collected in the ZeroLabs newsroom.

Every production skew strategy that actually works — AQE skew handling, salting, hot-key isolation, broadcast escape hatches — and the exact rules for choosing between them.Part I | Part II | Part III | Part IV | Part V | Part VI | Part VIIThe Stage That Was 99.5% Done for Three HoursA customer-events join ran every night: 4.2TB of clickstream events joined against a 900GB orders table on customer_id, 200 shuffle partitions. The Spark UI told a story every data engineer eventually learns to dread:199 tasks completed in ~40 seconds each, shuffle read ~180MB per task.1 task ran for 3 hours 12 minutes, shuffle read 312GB — then died with ExecutorLostFailure after spilling 1.1TB to disk.The job was, by every dashboard metric, “99.5% complete” the entire night. The on-call engineer bumped executor memory twice, doubled spark.sql.shuffle.partitions to 400, and got the exact same shape: 399 fast tasks, one monster. The reason was in the data, not the config: 31% of all events carried the same customer_id — a synthetic ID that an upstream mobile SDK assigned to logged-out users. One key, one hash, one partition, one task, one executor. No amount of memory or partition count fixes that, because a single key can never be split by a hash partitioner — every row with that key must land in the same partition.That’s data skew: a workload distribution problem masquerading as a resource problem. Teams routinely burn weeks throwing hardware at it because the failure looks like an OOM.So: how do you detect skew before it detonates, and which of the five production remediation strategies — AQE skew join, salting, hot-key isolation, broadcast conversion, null/default-key filtering — do you reach for, in what order, and why?Why Skew Happens: The Hash Partitioner Has No Opinion About Your DataEvery wide transformation — groupBy, join, distinct, repartition(col) — routes rows to reduce partitions with a HashPartitioner:partition_id = hash(key) % numPartitionsThis is deterministic and key-blind. It balances keys across partitions, not rows. If your keys follow a Zipfian distribution — and in production they almost always do (power users, null defaults, “UNKNOWN” placeholders, single-tenant hot spots) — the partition receiving the hot key receives all of its rows.The three consequences that actually page you:Straggler tasks. Stage time = slowest task time. One 312GB partition holds 199 idle cores hostage. Cluster utilization craters while wall-clock time explodes.Execution-memory pressure and spill. The task processing the hot partition needs its hash map / sort buffer to hold everything for that key. It exhausts its execution memory share, spills to disk (Part V covered why), and every spill round-trip adds serialization + disk I/O.Executor death, then a lie of a retry. The container gets killed by YARN/Kubernetes for exceeding memory. Spark retries the task — on the same data — so the retry hits the identical wall. Four retries later, the whole stage fails, three hours in.Key insight: increasing spark.sql.shuffle.partitions spreads the other keys thinner but does nothing for the hot key. hash(hot_key) % 400 is still one number.Detecting Skew: Read the Distribution, Not the AverageSkew hides from averages. A stage with mean task duration of 65s looks healthy while its max is 11,520s. Look at the distribution:Spark UI → Stage detail → Summary Metrics. Compare the max row against the 75th percentile for Duration and Shuffle Read Size. A max more than ~5–10x the median is skew, full stop.Event timeline. The lone green bar stretching across the timeline while everything else finished long ago.Interrogate the keys directly before you ship the pipeline:-- Find keys that dominate the distributionSELECT customer_id, COUNT(*) AS cnt, COUNT(*) * 100.0 / SUM(COUNT(*)) OVER () AS pct_of_totalFROM eventsGROUP BY customer_idORDER BY cnt DESCLIMIT 20;If the top key holds more than a few percent of the table, every join and aggregation on that column inherits the problem. Make this query part of data-contract validation for high-cardinality join keys — skew that’s caught in CI never pages anyone.Strategy 1: Let AQE Split the Skewed Partition (Try This First)Since Spark 3.0, Adaptive Query Execution can repair join skew at runtime with zero code changes. After each shuffle map stage, AQE has actual partition sizes — not estimates — and its skew join optimization (OptimizeSkewedJoin) rewrites the physical plan mid-flight.The mechanics matter, because the defaults bite:A partition is flagged as skewed only if both conditions hold:it is larger than spark.sql.adaptive.skewJoin.skewedPartitionFactor (default 5.0) × the median partition size, andit exceeds spark.sql.adaptive.skewJoin.skewedPartitionThresholdInBytes (default 256MB).AQE then splits that partition into chunks of roughly spark.sql.adaptive.advisoryPartitionSizeInBytes (default 64MB) and duplicates the matching partition on the other side of the join for each chunk. N chunks × 1 duplicated partition = N parallel tasks instead of one monster.# Naive: hope 200 partitions are enough. Optimized: let runtime stats decide.spark.conf.set("spark.sql.adaptive.enabled", "true")spark.conf.set("spark.sql.adaptive.skewJoin.enabled", "true")# Our 312GB partition vs ~180MB median: defaults would catch it,# but tighten the factor if your skew is subtler than 5x medianspark.conf.set("spark.sql.adaptive.skewJoin.skewedPartitionFactor", "3")spark.conf.set("spark.sql.adaptive.advisoryPartitionSizeInBytes", "128m")Result on the opening job: the 312GB partition became ~2,400 chunks executed in parallel across the cluster. Stage time dropped from failed after 3h+ to 11 minutes, no code change.Where AQE skew handling does NOT save you — and this is the part most posts skip:Aggregations. OptimizeSkewedJoin applies to sort-merge and shuffle-hash joins. A skewed groupBy().agg() still funnels the hot key into one task (partial aggregation helps only when the key-group compresses well).Joins followed by a required distribution. If the skewed join’s output must be co-partitioned for a downstream operation, AQE may skip the split rather than introduce an extra shuffle.Extreme single-key skew inside one task’s processing — splitting a partition doesn’t help operations that must see all rows of a key together, like a window over the hot key.For those, you intervene in the data itself.Strategy 2: Salting — Manufacture the Cardinality the Partitioner NeedsSalting breaks one hot key into N synthetic keys so the hash partitioner can distribute it. The cost: the other side of the join must be exploded N-fold so every salted variant still finds its match.from pyspark.sql import functions as FSALT_BUCKETS = 8# Fact side: assign each row a random salt bucketevents_salted = events.withColumn( "salt", (F.rand() * SALT_BUCKETS).cast("int"))# Dimension side: explode — replicate every row once per bucketorders_salted = orders.withColumn( "salt", F.explode(F.array([F.lit(i) for i in range(SALT_BUCKETS)])))# Naive: events.join(orders, "customer_id") -> one 312GB partition# Optimized: composite key spreads the hot key across 8 partitionsjoined = events_salted.join(orders_salted, ["customer_id", "salt"])Rules for using it well:Salt aggregations in two phases instead of exploding anything: aggregate on (key, salt) first, then re-aggregate on key. The second pass sees at most N pre-aggregated rows per key — this is the standard fix for skewed groupBy, which AQE won't touch.Size N to the skew, not to taste. N=8 turns a 312GB partition into ~39GB chunks — still too big. N should bring hot_key_bytes / N under your advisory partition size. Here, N≈50 would.Count the replication cost. The dimension side grows N-fold in shuffle volume. Salting a 900GB table 50x is a 45TB shuffle — which is why you never salt the whole table (next strategy).Strategy 3: Hot-Key Isolation — Surgical SaltingSalting everything punishes the 99% of keys that were fine. The production-grade refinement: split the DataFrame into a skewed slice and a healthy slice, treat them differently, union the results.# Hot keys identified by the detection query (or a daily profiling job)hot_keys = ["cust_42"] # in practice: driven by config/metadata, not literalsevents_hot = events.filter(F.col("customer_id").isin(hot_keys))events_rest = events.filter(~F.col("customer_id").isin(hot_keys))orders_hot = orders.filter(F.col("customer_id").isin(hot_keys))# Hot slice: orders side for ONE key is tiny -> broadcast, zero shufflejoined_hot = events_hot.join(F.broadcast(orders_hot), "customer_id")# Healthy slice: normal sort-merge join, no salt overheadjoined_rest = events_rest.join(orders, "customer_id")result = joined_hot.unionByName(joined_rest)This is usually the best-performing manual fix, because the hot key rarely needs a shuffle at all — the matching dimension rows for one key are almost always broadcastable. The trade-off is operational: you now own a hot-key list. Automate its generation (profile yesterday’s partition, write hot keys to a control table) or it will silently go stale as the data drifts.Strategy 4: Remove the Join’s Shuffle Entirely — BroadcastSkew is a shuffle pathology. If the dimension side fits in memory, a broadcast hash join ships the small table to every executor and the fact side never shuffles — the hot key gets processed in place, spread across whatever partitions it already occupies.# Naive: sort-merge join shuffles 4.2TB by customer_id -> skew detonates# Optimized: broadcast kills the shuffle; skew becomes irrelevantjoined = events.join(F.broadcast(orders_slim), "customer_id")Two caveats from Part VI still apply: the broadcast side must genuinely fit (driver collect + per-executor hash map), and estimated size — not file size — drives the automatic decision. Slim the dimension table (select only needed columns) before broadcasting; a 900GB table with 60 columns is often a 4GB table with the 3 columns the join actually needs.Strategy 5: The Skew Nobody Should Be Paying For — Null and Default KeysThe most common hot key in production isn’t a power user. It’s NULL, "", -1, or "UNKNOWN" — placeholder keys that will never match anything in the join anyway. In the opening story, the hot key was a synthetic logged-out-user ID whose join output was discarded downstream.Don’t engineer around rows you don’t need — remove or short-circuit them:# Rows with unmatched placeholder keys: skip the join, don't shuffle themevents_joinable = events.filter(F.col("customer_id").isNotNull())events_orphan = events.filter(F.col("customer_id").isNull())joined = events_joinable.join(orders, "customer_id", "left")# For an inner join, orphans are simply dropped.# For a left join, union them back with null order columns — no shuffle needed.For a left join where you must keep the rows, an equivalent trick is replacing null keys with a random value (concat(lit("null_"), rand())) so they distribute evenly and match nothing. Either way, the 31% hot partition disappears because it should never have existed.The Decision OrderPlaceholder/null key? Filter or randomize it. Fix the data before the engine. (Minutes of work, often eliminates the problem.)Skewed join, Spark 3.x? Enable AQE skew join, tune factor/advisory size. Zero code, handles drift automatically.Dimension side slimmable to memory? Broadcast. The shuffle — and the skew — vanish.Skewed aggregation, or AQE declined to split? Two-phase salted aggregation, or salt the join with N sized to the skew.A few known, stable hot keys? Hot-key isolation with a broadcast hot path — fastest, but you own the key list.The opening job shipped with three of these: null-key filtering (the SDK’s synthetic ID was 31% of events and joined to nothing), AQE skew join as the safety net, and a slimmed broadcast dimension. Nightly runtime went from failing after 3+ hours to 9 minutes, on the original executor memory.Skew is never a memory problem. It’s a distribution problem — and the fix is always to change the distribution, not the container size.If this saved you a 3 AM pager incident, follow me on Medium for Twice a week for the next 3 Months of Advanced Data Engineering & AI. Let’s connect on LinkedIn and X.Part VII - Data Skew in Spark — Why 199 Tasks Finish in 40 Seconds and One Runs for 3 Hours was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.