Skip to main content
← PROBLEMS / DATA-ENGINEERING
An end-to-end domain learning journey

Diagnose & Fix Spark Shuffle
Skew and Executor OOMs.

When a 4 TB Spark join stalls on task 142 (90 GB spill, Exit Code 137 OOM) due to null/default user_id skew, isolating nulls, enabling AQE skewJoin, and applying 16-way key salting finishes the job within the 20-minute SLA.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When a 4 TB Spark join stalls on task 142 (90 GB spill, Exit Code 137 OOM) due to null/default user_id skew, isolat, filter or salt skewed/null join keys across K buckets (and replicate the non-skewed side K times) alongside Spark 3 AQE skewJoin so no single executor spills 90 GB and OOMs.

TL;DR30-second simplified summary
▾

Core Mechanics: In a 4 TB nightly clickstream join against an 80 GB account profile table (too large for broadcast), 199 of 200 shuffle tasks finish in 40 s, while task 142 spills 90 GB to disk and dies with Exit Code 137 (OOM).

Visual & Structural Flow: Depicts Task 142 90GB OOM vs. Null Isolation + 16-Way Salted Shuffle (4TB Clickstream -> Shuffle Hash -> Executor 142 -> 16 Executors); Null Filter + 16-Bucket Salted Events x Exploded Profiles (4TB Events -> 80GB Profiles -> AQE Shuffle -> Balanced Tasks).

Trade-Offs & Production: Raising spark.executor.memory from 16 GB to 64 GB or bumping spark.sql.shuffle.partitions to 2,000 does not fix key skew: All Identical Keys Still Hash Together. Production Spark pipelines resolve skew in three layers:

