VAYULearn
Colour theme
Investigate a failure
VAYU Learn

Spark & PySpark

Spark Memory Management — Why Your Jobs Die and How to Stop It

Your Spark Job Failed with OutOfMemoryError. Again. Here Is Exactly What Is Happening and the Specific Configurations That Fix It.

Spark & PySpark
Driver OOM, executor OOM, shuffle spill, and GC pressure look similar from the outside. They are completely different problems underneath.

TL;DR

  • Spark has two memory regions that matter: driver and executor — they fail in different ways for different reasons
  • Exit code 137 means the OS killed your executor — it ran out of physical memory, not JVM heap
  • Shuffle spill to disk is not a crash — it is a silent 10–50× performance penalty that looks like a slow job
  • GC overhead is a symptom of too many small objects in memory — not a memory size problem
  • Most OOM errors are fixed by three configuration changes, not by throwing more nodes at the cluster

The OutOfMemoryError is rarely caused by what you think it is.


The job had been running for six hours. Then: ExecutorLostFailure: Executor 7 exited with exit code 137.
The team added more memory. It ran for seven hours. Then died again.
The problem was not memory size. It was 200 shuffle partitions on a 2 TB dataset. Each partition was 10 GB. No single executor could hold it in execution memory. Everything was spilling to disk.
The fix: set shuffle partitions to 2000. Job ran in 2 hours. No additional memory required.

The Error You’re Seeing

There are four distinct memory failures in Spark. Each has a different cause and a different fix. Treating them as the same problem — and just adding more memory — is why the job keeps dying.

# Failure 1 — Driver heap exhausted
java.lang.OutOfMemoryError: Java heap space
at org.apache.spark.rpc.netty...

# Failure 2 — Executor killed by OS (not JVM)
ExecutorLostFailure: Executor 4 exited with exit code 137
WARN TaskSetManager: Lost task 12.0 in stage 3.0

# Failure 3 — Shuffle spill (not a crash, but devastating)
WARN ExternalSorter: Spilling in-memory map of 1.2 GB to disk
WARN ExternalSorter: Spilling in-memory map of 2.4 GB to disk

# Failure 4 — GC killing throughput
WARN GCTimeoutError: GC overhead limit exceeded
INFO: Total GC time: 22.4s out of 25.1s task time

Identify which one you have before changing anything. The fix for each is different.


How Spark Memory Actually Works

Driver Memory

The driver runs the SparkContext, the DAG scheduler, and the result collection. It does not process data — it coordinates processing.

Driver memory is consumed by:

  • Broadcast variables (sent from driver to all executors)
  • collect() and toPandas() results pulled back from executors
  • DAG metadata — grows with partition count
  • The driver’s own JVM overhead (~300 MB baseline)

Default driver memory: 1 GB. For any job with large broadcast tables or result collection, this is too small.

Executor Memory

Each executor is a JVM process running on a worker node. Spark’s unified memory model divides executor memory into two regions that borrow from each other:

spark.executor.memory = 4g
↓
Reserved memory: 300 MB (always, non-negotiable)
Usable memory: 3.7 GB
↓
spark.memory.fraction = 0.6 (default)
↓
Spark managed: 2.22 GB ← execution + storage share this
User memory: 1.48 GB ← your UDFs, non-Spark objects

Spark managed breakdown:
spark.memory.storageFraction = 0.5 (default)
Execution memory: 1.11 GB ← joins, sorts, aggregations
Storage memory: 1.11 GB ← cached DataFrames, RDDs

Execution and storage memory borrow from each other dynamically. If execution needs more space and storage is holding cached data, Spark evicts cached blocks. If storage needs more and execution is idle, it borrows from execution.

The Unified Memory Model

The most important thing to understand: execution and storage share the same pool. If you cache a large DataFrame and then run a big join, they compete for the same memory. One of them spills to disk.


Failure Zone 1: Driver OOM

java.lang.OutOfMemoryError: Java heap space
at org.apache.spark.rpc.netty.NettyRpcEnvFactory...

What Kills the Driver

collect() on a large dataset. The entire result is pulled to driver memory. On a 50 GB dataset, this requires 50 GB of driver memory. Nobody has that.

Broadcast joins with tables that are too large. The broadcast threshold default is 10 MB. If you raise it to 500 MB and then broadcast a 400 MB table, the driver holds that 400 MB in memory while distributing it to all executors.

Too many partitions. Each partition has metadata tracked by the DAG scheduler on the driver. A job with 500,000 partitions (common after an unoptimized repartition) can accumulate gigabytes of partition metadata on the driver alone.

The Fixes

# Fix 1: increase driver memory
spark = SparkSession.builder \
.config("spark.driver.memory", "8g") \
.config("spark.driver.maxResultSize", "4g") \
.getOrCreate()

