DataEng Hub
PySparkadvancedArticle · 10 min read

Spark Memory Management: Executors, Spills and OOM Fixes

How executor and driver memory is actually divided, why tasks spill, and how to diagnose and fix each kind of out-of-memory error instead of just adding RAM.

Balaji S.
Lead Data Engineer

TL;DR

  • An executor's memory is heap (300 MB reserved, ~40% user memory, ~60% unified memory) plus overhead outside the heap. Python workers live in the overhead.
  • Unified memory is shared by execution (joins, sorts, aggregations) and storage (cache). Execution can evict cached blocks; storage can't evict execution.
  • Running tasks split execution memory. With 4 cores, each task gets roughly a quarter. That's the number that matters, not the executor's total.
  • Spill is Spark coping with too little memory per task. OOM is when it can't cope. Both usually point to an oversized partition, not a small cluster.
  • Three different OOMs, three different fixes: driver (stop pulling data to it), executor heap (smaller partitions, fix skew), container killed (overhead: Python, Arrow, native memory).

The problem

NorthBridge's basket-analysis job failed every Monday with:

org.apache.spark.SparkException: Job aborted due to stage failure:
Task 412 in stage 9.0 failed 4 times ... ExecutorLostFailure (executor 7 exited caused by
one of the running tasks) Reason: Command exited with code 137

The first fix was a bigger instance type. It worked for two weeks, then failed again. The second was an even bigger instance type. Cost was up 3×.

The real cause was a collect_list over each customer's basket: one loyalty account used by a franchise store had 14 million line items. One task tried to build a 14-million-element array in memory. No reasonable machine would hold it, and Monday's load (the weekend) made it just big enough to fail.

Key concepts

Concept What it means Why it matters here
Executor A JVM process on a worker running tasks in parallel, one per core Its memory is shared by all its running tasks
Heap JVM memory, spark.executor.memory Where Spark's data structures live
Unified memory spark.memory.fraction (0.6) × (heap − 300 MB) Shared by execution and storage
Execution memory Buffers for shuffles, joins, sorts, aggregations Too little → spill
Storage memory Cached and broadcast data Can be evicted to make room for execution
Memory overhead Off-heap allowance per executor, default max(384 MB, 10% of heap) Python workers, native buffers, JVM internals
Spill Writing intermediate data to local disk when execution memory runs out Slow but survivable

Executor memory layout with reserved, user, storage and execution memory and overhead, plus three OOM types The executor's total doesn't matter much. Memory per running task does.

How executor memory is divided

Take an executor with spark.executor.memory = 16g and 4 cores, default settings:

Region Size Used for
Reserved 300 MB Spark internals
User memory (16 GB − 300 MB) × 0.4 ≈ 6.3 GB Your objects, UDF data structures, metadata
Unified memory (16 GB − 300 MB) × 0.6 ≈ 9.4 GB Execution + storage
↳ storage, protected 9.4 GB × spark.memory.storageFraction (0.5) ≈ 4.7 GB Cache that execution can't evict
↳ execution the rest, plus anything storage isn't using Shuffle, join, sort, aggregation buffers
Overhead (outside heap) max(384 MB, 10% × 16 GB) = 1.6 GB Python workers, Netty buffers, JVM overhead

The boundary between storage and execution is soft:

  • Execution can borrow free storage memory, and can evict cached blocks above the protected 50%.
  • Storage can borrow free execution memory, but can't evict execution; if execution needs it back, cached blocks are dropped.

So caching a big DataFrame doesn't usually cause OOM. It causes cache eviction and recomputation, which is slower but quieter.

Memory per task is what counts

Execution memory is shared among the tasks running on the executor. With N active tasks, each task can get between 1/(2N) and 1/N of the execution pool. With 4 cores and ~9.4 GB unified memory (most of it available to execution when nothing is cached), each task has roughly 1.2–2.4 GB.

That's what a single partition's join or sort has to fit into before it spills. Implications:

  • A 6 GB skewed partition will spill no matter how many nodes you add.
  • More cores per executor at the same memory means less memory per task.
  • More, smaller partitions reduce memory per task needed.

