IntermediateSpark · 14 min · 16 challenges

Memory and Caching: Intermediate

Uber's nightly trip pipeline joins a week of rides to driver records, caches the result, and feeds 3 fare reports. Tonight 2 executors vanish mid-join with exit code 137, while their heaps sit half empty and no OutOfMemoryError appears anywhere. Raise the heap, raise the overhead, or drop the cache? Picking right depends on knowing which slice of executor memory actually ran out.

The Executor Memory Split

Daily Life
Interviews

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

Bottom of the heap to top
  • 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.

RegionHow it is computedSize at an 8 GB heap
Heap (`spark.executor.memory`)heap in GB times 1,0248,192 MB
Reservedfixed300 MB
Usable heapheap minus reserved7,892 MB
Unified (`spark.memory.fraction` 0.6)usable times 0.64,735 MB
Storage side (`storageFraction` 0.5)unified times 0.5about 2,368 MB
Execution sideunified minus storage sideabout 2,367 MB
User memoryusable times 0.43,157 MB
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 the default to 0.6, where it has stayed.

Which setting moves which region

SettingDefaultRaising it does this
`spark.executor.memory`1gGrows every region except reserved, in proportion
`spark.memory.fraction`0.6Grows unified memory and shrinks user memory by the same amount
`spark.memory.storageFraction`0.5Widens the cache's protected share and narrows execution's
`spark.executor.cores`1 on most cluster managersChanges no region, but more tasks share the execution side at once
TIP
Pushing 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.
Multiple Choice

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?

Execution vs Storage Memory

Daily Life
Interviews

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.

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

SituationWhat Spark does
Storage wants space and execution's side is idleStorage borrows it, so a cache can grow past its half
Execution wants space that storage has borrowedExecution evicts cached blocks until storage is back at its line
Execution wants more, and storage is at or below its lineExecution evicts nothing further, and the task spills to disk
Storage wants space that execution is usingStorage 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

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 MB, then runs a join that asks for working memory in 2 rounds.
StepEventStorage (MB)Execution (MB)Free (MB)
1Executor starts004,735
2`cache()` fills 3,600 MB of partitions3,60001,135
3Join tasks ask for 2,000 MB2,7352,0000
4Join tasks ask for 600 MB more2,3682,3670
5Join finishes2,36802,367
At step 2 the cache has borrowed 1,232 MB from the execution side. At step 3 the join takes the 1,135 MB that were free and evicts 865 MB of cached partitions to cover the rest. At step 4 only 367 MB more can be evicted before storage reaches its line, so 233 MB of the request goes unmet and the tasks spill. After step 5 the cache is short 1,232 MB of partitions, and 2,367 MB sits free.
Multiple Choice

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.

✓What a big join can do to your cache
  • 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
✗What your cache can do to a big join
  • 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
That right-hand column is why a cache can never stall a join. No running task waits for storage to hand memory back. The worst a cache does is sit in its protected half, which caps execution and makes the join spill sooner, a cost the next section teaches you to read.
TIP
Pick 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.
Multiple Choice

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?

Spilling to Disk

Daily Life
Interviews
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 leave RAM.

How much memory one task can get

Every task running on an executor at the same moment draws on the same execution pool. With N tasks running, each can hold at most 1/N of the pool. Spark also keeps a floor: before a task is left with less than 1/(2N), it waits for other tasks to release memory. On the running example's 4 cores, N is 4.
Executor stateExecution poolMost a task can holdFloor a task is given
No cache, 4 tasks running4,735 MBabout 1,184 MBabout 592 MB
Cache at its 2,368 MB line, 4 tasks runningabout 2,367 MBabout 592 MBabout 296 MB
Cache at its line, 2 cores instead of 4about 2,367 MBabout 1,184 MBabout 592 MB
Use the table as a test for any stage: when a task's input, held in memory as rows, outgrows its share, that task spills. Shuffle read sizes in the UI are compressed bytes, and the same rows usually take several times that space once deserialized, so 300 MB of shuffle read can overflow a 592 MB share. The last row shows a lever on the cores: halving them doubles each task's share without touching the heap, at the price of half as many tasks at once.

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()
trips12 rows
trip_id
driver_id
fare
1
101
12.5
2
101
8
3
102
22
4
101
15.25
5
103
9.75
6
101
31
7
104
6.5
8
101
18
9
102
11
10
101
27.5
11
105
14
12
101
7.25
drivers5 rows
driver_id
city
101
Chicago
102
Austin
103
Denver
104
Austin
105
Boston
Preparing the animation
The plan has 3 stages: a map stage for each side writing shuffle files, then the join stage reading them. The task that receives driver 101 holds at least 7 trip rows, while the other 2 tasks share at most the remaining 5. Scale every row up a million times: that task gets the same share of memory as its neighbours, with several times their input, and it is the one that spills.

Reading a spill in the stage metrics