# Fix 2: never collect large datasets — sample or write instead
# WRONG
result = df.collect() # pulls everything to driver

# RIGHT
df.write.parquet("s3://bucket/output/")
# or if you genuinely need local data:
sample = df.sample(fraction=0.001).toPandas()

# Fix 3: limit broadcast threshold explicitly
spark.conf.set("spark.sql.autoBroadcastJoinThreshold", 50 * 1024 * 1024) # 50 MB max

# If driver metadata pressure is the issue, the correct fix is
# reducing the partition count at the SOURCE — at read time or
# after a shuffle — not blindly coalescing before a wide operation,
# which can increase partition size and worsen executor pressure.
spark.conf.set("spark.sql.files.maxPartitionBytes", "134217728") # 128 MB

Failure Zone 2: Executor OOM and Exit Code 137

ExecutorLostFailure: Executor 4 exited with exit code 137
WARN TaskSetManager: Lost task 8.0 in stage 2.0 (TID 234)

What Kills the Executor

Exit code 137 means the Linux OOM killer terminated the JVM process. This happens when the executor’s total memory consumption — JVM heap + off-heap + overhead — exceeds the physical memory available on the node.

The key distinction: this is not a JVM heap OOM. The JVM itself would have thrown OutOfMemoryError first. Exit code 137 means the OS intervened because the entire process was consuming too much physical memory.

The most common cause: spark.executor.memory is set, but spark.executor.memoryOverhead is not. Memory overhead covers off-heap usage — Python worker memory for PySpark UDFs, native libraries, JVM internal buffers. Default overhead is max(384 MB, 0.1 × executor.memory). For PySpark jobs with heavy UDF usage, this is almost always insufficient.

The Fixes

# Fix 1: add explicit memory overhead for PySpark jobs
spark = SparkSession.builder \
.config("spark.executor.memory", "8g") \
.config("spark.executor.memoryOverhead", "2g") \ # explicit, not default
.getOrCreate()

# Fix 2: for heavy PySpark UDF usage, increase further
# Rule of thumb: overhead = 20-25% of executor.memory for UDF-heavy jobs
.config("spark.executor.memoryOverhead", "2048") # in MB

# Fix 3: reduce executor memory fraction to leave OS headroom
.config("spark.memory.fraction", "0.6") # default — do not raise this above 0.75

# Fix 4: check if your UDFs are leaking memory
# A UDF that creates large objects without releasing them will grow
# the Python worker process until the OS kills it
# Replace Python UDFs with native Spark SQL functions wherever possible
from pyspark.sql import functions as F

# WRONG — Python UDF, grows off-heap
@udf("double")
def normalize(x):
return float(x) / 1000.0

# RIGHT — native function, no off-heap growth
df.withColumn("normalized", F.col("amount") / 1000.0)

Failure Zone 3: Shuffle Spill

WARN ExternalSorter: Spilling in-memory map of 1.8 GB to disk (iteration 0)
WARN ExternalSorter: Spilling in-memory map of 2.1 GB to disk (iteration 1)

Why Pathological Spill Kills Performance

Spill is not inherently bad. Large joins and aggregations routinely spill some data to disk — that is expected and manageable. The problem is pathological spill: repeated multi-GB spills that saturate local disk and reduce effective throughput by 10–50×.

The difference:

The signal for pathological spill: open the Stages tab in the Spark UI. If “Shuffle Spill (Disk)” is in the tens of GB and stage duration is dominated by disk I/O rather than CPU, your partitions are too large. If spill is a few hundred MB on a large join, leave it alone.

The most common cause: too few shuffle partitions. Default is 200. On a 2 TB dataset with 200 partitions, each partition is 10 GB. No executor can hold 10 GB in its execution memory region. Everything spills.

The Fixes

# Fix 1: right-size shuffle partitions
# Rule of thumb: target 100–200 MB per partition
# 2 TB dataset → 2,000,000 MB / 150 MB = ~13,000 partitions
spark.conf.set("spark.sql.shuffle.partitions", 13000)

# Fix 2: let AQE handle partition sizing automatically (Spark 3.0+)
spark.conf.set("spark.sql.adaptive.enabled", "true")
spark.conf.set("spark.sql.adaptive.coalescePartitions.enabled", "true")
spark.conf.set("spark.sql.adaptive.coalescePartitions.minPartitionSize", "64mb")
spark.conf.set("spark.sql.adaptive.skewJoin.enabled", "true")

# AQE does three things that matter for memory:
# 1. Coalesces small post-shuffle partitions (avoids thousands of tiny tasks)
# 2. Splits skewed partitions that would OOM a single executor
# 3. Converts SortMergeJoin → BroadcastHashJoin at runtime when one side
# shrinks after filtering — eliminating the shuffle entirely
#
# AQE cannot help if partitions are too LARGE going into a shuffle.
# For that, set spark.sql.shuffle.partitions manually first,
# then let AQE coalesce the result.