Failure Modes & Application: Key salting and AQE skew mitigation are essential across large-scale batch and streaming pipelines: Clickstream & Ad Attribution Joins: Joining billions of anonymous/logged-out events against user profiles.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Spark Shuffle, Partitioning & AQE
Spark shuffles redistribute records across executors over the network whenever wide transformations (join, groupBy, repartition) cross partition boundaries. Mastering partitioning, Broadcast Hash Joins, executor memory sizing, and Adaptive Query Execution (AQE...
Apache Spark Data Engineering
Apache Spark processes petabyte-scale batch and streaming data across distributed clusters using lazy DAG execution, the Catalyst query optimizer, Tungsten off-heap memory, and Adaptive Query Execution (AQE) over columnar formats like Parquet, Delta Lake, and...
Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

Why Spark shuffle skew causes Exit Code 137 OOMs.

Why this matters: The mechanism: understand how Why Spark shuffle skew causes Exit Code 137 OOMs works from first principles.

Think of Why Spark shuffle skew causes Exit Code 137 OOMs as the intuition layer for Diagnose & Fix Spark Shuffle Skew and Executor OOMs: The mechanism: understand how Why Spark shuffle skew causes Exit Code 137 OOMs works from first principles.

In a 4 TB nightly clickstream join against an 80 GB account profile table (too large for broadcast), 199 of 200 shuffle tasks finish in 40 s, while task 142 spills 90 GB to disk and dies with Exit Code 137 (OOM). Because Spark hashes user_id (hash(key) % 200), millions of NULL, -1, or bot user_id rows all route to one partition—exceeding the 16 GB heap + 3 GB off-heap container limit.

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

What happens when one partition holds 90 GB of skewed keys.

Why this matters: The problem: see what breaks without What happens when one partition holds 90 GB of skewed keys under real concurrency or scale.

Extreme partition skew breaks Spark's execution model in three ways:

  1. Straggler Barrier: Stage 4 cannot complete until task 142 finishes, idling 199 cores.
  2. Disk Spill Thrashing: UnsafeExternalSorter spills 90 GB to local NVMe, saturating disk I/O.
  3. Container OOMKill (137): Off-heap/Tungsten memory overhead breaches Kubernetes/YARN cgroup limits, killing the executor and triggering 4× task retries.
Skewed Shuffle vs. Salted Join

Task 142 90GB OOM vs. Null Isolation + 16-Way Salted Shuffle

4TB ClickstreamShuffle HashExecutor 14216 Executors1. Naive: hash(null / bot_id) ->part 1422. 90GB spill -> Exit Code 137OOM!3. Fix: filter nulls + salt hotkey (0..15)4. 5.6GB/task balanced + AQE -><20m SLA

Isolating null keys and salting hot keys across 16 buckets eliminates the 90 GB single-task spill.

Engineering Decision Framework
Problem
How to implement Diagnose & Fix Spark Shuffle Skew and Executor OOMs without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
When a 4 TB Spark join stalls on task 142 (90 GB spill, Exit Code 137 OOM) due to null/default user_id skew, isolat, filter or salt skewed/null join keys across K buckets (and replicate the non-skewed side K times) alongside Spark 3 AQE skewJoin so no single executor spills 90 GB and OOMs.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Diagnose & Fix Spark Shuffle Skew and Executor OOMs experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

Naive solution (and why bumping executor memory fails).

Why this matters: The problem: see what breaks without Naive solution under real concurrency or scale.

Raising spark.executor.memory from 16 GB to 64 GB or bumping spark.sql.shuffle.partitions to 2,000 does not fix key skew:

  • All Identical Keys Still Hash Together: Even with 10,000 partitions, every user_id = NULL row hashes to the exact same partition.
  • Wasted Cluster RAM: Over-provisioning 64 GB executors for 199 tiny tasks wastes cluster capacity.
Request & State Flow

Naive solution (and why bumping executor memory fails)

CallerService EntryCore ProcessorState Store1. Submit bounded request2. Apply domain invariant3. Persist or read state4. Return verified response
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

Enterprise solution: Null Isolation + AQE SkewJoin + 16-Way Key Salting.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

Production Spark pipelines resolve skew in three layers:

  • 1. Isolate Null/Default Keys: Filter user_id IS NOT NULL AND user_id != -1 before the join (and union unjoined nulls back afterward).
  • 2. Enable Spark 3 AQE: Set spark.sql.adaptive.enabled=true and spark.sql.adaptive.skewJoin.enabled=true so Spark automatically splits skewed shuffle partitions.
  • 3. Explicit 16-Way Key Salting (for non-null whale keys): Append salt = floor(rand() * 16) to events and explode profiles (array(0..15)) on the join key—spreading the 90 GB task evenly across 16 tasks (~5.6 GB each) within the 16 GB heap + 3 GB overhead budget.
Salted Distributed Join

Null Filter + 16-Bucket Salted Events x Exploded Profiles

4TB Events+ salt in 0..1580GB Profilesexplode(0..15) hotAQE ShuffleSplits skewed partsBalanced Tasks<16GB heap, <20m

1.Null Isolation: Skips shuffling millions of unjoinable NULL/-1 rows entirely.

2.AQE SkewJoin: Dynamically splits partitions exceeding skewedPartitionThresholdInBytes.

3.16-Way Salting: Turns 1x 90 GB task into 16x 5.6 GB parallel tasks.

4.Memory Budget: Stays safely inside 16 GB heap + 3 GB off-heap with zero Exit 137.

Combining null filtering, AQE skewJoin, and 16-way salting completes the 4 TB join comfortably inside the 20-minute SLA.

from pyspark.sql.functions import col, concat, lit, floor, rand

# Salt hot/null keys across 16 buckets when AQE alone isn't enough
salted_events = events.withColumn('salt', (rand() * 16).cast('int'))
exploded_profiles = profiles.crossJoin(spark.range(16).withColumnRenamed('id', 'salt'))
joined = salted_events.join(exploded_profiles, ['user_id', 'salt'])
Dataset<Row> salted = events.withColumn("salt", functions.floor(functions.rand().multiply(16)));
Dataset<Row> exploded = profiles.crossJoin(spark.range(16).withColumnRenamed("id", "salt"));
Dataset<Row> joined = salted.join(exploded, JavaConverters.asScalaBuffer(Arrays.asList("user_id", "salt")).toSeq());
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

Where Skew & Shuffle Optimization applies in Data Engineering.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Key salting and AQE skew mitigation are essential across large-scale batch and streaming pipelines:

  • Clickstream & Ad Attribution Joins: Joining billions of anonymous/logged-out events against user profiles.
  • E-Commerce Whale Merchant Aggregations: Computing daily rollups when 1% of merchants generate 70% of orders.
  • Graph & ML Feature Pipelines: Preventing straggler OOMs in PySpark/Iceberg feature joins.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why does increasing spark.sql.shuffle.partitions from 200 to 2,000 fail to fix a 90 GB spill caused by user_id = NULL skew?

Recommended Learning Flow