Memory and Caching: Intermediate
Every executor runs as a single JVM process, and the memory it gets is fixed when it launches. The spark.executor.memory setting, which --executor-memory sets on spark-submit, becomes that JVM's maximum heap. Inside the heap, Spark draws 3 regions, each with its own job and its own way of failing. A further pool, the overhead, sits outside the heap and gets its own section later in this lesson.
Three regions inside the heap
- Reserved memory300 MB, fixedSpark sets this aside for its own internal objects before counting anything else. No setting changes it, and Spark refuses to launch an executor with less than 450 MB of heap, one and a half times the reserved block.
- User memory40% of the heap left after reservedSpace outside Spark's accounting. It holds Spark's internal metadata, such as the records it keeps for partitions and blocks, plus any objects that code outside Spark's operators builds on the heap. Nothing here can spill or be evicted, so overfilling it ends in a heap OutOfMemoryError.
- Unified memory60% of the heap left after reservedThe region Spark manages, sized by spark.memory.fraction. Execution and storage share it, with a soft boundary between them placed by spark.memory.storageFraction, which defaults to 0.5.
Sizing an 8 GB executor
The arithmetic runs in megabytes of 1,024 KB, which the Spark UI writes as MiB: start from the heap, take away the reserved block, then split the rest by spark.memory.fraction. The executor below, 8 GB of heap and 4 cores, is the running example for every section that follows.
| Region | How it is computed | Size at an 8 GB heap |
|---|---|---|
| Heap (`spark.executor.memory`) | heap in GB times 1,024 | 8,192 MB |
| Reserved | fixed | 300 MB |
| Usable heap | heap minus reserved | 7,892 MB |
| Unified (`spark.memory.fraction` 0.6) | usable times 0.6 | 4,735 MB |
| Storage side (`storageFraction` 0.5) | unified times 0.5 | about 2,368 MB |
| Execution side | unified minus storage side | about 2,367 MB |
| User memory | usable times 0.4 | 3,157 MB |
Spark 1.6 introduced this layout with spark.memory.fraction at 0.75. Spark 2.0 lowered the default to 0.6, where it has stayed.
Which setting moves which region
| Setting | Default | Raising it does this |
|---|---|---|
| `spark.executor.memory` | 1g | Grows every region except reserved, in proportion |
| `spark.memory.fraction` | 0.6 | Grows unified memory and shrinks user memory by the same amount |
| `spark.memory.storageFraction` | 0.5 | Widens the cache's protected share and narrows execution's |
| `spark.executor.cores` | 1 on most cluster managers | Changes no region, but more tasks share the execution side at once |
spark.memory.fraction toward 0.9 looks like free memory for joins, but user memory shrinks to match, and code that builds large objects on the heap starts dying with OutOfMemoryError. Keep 0.6 until you have measured user memory sitting idle.An executor launches with spark.executor.memory set to 4g and every other memory setting at its default. How large is its unified region, the pool execution and storage share?
The unified region holds 2 kinds of data. Execution memory is working space for tasks running right now: the hash table a groupBy builds, the buffer a sort fills, the rows a sort-merge join holds while it matches keys, and records waiting to be written as shuffle files. Storage memory holds blocks you asked Spark to keep: partitions from cache() and persist(), plus broadcast variables, including the table a broadcast join ships to every executor.
The borrowing rules
| Situation | What Spark does |
|---|---|
| Storage wants space and execution's side is idle | Storage borrows it, so a cache can grow past its half |
| Execution wants space that storage has borrowed | Execution evicts cached blocks until storage is back at its line |
| Execution wants more, and storage is at or below its line | Execution evicts nothing further, and the task spills to disk |
| Storage wants space that execution is using | Storage cannot evict execution, so the new block goes to disk or stays uncached, per its storage level |
The asymmetry follows from what each side holds. Execution memory is the half-finished state of a running task, and taking it away would mean failing the task or redoing its work. A cached block is a copy: once evicted, Spark can rebuild it from lineage or read it back from disk. So execution wins every contest, but only down to the line spark.memory.storageFraction draws, which keeps a large shuffle from wiping a cache out entirely.
One executor, one join, step by step
| Step | Event | Storage (MB) | Execution (MB) | Free (MB) |
|---|---|---|---|---|
| 1 | Executor starts | 0 | 0 | 4,735 |
| 2 | `cache()` fills 3,600 MB of partitions | 3,600 | 0 | 1,135 |
| 3 | Join tasks ask for 2,000 MB | 2,735 | 2,000 | 0 |
| 4 | Join tasks ask for 600 MB more | 2,368 | 2,367 | 0 |
| 5 | Join finishes | 2,368 | 0 | 2,367 |
The running-example executor has a cached DataFrame using 3,000 MB of its 4,735 MB unified region when a join's tasks ask for 2,500 MB of execution memory. What happens?
What happens to evicted partitions depends on the storage level. Under MEMORY_ONLY they are dropped, and the next action that reads them recomputes them from lineage. Under a memory-and-disk level they are written to local disk as they leave memory, and the next read comes from there. A DataFrame's cache() uses a memory-and-disk level, while an RDD's cache() uses MEMORY_ONLY.
- Evict every cached block above the storage line
- Turn the next read of those partitions into a recompute or a disk scan
- Leave memory free that refills only when an action reads those partitions again
- Hold its protected half, about 2,368 MB here, out of execution's reach
- Lower the ceiling on execution, so join tasks spill earlier
- Never take memory from a task that is already running
MEMORY_ONLY only when recomputing a partition is cheaper than reading it back from local disk. For a cache built from a wide join or an expensive aggregation, keep a memory-and-disk level, so a later shuffle's evictions cost a disk read instead of a rerun.A DataFrame built from a wide join of transactions to products is persisted, and a large aggregation then runs on the same executors and evicts part of it. Which choice of storage level makes the next read of the evicted partitions skip a rerun of the join?
How much memory one task can get
| Executor state | Execution pool | Most a task can hold | Floor a task is given |
|---|---|---|---|
| No cache, 4 tasks running | 4,735 MB | about 1,184 MB | about 592 MB |
| Cache at its 2,368 MB line, 4 tasks running | about 2,367 MB | about 592 MB | about 296 MB |
| Cache at its line, 2 cores instead of 4 | about 2,367 MB | about 1,184 MB | about 592 MB |
Where a skewed key puts the pressure
This job joins trips to drivers with broadcasting switched off, so both sides are shuffled into 3 reducer tasks by driver_id. Driver 101 has 7 of the 12 trips. Every row a reducer task receives is held in its execution memory while the sort-merge join sorts and matches it, so watch which task collects the 7.
spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1)joined = trips.join(drivers, "driver_id")joined.collect()
Reading a spill in the stage metrics
| Metric | Min | Median | 75th percentile | Max |
|---|---|---|---|---|
| Duration | 41 s | 48 s | 55 s | 14 min |
| Shuffle Read Size | 75 MiB | 92 MiB | 105 MiB | 1.9 GiB |
| Peak Execution Memory | 230 MiB | 280 MiB | 310 MiB | 2.3 GiB |
| Spill (Memory) | 0 B | 0 B | 0 B | 7.6 GiB |
| Spill (Disk) | 0 B | 0 B | 0 B | 1.6 GiB |
A stage's summary metrics show the median task reading 120 MiB of shuffle data with no spill, while the max task reads 3.1 GiB and spills 11 GiB. Executors have 8g heaps and 4 cores. Which change targets the cause?
- Find the stage with nonzero Spill (Disk) and open its summary metrics.
- Compare Max with Median. Spill on the top tasks only means skewed input: salt or isolate the hot key, since more partitions leave it in one task.
- Spill on every task means each task's input outgrows its share. Raise spark.sql.shuffle.partitions so each task reads less.
- Even spill that more partitions do not cure, with a large cache at its line, means the cache is capping execution. Unpersist it before the stage, or give each task more memory with fewer cores or a bigger heap.
Find the execution memory in a query
The cell below aggregates the practice transactions table. It has 2 shuffles and 3 stages: the groupBy hashes rows by user_id, and the orderBy range-partitions the totals. Each reducer task builds a structure from execution memory, a hash table for the aggregation and a sort buffer for the ordering. Run it, then point to the 2 operations that would spill first if this table held a billion rows.
from pyspark.sql import functions as F
tx = spark.table("transactions").filter(
F.col("user_id").isNotNull() & F.col("total_amount").isNotNull()
)
spend = (
tx.groupBy("user_id")
.agg(
F.count("*").alias("purchases"),
F.round(F.sum("total_amount"), 2).alias("total_spend"),
)
.orderBy(F.desc("total_spend"), "user_id")
)
spend.collect()Everything so far lives inside the JVM heap. The cluster manager does not police the heap, though. It limits the whole process, and it sets that limit at the heap plus spark.executor.memoryOverhead. When the process's resident memory crosses the limit, the cluster manager kills it outright, with no exception, no spill and no chance to finish the task.
What lives outside the heap
Heap error or container kill
- The JVM throws java.lang.OutOfMemoryError: Java heap space inside a task
- The executor log holds the error and its stack trace
- The task fails with the error as its reason
- Fix with less data per task, more heap, or fewer cores
- The cluster manager kills the process from outside the JVM
- The executor log stops mid-stream, with no OutOfMemoryError
- The driver reports ExecutorLostFailure, often with exit code 137, which is 128 plus signal 9
- Fix with more spark.executor.memoryOverhead or fewer concurrent tasks
The tell is the mismatch. In the Executors tab, covered in the next section, a dead executor's storage memory can read far below its total, and its last log lines can be routine task progress, because the heap never ran out. The process outgrew its limit in memory the JVM does not count. The driver's failure reason starts with ExecutorLostFailure (executor 7 exited caused by one of the running tasks), followed by the cluster manager's own words: the container was killed for exceeding memory limits.
Raising the overhead
Fix the region that grew. Raising spark.executor.memory from 8g to 9g grows a heap that had room and adds only about 100 MB of overhead through the 10% share. Set the overhead directly instead:
The container grows from 9,011 MB to 10,240 MB, and every added megabyte lands outside the heap, where the kills came from. Spark 3.3 added spark.executor.memoryOverheadFactor for setting the share instead of a size: raising it from 0.10 to 0.20 gives the same 8 GB heap about 1,638 MB of overhead.
Executors keep dying mid-stage. The driver shows ExecutorLostFailure with exit code 137, the executor logs end with no OutOfMemoryError, and the dead executors' storage memory read 0.9 GiB of 4.4 GiB. Each has an 8g heap and the default overhead. What do you change?
Executors tab: unified memory per executor
Each executor gets a row. Storage Memory reads as used over total, for example 2.3 GiB / 4.4 GiB. The total is the whole unified region, since storage may borrow all of it, and it lands a little below the formula's 4,735 MB (4.6 GiB) because the JVM reports slightly less heap than it was given. Disk Used counts cached blocks held on local disk. Among the tab's additional metrics, Peak JVM Memory shows the most heap the process ever used. Task Time (GC Time) turns red when garbage collection takes more than 10% of task time, a sign the heap is crowded with live objects.
Storage tab: what survived in the cache
Each cached DataFrame gets a row, with its Storage Level, Cached Partitions, Fraction Cached, Size in Memory and Size on Disk. Under MEMORY_ONLY, evicted partitions leave the cache, so Fraction Cached falls below 100%. Under a memory-and-disk level, they move from Size in Memory to Size on Disk, and Fraction Cached can stay at 100% while the cache quietly slows down.
Stage page: execution memory per task
Open the slowest stage. Its summary metrics give Peak Execution Memory, Spill (Memory) and Spill (Disk) as quantiles, and its task table lists failed tasks with their error, which is where ExecutorLostFailure shows up.
From symptom to region
| What you see | Region under pressure | First move |
|---|---|---|
| Spill on most tasks, peaks near each task's share | Execution, in unified memory | More shuffle partitions, or fewer cores per executor |
| Spill on the max task only | Execution, from skewed input | Salt or isolate the hot key |
| Fraction Cached below 100%, or Size on Disk climbing during joins | Storage, in unified memory | Cache fewer columns, or unpersist sooner |
| `java.lang.OutOfMemoryError: Java heap space` in an executor log | User memory, or the heap as a whole | Less data per task, or more heap |
| `ExecutorLostFailure`, exit code 137, no heap error | Overhead, outside the heap | Raise `spark.executor.memoryOverhead` |
| GC Time in red | Heap crowded with live objects | Check cache size and per-task data first |
A report reads a DataFrame persisted with MEMORY_ONLY, after a large join ran on the same executors. Which reading tells you whether part of that DataFrame had to be recomputed?
Putting the readings together
A job caches trips_enriched with cache() on the running-example executors, then runs a heavy aggregation over it. No task fails. Mid-stage, the Executors tab and the stage's summary metrics read as follows.
| Executor | Storage Memory | Disk Used |
|---|---|---|
| 1 | 2.2 GiB / 4.4 GiB | 3.1 GiB |
| 2 | 2.2 GiB / 4.4 GiB | 3.0 GiB |
| 3 | 2.2 GiB / 4.4 GiB | 3.2 GiB |
| Metric | Median | Max |
|---|---|---|
| Peak Execution Memory | 548 MiB | 563 MiB |
| Spill (Memory) | 2.8 GiB | 3.0 GiB |
| Spill (Disk) | 610 MiB | 650 MiB |
Which reading of these numbers is right, and what is the first move?
> Uber's nightly trip job from the intro runs on executors with 8g heaps, 4 cores and default memory settings. It caches trips_enriched at 3,600 MB per executor, joins trips to drivers, and loses 2 executors with exit code 137 while their storage memory sits well below its total.
cache() uses a memory-and-disk level, the 3 reports read those partitions from local disk instead of recomputing a week of trips.spark.executor.memoryOverhead to 2g grows each container from 9,011 MB to 10,240 MB.spark.executor.memoryOverhead, and leave the heap alone.Size each slice of executor memory, see why joins evict caches, and trace spills and container kills to their cause.
- Category
- Spark
- Difficulty
- intermediate
- Duration
- 14 minutes
- Challenges
- 16 hands-on challenges
Topics covered: The Executor Memory Split, Execution vs Storage Memory, Spilling to Disk, The memoryOverhead OOM, Reading Memory in the UI
Lesson Sections
- The Executor Memory Split
Three regions inside the heap Sizing an 8 GB executor Look at where the 0.6 lands. It multiplies the usable heap, so an executor launched with 8 GB gives Spark's managed region about 4.6 GB, a little over half of what the command line asked for. The storage and execution sides are a starting position: the next section shows each one growing into the other's space, and what happens when the owner wants it back. Spark 1.6 introduced this layout with spark.memory.fraction at 0.75. Spark 2.0 lowered
- Execution vs Storage Memory
Before Spark 1.6 a fixed wall stood between them, so a job with no cache left its storage share idle while its sorts spilled. The unified design takes the wall down and lets either side borrow what the other is not using. The rules that matter are the ones for getting borrowed memory back. The borrowing rules One executor, one join, step by step Back to the running example: 4,735 MB of unified memory, with the storage line near 2,368 MB. A job caches an enriched trips DataFrame that needs 3,600
- Spilling to Disk
A spill is what a task does when it asks for execution memory and the memory manager refuses. The operator holding the data, whether a sort buffer, an aggregation hash table or the sort inside a sort-merge join, writes what it has to local disk as a sorted file, frees the memory, and keeps reading. When input runs out, it merges the spilled files with what is still in memory. The task finishes with the right answer, after serializing, writing, reading back and merging data that never needed to l
- The memoryOverhead OOM
What lives outside the heap None of this appears in Spark's memory accounting, so none of it can spill or be evicted. The default overhead is the larger of the floor and the share: for the running example's 8,192 MB heap, 10% gives 819 MB, and the cluster manager grants a container of 9,011 MB. Heap error or container kill Raising the overhead
- Reading Memory in the UI
Each region from this lesson leaves a trace in the Spark UI, spread across 3 places: the Executors tab, the Storage tab, and the detail page for each stage. Walking them in that order narrows a memory problem to a single region. Executors tab: unified memory per executor Storage tab: what survived in the cache Stage page: execution memory per task From symptom to region Putting the readings together