Spark records 2 spill numbers per task. Spill (Memory) is the size of the spilled data as deserialized rows in memory at the moment it was written out. Spill (Disk) is the size of the same data serialized and compressed on disk. The memory figure is usually several times the disk figure, and both read 0 for a task that never ran short. The stage page shows them as quantiles across the stage's tasks:
MetricMinMedian75th percentileMax
Duration41 s48 s55 s14 min
Shuffle Read Size75 MiB92 MiB105 MiB1.9 GiB
Peak Execution Memory230 MiB280 MiB310 MiB2.3 GiB
Spill (Memory)0 B0 B0 B7.6 GiB
Spill (Disk)0 B0 B0 B1.6 GiB
This stage ran on running-example executors with a cache sitting at its 2,368 MB line, so the execution pool was about 2,367 MB and each of 4 tasks started with about 592 MB. The max column carries the story. One task read 1.9 GiB of shuffle data, about 21 times the median, and spilled 7.6 GiB of rows. Its peak execution memory of 2.3 GiB is nearly the whole pool: as the other tasks finished, N fell, its share grew toward all of it, and it still could not hold its input. The median task, with its 592 MB share and a 280 MiB peak, never spilled.
Multiple Choice

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?

Tracing a spill to the memory it lacked
  • 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.
Loading the challenge

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()

The memoryOverhead OOM

Daily Life
Interviews

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.

384 MB
default overhead floor
10%
default overhead share of the heap
137
exit code of a killed executor

What lives outside the heap

Thread stacks for every task, shuffle and network thread the executor runs
Thread stacks for every task, shuffle and network thread the executor runs
The JVM's own metadata, such as loaded classes and compiled code
The JVM's own metadata, such as loaded classes and compiled code
Direct byte buffers the network layer uses to send and fetch shuffle blocks
Direct byte buffers the network layer uses to send and fetch shuffle blocks
Native memory used by compression libraries and other code outside the JVM
Native memory used by compression libraries and other code outside the JVM
Python worker processes the executor starts to run your Python functions
Python worker processes the executor starts to run your Python functions
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

✓Heap OutOfMemoryError
  • 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
✗Container kill
  • 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:

from pyspark.sql import SparkSession
spark = (
SparkSession.builder
.appName("trips_nightly")
.config("spark.executor.memory", "8g")
.config("spark.executor.cores", "4")
.config("spark.executor.memoryOverhead", "2g")
.getOrCreate()
)

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.

TIP
Fewer cores per executor also helps. Each concurrent task brings its own threads, buffers and in-flight shuffle fetches, so 2 tasks need less overhead than 4 inside the same container.
Multiple Choice

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?

Reading Memory in the UI

Daily Life
Interviews
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

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 seeRegion under pressureFirst move
Spill on most tasks, peaks near each task's shareExecution, in unified memoryMore shuffle partitions, or fewer cores per executor
Spill on the max task onlyExecution, from skewed inputSalt or isolate the hot key
Fraction Cached below 100%, or Size on Disk climbing during joinsStorage, in unified memoryCache fewer columns, or unpersist sooner
`java.lang.OutOfMemoryError: Java heap space` in an executor logUser memory, or the heap as a wholeLess data per task, or more heap
`ExecutorLostFailure`, exit code 137, no heap errorOverhead, outside the heapRaise `spark.executor.memoryOverhead`
GC Time in redHeap crowded with live objectsCheck cache size and per-task data first
Multiple Choice

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.

Executors tab, mid-stage
ExecutorStorage MemoryDisk Used
12.2 GiB / 4.4 GiB3.1 GiB
22.2 GiB / 4.4 GiB3.0 GiB
32.2 GiB / 4.4 GiB3.2 GiB
Stage summary metrics
MetricMedianMax
Peak Execution Memory548 MiB563 MiB
Spill (Memory)2.8 GiB3.0 GiB
Spill (Disk)610 MiB650 MiB
Multiple Choice

Which reading of these numbers is right, and what is the first move?

PUTTING IT ALL TOGETHER

> 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.

The heap math sets the stage: 7,892 MB usable, 4,735 MB unified, 3,157 MB user, and a storage line near 2,368 MB.
The join evicts the 1,232 MB of cache above that line, and because a DataFrame's cache() uses a memory-and-disk level, the 3 reports read those partitions from local disk instead of recomputing a week of trips.
With the cache at its line, each of the 4 join tasks gets about 592 MB, so even spill across tasks points at too much data per task, while a single spilling task would point at a hot driver.
The lost executors had heap to spare, so the kill came from overhead: raising spark.executor.memoryOverhead to 2g grows each container from 9,011 MB to 10,240 MB.
The Executors tab, the Storage tab and the stage summary each confirm one piece, which is how the fix lands on overhead instead of the heap.
KEY TAKEAWAYS
An executor's heap splits into 300 MB reserved, user memory, and a unified region of 0.6 of the rest, shared by execution and storage.
Execution can evict cached blocks down to the storage line, and storage can never take memory from a running task.
A task gets between 1/(2N) and 1/N of the execution pool, and spills whenever its input outgrows that share.
Spill on every task means too much data per task; spill on the max task alone means a skewed key.
Exit code 137 with no heap error is a container kill: raise spark.executor.memoryOverhead, and leave the heap alone.
The Executors tab, the Storage tab and the stage summary each point at a different region.

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

  1. 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

  2. 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

  3. 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

  4. 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

  5. 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