# Fix 3: increase execution memory fraction for shuffle-heavy jobs
# (reduces storage memory, evicts cache — only do this if you're not caching)
spark.conf.set("spark.memory.storageFraction", "0.2") # was 0.5
# Now execution gets 80% of managed memory instead of 50%

# Fix 4: detect spill before it kills your job
# Check Spark UI → Stages → Shuffle Spill (Memory) and Shuffle Spill (Disk)
# Any non-zero value in Shuffle Spill (Disk) means you are spilling

The fastest way to confirm spill: open the Spark UI, go to the Stages tab, and look at the “Shuffle Spill (Disk)” column. If it shows anything other than 0, your job is spilling.


Failure Zone 4: GC Overhead

WARN GCTimeoutError: GC overhead limit exceeded
INFO BlockManager: Found block rdd_123_0 locally
INFO: Total GC time: 18.7s out of 20.1s task time (93%)

How to Diagnose GC Pressure

GC overhead means the JVM is spending more time collecting garbage than executing your job.

GC overhead is often an object allocation or heap pressure problem rather than simply insufficient memory — though a heap that is genuinely too small will also produce constant full GCs. Check object allocation patterns first before increasing heap size.

The most common causes in Spark:

  • Python UDFs creating many small Python objects that cross the JVM-Python boundary repeatedly
  • UDFs or transformations building large collections (lists, dicts) per row
  • Collecting too many small DataFrames into the driver and then processing them iteratively

The signal: look at the Executors tab in the Spark UI. If “GC Time” is more than 10% of “Task Time”, you have a GC problem.

The Fixes

# Fix 1: switch to G1GC with appropriate settings
# Add to spark-submit or SparkConf:
.config("spark.executor.extraJavaOptions",
"-XX:+UseG1GC "
"-XX:G1HeapRegionSize=16m "
"-XX:+G1SummarizeRSetStats "
"-XX:MaxGCPauseMillis=200")

# Fix 2: prefer native Spark SQL functions first
# If custom logic is unavoidable, Pandas UDFs are often better than
# row-at-a-time Python UDFs — but they are not free.
# Pandas UDFs require Arrow, batch in memory, and can increase
# memory pressure on large datasets. Use them when native functions
# genuinely cannot express the logic.

from pyspark.sql.functions import pandas_udf
import pandas as pd

# WRONG — row-at-a-time, one JVM-Python round trip per row
@udf("double")
def process(x):
return complex_calculation(x)

# BETTER — vectorized, Arrow-serialized batches
# Still has overhead — prefer native F.col() expressions above this
@pandas_udf("double")
def process(series: pd.Series) -> pd.Series:
return series.apply(complex_calculation)

# BEST — no Python boundary at all
df.withColumn("result", F.col("amount") * F.lit(0.95))

# The priority order:
# native Spark SQL functions → Pandas UDFs → Python UDFs
# Never reach for a Python UDF if a native expression exists

# Fix 3: reduce executor cores to reduce concurrent thread pressure on GC
.config("spark.executor.cores", "4") # instead of 8
# Fewer cores per executor = less concurrent object creation = less GC pressure
# Trade: more executors needed, but GC becomes manageable

# Fix 4: increase off-heap memory for Tungsten operations
.config("spark.memory.offHeap.enabled", "true")
.config("spark.memory.offHeap.size", "2g")
# Moves some Spark-internal data structures off the JVM heap
# Reduces the amount of memory the GC has to manage

The spark-submit Configuration That Actually Matters

Most Spark memory problems are fixed by getting these seven settings right. Not by adding nodes.

spark-submit \
--driver-memory 8g \
--driver-java-options "-XX:+UseG1GC -XX:MaxGCPauseMillis=200" \
\
--executor-memory 16g \
--executor-cores 4 \
--num-executors 20 \
\
--conf spark.executor.memoryOverhead=3g \
--conf spark.memory.fraction=0.6 \
--conf spark.memory.storageFraction=0.4 \
\
--conf spark.sql.shuffle.partitions=2000 \
--conf spark.sql.adaptive.enabled=true \
--conf spark.sql.adaptive.coalescePartitions.enabled=true \
\
--conf spark.driver.maxResultSize=4g \
--conf spark.sql.autoBroadcastJoinThreshold=52428800 \
\
--conf spark.executor.extraJavaOptions="-XX:+UseG1GC -XX:G1HeapRegionSize=16m" \
your_job.py

Work through these in order when debugging:


How to Read the Spark UI for Memory Problems

The Spark UI tells you exactly where memory is failing. Most engineers don’t know which tab to look at.