On Databricks classic compute, each worker runs one executor sized from the instance type, so the levers are instance type (memory per core), partition size and skew, not spark.executor.memory.

Spill: the warning light

When a task's sort, aggregation or join buffer outgrows its share, Spark sorts what it has, writes it to local disk, and continues. At the end it merges the spill files. It works, but disk I/O is far slower than memory.

In the Spark UI's stage summary:

  • Spill (Memory): the deserialized size of the data that was spilled.
  • Spill (Disk): the same data serialized and compressed on disk. Always smaller.
Pattern Meaning Fix
Spill on the max task only Skew Fix the key: Data Skew in Spark
Spill on most tasks Partitions too big for memory per task More shuffle partitions, smaller AQE advisory size, more memory per core
Spill during a broadcast join Unlikely; check for a hash aggregation after it Read which operator reports spill in the SQL tab

The three OOMs

1. Driver OOM

What you see: java.lang.OutOfMemoryError in the driver log; on Databricks, "The spark driver has stopped unexpectedly and is restarting"; or:

Total size of serialized results of 312 tasks (1024.3 MiB) is bigger than
spark.driver.maxResultSize (1024.0 MiB)

Causes:

  • collect(), toPandas(), take(10_000_000), or display() of something huge
  • Broadcasting a table that's much bigger in memory than on disk (the driver builds the broadcast)
  • Planning over millions of files or a plan with thousands of columns/operations
  • Lots of Python code holding data on the driver

Fixes:

# Instead of pulling 200M rows to pandas for a summary...
pdf = sales.toPandas()                                     # driver OOM
summary = pdf.groupby("store_id")["net_amount"].sum()
 
# ...aggregate in Spark, then collect the small result
summary = (sales.groupBy("store_id").agg(F.sum("net_amount").alias("net"))
                .toPandas())                               # 2,400 rows

Write big results to a table instead of collecting them. Don't hard-code broadcasts for tables that grow (see join strategies). Raise spark.driver.maxResultSize or driver size only after confirming you really need that much data on the driver.

2. Executor heap OOM

What you see: java.lang.OutOfMemoryError: Java heap space, GC overhead limit exceeded, or SparkOutOfMemoryError: Unable to acquire ... bytes of memory in a task's error, often preceded by heavy spill and GC.

Causes:

  • One partition far bigger than the rest (skew)
  • Operations that build big per-row or per-group objects in memory: collect_list, collect_set, explode of large arrays, huge strings or JSON blobs, wide pivot
  • Too many cores sharing too little heap
  • Large Python objects captured in closures (broadcast variables of big dicts)

Fixes, in order:

  1. Find the biggest task. Stage summary → max shuffle read. If it's skew, fix the skew.
  2. Make partitions smaller. More shuffle partitions, spark.sql.adaptive.advisoryPartitionSizeInBytes down to 32–64 MB, spark.sql.files.maxPartitionBytes down for wide input rows.
  3. Rethink in-memory structures. For NorthBridge's baskets:
# Before: one array per customer; one customer had 14M items
baskets = lines.groupBy("loyalty_id").agg(F.collect_list("sku").alias("skus"))
 
# After: baskets are per transaction, not per customer, and capped
baskets = (lines.groupBy("loyalty_id", "transaction_id")
                .agg(F.slice(F.collect_set("sku"), 1, 500).alias("skus")))
  1. More memory per core: memory-optimized instances, or fewer cores per executor on platforms that let you set it.

3. Container killed (exit code 137 / overhead exceeded)

What you see: ExecutorLostFailure ... exited caused by one of the running tasks ... exit code 137, or on YARN, "Container killed by YARN for exceeding memory limits. Consider boosting spark.executor.memoryOverhead". The JVM heap was fine; the process used more than the container allows.

Causes:

  • Python workers. Python UDFs, pandas UDFs, applyInPandas and mapInPandas run in separate Python processes that count against overhead, not the heap.
  • Large Arrow batches moving between the JVM and Python
  • applyInPandas with one huge group (the whole group is loaded into one pandas DataFrame)
  • Native libraries or off-heap buffers

Fixes:

# Smaller Arrow batches for pandas UDFs over wide rows (default 10,000 rows)
spark.conf.set("spark.sql.execution.arrow.maxRecordsPerBatch", "2000")
  • Replace Python UDFs with built-ins where possible; see PySpark UDF vs Pandas UDF.
  • Split huge groups before applyInPandas, or pre-aggregate in Spark.
  • On platforms where you set it: raise spark.executor.memoryOverhead, or set spark.executor.pyspark.memory to cap and account for Python memory explicitly.
  • On Databricks, choose an instance type with more memory per core; overhead is managed for you.

Error message cheat sheet

Message Where First thing to check
OutOfMemoryError: Java heap space (driver log) Driver collect, toPandas, broadcast size
bigger than spark.driver.maxResultSize Driver What's being returned to the driver
OutOfMemoryError: Java heap space (task) Executor Max partition size, collect_list, explode
GC overhead limit exceeded Either Same as heap space; GC was thrashing first
SparkOutOfMemoryError: Unable to acquire ... Executor Partition too big for memory per task
Exit code 137 / container killed Executor Python workers, Arrow batches, big groups
Cannot broadcast the table that is larger than 8GB Driver Broadcast hint or stale stats
FetchFailedException after lost executors Executor Usually a symptom: an executor died (often OOM)

The result

NorthBridge changed basket grouping to per-transaction with a cap, and moved the franchise loyalty account to a separate B2B flow. The Monday job went back to the original instance type, ran in 21 minutes instead of failing after 50, and the compute bill for it dropped by two thirds.

From production: gotchas and lessons

  1. Symptom: Doubling executor memory made OOMs rarer but not gone. Cause: A skewed partition grew with the data. Fix: Measure max partition size before resizing. Memory buys time; it doesn't fix skew.

  2. Symptom: Exit code 137 on a job with lots of free heap. Cause: A pandas UDF over rows with 2 MB JSON payloads; Arrow batches of 10,000 rows were ~20 GB. Fix: maxRecordsPerBatch to 500 and parse the JSON with from_json in Spark first.

  3. Symptom: Driver OOM on a job that never called collect(). Cause: A broadcast hint on a dimension that had grown to 5 GB in memory (800 MB on disk, compressed). Fix: Removed the hint; AQE picked a sort-merge join. Remember: Parquet sizes are compressed; in-memory sizes can be 3–10× larger.

  4. Symptom: Cached data kept disappearing from the Storage tab mid-job. Cause: Execution evicted cache blocks to make room for a big join. Fix: Cache less (only the reused DataFrame), or persist with MEMORY_AND_DISK so evicted blocks spill instead of being recomputed. See cache vs persist vs checkpoint.

  5. Symptom: Moving to an instance with more cores and the same memory caused spill everywhere. Cause: Memory per task dropped. Fix: Compare memory per core, not memory per node, when choosing instance types.

Performance and cost notes

Memory-optimized instances cost more per hour, but a shuffle-heavy job that stops spilling often finishes fast enough to cost less overall. Compute-optimized instances suit scan-and-filter jobs with little shuffle. Pick per job, from what the Spark UI shows, not one size for everything.

Adding memory is the most expensive fix and the least durable one. Reducing what a single task has to hold (smaller partitions, no skew, no giant per-key arrays) is cheaper and keeps working as data grows.

When not to use this

You rarely need to touch spark.memory.fraction or storageFraction; the defaults are sensible and changing them mostly moves the problem. On serverless compute you can't size executors at all; focus on partition sizes, skew and what your code holds in memory.

Checklist

  • Know your memory per running task (unified memory ÷ cores)
  • Spill checked per stage; max vs median compared
  • Skew ruled out before resizing anything
  • No collect/toPandas on unbounded data
  • No hard-coded broadcasts on growing tables
  • Python UDF and Arrow batch sizes reviewed for exit-code-137 failures
  • Instance type chosen by memory per core for shuffle-heavy jobs

Practice

Further reading

#memory#oom#executors#spill#garbage-collection

Keep going

Article10 min read

Data Skew in Spark: Detect It and Fix It

Find the hot key behind a stage that never finishes, then fix it with AQE skew joins, key cleanup, hot-key isolation or salting, in that order.

One practical note a week

Get new articles, problems and guides in your inbox.