Executors tab → look at “GC Time” column. If any executor shows GC Time > 10% of Task Time, you have GC pressure.

Stages tab → look at “Shuffle Spill (Disk)”. Any non-zero value means spill is happening. The “Shuffle Read” and “Shuffle Write” columns tell you how much data is crossing the network per stage — large values here mean partition count is likely too low.

Storage tab → look at “Fraction Cached” and “Size in Memory vs Size on Disk”. If you see data in the “Size on Disk” column for cached DataFrames, your storage memory region is too small for the data you’re caching.

Jobs tab → look at the timeline. If you see long gaps between stages, the driver is struggling with DAG planning or result collection. This points to a driver memory problem, not an executor problem.


The Five Memory Mistakes Engineers Repeat

These are not edge cases. They appear in production Spark jobs constantly — including at teams that have been running Spark for years.

1. collect() in production code

Someone added it for debugging. It stayed. The DataFrame was small during development. It’s 40 GB in production. The driver dies every Tuesday at 2 AM.

python

# Find it and kill it
result = df.collect() # danger
result = df.toPandas() # also danger at scale

# Replace with
df.write.parquet("s3://output/") # write and read downstream
sample = df.limit(1000).toPandas() # if you genuinely need local data

2. Caching everything

Someone read that caching speeds up Spark. They cached every intermediate DataFrame. Now the storage memory region is exhausted, execution memory has nothing to borrow from, and every join spills.

Cache only DataFrames that are reused more than once in the same job. Unpersist them when done. An uncached DataFrame that is read twice from Parquet is often faster than a cached DataFrame that evicts execution memory.

python

# Cache with intention, release with discipline
df_features = compute_expensive_features(df).cache()
df_features.count() # materialize immediately

result_a = df_features.join(dim_a, "id")
result_b = df_features.join(dim_b, "id")

df_features.unpersist() # release — do not leave this to GC

3. Oversized executors

Bigger executors feel more efficient. In practice, a single executor with 64 GB and 16 cores creates GC pressure because all 16 threads compete for the same heap. The JVM spends more time collecting garbage than executing tasks.

The sweet spot for most workloads: 4–5 cores per executor, 16–32 GB memory. More executors, smaller each.

4. Default shuffle partitions on large data

spark.sql.shuffle.partitions = 200 is the default. On datasets over 100 GB, this produces partitions that are too large to fit in execution memory. Pathological spill follows.

Set this explicitly for every job. Target 100–200 MB per post-shuffle partition. Let AQE coalesce the small ones.

5. Ignoring spark.executor.memoryOverhead for PySpark jobs

The default overhead is max(384 MB, 10% of executor memory). For PySpark jobs running UDFs, the Python worker process lives outside the JVM heap and consumes memory from this overhead budget. When the budget is exhausted, the OS kills the executor.

Exit code 137 on PySpark jobs is very often caused by insufficient memoryOverhead — but it can also come from native libraries, Arrow serialization, container memory limits, or off-heap pressure from Tungsten. Start by raising memoryOverhead to 20–25% of executor memory. If the job still dies, check container limits and off-heap configuration next.


🚀 Final Takeaway

Spark memory failures are not random. Each failure mode has a specific cause and a specific fix.

Exit code 137 → add memoryOverhead, check PySpark UDF memory leaks. Shuffle spill → increase shuffle partitions, enable AQE. Driver OOM → never collect large datasets, limit broadcast threshold. GC overhead → switch to G1GC, replace Python UDFs with Pandas UDFs.

Add nodes last. Fix the configuration first.

📌 Core Principle

The OutOfMemoryError is telling you
what failed — not why it failed.
Read the error type, find the zone,
apply the specific fix.
Adding memory to the wrong region
solves nothing.

🔥 Next in Series

⚡Partitioning Strategy for Spark — The Decision That Determines Everything

Wrong partitioning is the root cause of most Spark performance problems.

Next: how to choose partition count with a real formula, when to use repartition vs coalesce, how to detect and fix partition skew — and why getting this wrong at the start of a job compounds into every stage that follows.


🔔 Follow for More

Follow TheDataForge for high-signal deep dives on Spark, Kafka, Streaming, Lakehouse, and real-world data engineering — no fluff, only engineering truth.

⚡️Let’s connect — I post daily Big Data & Spark insights at DataForgeX on X.

💬 Comment Below

What was the Spark memory failure that took you the longest to diagnose?

Exit code 137 that turned out to be PySpark overhead? Shuffle spill that looked like a slow job for three weeks before anyone checked the Stages tab? A driver OOM from a collect() that someone added "just for debugging"?

👇 Real failures. The more specific the better.


🏷️ Tags

#apache-spark #pyspark #data-engineering #big-data #performance-engineering #production-engineering #distributed-systems #cloud-infrastructure #software-engineering #python