The memory manager
Part of the free LogicWiz Data Engineering course, Module 12: How Spark runs. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 2:10 a.m. and the nightly join has died again. Tuesday's log says java.lang.OutOfMemoryError: Java heap space. Thursday's says Container killed by YARN for exceeding physical memory limits. Nora reads both and says: "Same job, two different deaths. Find out where the memory went."
You'll learn to
- Draw where an 8 GB executor's memory goes, with real numbers
- Explain how the cache and the running tasks share one pool
- Work out how much memory one task may hold
- Tell three out-of-memory deaths apart from the log, and fix each
Learn
One worker, four rooms
Start with one worker. Spark calls the program that runs on it an executor, and you gave it 8 GB.
Think of that memory as a flat with four rooms. Spark keeps a small room for itself. Your own objects get a room. The two biggest rooms do the real work: one holds data you asked Spark to cache, the other is the workbench where joins and sorts happen.
There is also a balcony outside the flat. We will come back to it: Thursday's crash happened there.
Where 8 GB goes
One bar for an 8 GB executor, split into Spark's reserved room, your room, the cache room and the workbench inside the Java heap, and the overhead outside it, with the container, the heap and the unified memory bracketed.
Read it left to right. The first four blocks are inside the Java heap. The orange block is outside it.
Now read the picture with Spark's own names, one line per step:
- The heap is 8,192 MB. Spark's room, reserved memory, is always 300 MB. That leaves 7,892 MB.
- 60% of that is the two big rooms together: 7,892 × 0.6 = 4,735 MB.
- The wall starts in the middle: 2,368 MB for the cache (storage memory), 2,368 MB for the workbench (execution memory).
- The other 40%, 3,157 MB, is your room: user memory. Spark does not count what you put in it.
- The balcony, overhead, is 10% of the heap: 819 MB.
Run the numbers yourself
def regions(heap_mb, fraction=0.6, storage_fraction=0.5, overhead_factor=0.10,
min_overhead_mb=384, offheap_mb=0, pyspark_mb=0):
"""Where an executor's memory goes, in MB, the way Spark sizes it."""
usable = heap_mb - 300 # 300 MB reserved for Spark itself
unified = usable * fraction # M: execution + storage
storage = unified * storage_fraction # R: cached blocks execution cannot evict
overhead = max(min_overhead_mb, heap_mb * overhead_factor)
return {
'container': heap_mb + overhead + offheap_mb + pyspark_mb,
'overhead': overhead, 'reserved': 300, 'user': usable - unified,
'storage': storage, 'execution': unified - storage,
}
for gb in (8, 16):
r = regions(gb * 1024)
print(f'{gb}g:', {k: round(v) for k, v in r.items()})
print('8g + pyspark 2g:', round(regions(8192, pyspark_mb=2048)['container']))
The last line adds a 2 GB allowance for Python (spark.executor.pyspark.memory): the container grows, the heap does not. Try regions(2048): the overhead stops at 384 MB, its smallest size.
The two rooms share a wall
The cache room and the workbench are not fixed. The wall between them moves.
If the workbench is empty, the cache may spread into it. When a join needs the space back, Spark pushes cached data out again, but only down to a line it promised the cache: half of the two rooms, 2,368 MB here. Pushing cached data out of memory is called eviction.
Spark calls the two rooms together unified memory. Step through one night of it.
A join asks for its space back
The 4,735 MB of unified memory on an 8 GB executor in four steps: empty, filled by a 4 GB cached table that borrows from the workbench, partly evicted when a join starts, and evicted down to the promised line when a bigger stage runs.
An idle executor. Nothing is cached and nothing runs. Both rooms are empty: 4,735 MB, with the promised line in the middle.
You cache a 4 GB table. It fills the cache room, then spreads 1,728 MB past the line, because the workbench is idle. 639 MB stays free.
A join starts. Its four tasks want 400 MB each: 1,600 MB. Only 639 MB is free, so Spark evicts 961 MB of the cache to make room.
A bigger stage starts. Four tasks want 1,200 MB each. The cache is evicted down to the promised line, 2,368 MB, and no further. The tasks share what is left.
Read each bar left to right: the cache grows from the left, the tasks from the right. A DataFrame cache is stored as MEMORY_AND_DISK, so evicted blocks are written to the worker's local disk. With MEMORY_ONLY they are dropped and computed again later.
Remember: the cache can borrow from the workbench, and the workbench can take it back. Never the other way round: a running join is never pushed out to make room for cache.
Four tasks, one workbench
The executor has 4 cores, so it runs 4 tasks at once (Lesson 12.1). They share the workbench, and Spark keeps them honest with one rule.
With N tasks running, each task may hold at most 1/N of the workbench. And each is promised half of that, 1/(2N): a task that cannot get its promise waits for the others to free memory, instead of giving up early.
How big is the workbench? All the unified memory, minus the cached data that sits inside the promised line. With nothing cached that is the full 4,735 MB. With the cache room full it is 2,368 MB.
Four tasks arrive, one by one
The 4,735 MB workbench as one bar while four tasks that each want 2,000 MB start one after another: the first two get it all, the third waits, the early tasks spill down to the shrinking cap, and all four end at 1,184 MB.
Task 1 starts alone. N = 1, so its cap is the whole workbench. It asks for 2,000 MB and gets it.
Task 2 starts. N = 2: the cap drops to 4,735 / 2 = 2,368 MB. Both tasks hold 2,000 MB. Only 735 MB is free.
Task 3 starts, and waits. N = 3: the cap is 1,578 MB and the promise is 789 MB. Only 735 MB is free, less than the promise, so task 3 waits. Tasks 1 and 2 are now over the cap.
The first two spill. The next time they ask for memory they get none. So they write what they hold to disk and carry on under the cap. Task 3 gets its memory.
Task 4 starts. N = 4: the cap is 1,184 MB, the promise 592 MB. The same dance again: it waits, the others spill, and all four settle at 1,184 MB. Whatever a task needs beyond that goes to disk.
Read the bar as the whole workbench. N counts the tasks running right now, so the cap moves as tasks start and finish. Twice the cores on the same heap means half the memory per task.
The same rule, as a small Python class
class ExecutionPool:
"""Execution memory shared by the running tasks, as Spark's ExecutionMemoryPool shares it."""
def __init__(self, size_mb):
self.size = size_mb
self.held = {} # task -> MB it holds now
def acquire(self, task, want_mb):
"""Grant up to want_mb. With N tasks running, no task may hold more than size / N."""
self.held.setdefault(task, 0)
cap = self.size / len(self.held)
free = self.size - sum(self.held.values())
grant = max(0, min(want_mb, cap - self.held[task], free))
self.held[task] += grant
return grant
def spill(self, task):
"""The task writes what it holds to disk and gives the memory back."""
self.held[task] = 0
pool = ExecutionPool(4735) # 8 GB heap, 4 cores, nothing cached
for task in (1, 2, 3, 4):
got = pool.acquire(task, 2000)
print(f'task {task} asks for 2000 MB, gets {got:4.0f}, cap now {pool.size / len(pool.held):4.0f}')
pool.spill(1) # task 1 is over its cap: it spills
print('task 4 asks again, gets', round(pool.acquire(4, 2000)))
print('held:', {t: round(mb) for t, mb in pool.held.items()})
This small class does not wait: task 3 takes the 735 MB that is free and task 4 gets nothing. In Spark both would wait for their promise. Either way, memory moves only when a task over its cap spills.
When the workbench is full, Spark spills
A task that reaches its cap does not crash. It spills: it sorts what it holds, writes it to the worker's local disk as one sorted file, and gives the memory back. At the end it merges its files. Think of clearing a full desk into a labelled box so you can keep working.
Sorts spill. So do the joins that sort (the sort-merge join of Lesson 12.4) and the shuffle writers of the next lesson. A big group-by spills too: when its hash table cannot grow, Spark sorts it, spills it, and finishes the job as a sort. Slow, but safe.
Three things cannot spill: a broadcast table, one row bigger than the memory, and anything in your room. Hold on to that last one.
Try it: cache a table, then run two stages
An 8 GB executor: a 4 GB table is cached and borrows idle execution memory, then two stages of four tasks evict cached blocks down to the storage region, and the tasks that need more than their share spill.
Step through it: this is the walkthrough above, with each task's share and its spill drawn in. Then move spark.memory.storageFraction and step again: the dashed line is the promise to the cache, where eviction stops.
Tuesday: the room nobody watches
Tuesday's log says java.lang.OutOfMemoryError: Java heap space. The heap is full, so the trouble is inside the flat.
But the workbench cannot overflow: it spills. The cache cannot either: it is evicted. That leaves your room, the user memory Spark does not count.
The job's last step gathers each customer's order ids into one list with collect_list. One reseller account has millions of orders. Say each of the 4 tasks builds a 1,000 MB list: 4,000 MB, in a room of 3,157 MB. (Made-up sizes, real mechanism.)
Java gives up, and the executor exits with code 52. It is the first log below.
Three logs from three bad nights
Runs in the cloud:
# 1. Executor log: a heap OOM in a task
ERROR Executor: Exception in task 17.0 in stage 4.0 (TID 213)
java.lang.OutOfMemoryError: Java heap space
# ... and in the driver log
Lost task 17.0 in stage 4.0 (TID 213) (10.0.1.14 executor 3): ExecutorLostFailure (executor 3 exited caused by one of the running tasks) Reason: Remote RPC client disassociated. Likely due to containers exceeding thresholds, or network issues.
# 2. Driver log on YARN: the container was killed
WARN YarnAllocator: Container killed by YARN for exceeding physical memory limits. 9.4 GB of 9 GB physical memory used. Consider boosting spark.executor.memoryOverhead.
# 3. Driver log on Kubernetes: the same kill
The executor with id 5 exited with exit code 137(SIGKILL, possible container OOM).
Trimmed. Log 1 is Tuesday: a Java error with a stack trace in the executor's log, and a vaguer line in the driver's. Logs 2 and 3 are Thursday's kind of death, on YARN and on Kubernetes. They have no Java stack trace. The 9 GB in log 2 is the 9,011 MB container, rounded up by YARN.
Thursday: the balcony
Thursday's log has no Java error at all. Now the balcony matters.
Spark does not ask the cluster for 8 GB. It asks for a box, the container, that holds the heap plus room outside it: the overhead, 10% of the heap and never less than 384 MB. Here that is 8,192 + 819 = 9,011 MB. The cluster enforces that number, not the heap.
The overhead holds everything that is not Java heap: Java's own threads and network buffers, and any other process in the box. The same job also scores each order with a function written with pandas (Lesson 12.11 opens it up). Its code runs in Python workers: separate processes, one per task, all on the balcony.
Thursday night, step by step
Two bars on one scale, the 9,011 MB the cluster allows and what the executor process uses, in four steps: Python workers start, grow to 2,400 MB, the heap fills until the total passes the limit and the process is killed, and the driver retries on a fresh executor.
The pandas stage starts. Four tasks each start a Python worker, a separate process outside the Java heap. So far they are small: 100 MB each.
The Python workers grow. Each holds a batch of rows and the pandas copies of it: 600 MB each, 2,400 MB in all. The overhead was sized for 819 MB.
The join fills the heap, and the box is too small. Java now uses 7,200 MB of its 8,192 MB. With the Python workers that is 9,600 MB, in a box of 9,011 MB. The cluster kills the whole process: exit code 137 on Kubernetes, where the pod says
OOMKilled. Java never gets to write a stack trace.The driver tries again. It sees
ExecutorLostFailure: the running tasks and the shuffle files this executor served are gone. A fresh executor starts the same tasks on the same data, and fills up the same way. Each task is retried up to 4 times, then the job fails.
Compare the two bars: the kill comes when the lower one grows longer than the upper one. The heap sizes are made up; 9,600 MB is the "9.4 GB of 9 GB" in log 2. Two extras are added to the box when you set them: spark.memory.offHeap.size and spark.executor.pyspark.memory.
A third way to die: the driver
There is one more flat in the building. The driver is the program that plans the job and hands out the tasks (Lesson 12.1), and it has its own heap: 1 GB unless you change it.
It fills up when you bring data home: collect(), toPandas(), or a broadcast join, where the driver gathers the small table and builds its hash table before sending it out.
Spark puts a guard at the door. Once the results coming back pass 1 GB (spark.driver.maxResultSize), it stops the job with a clear error. Take the guard away and the driver itself runs out of memory. When the driver dies, the whole application dies with it, not one task.
Three deaths, told apart
| Kind | What the log says | Exit | Usual cause | Fix |
|---|---|---|---|---|
| Heap out of memory in a task (Tuesday) | java.lang.OutOfMemoryError: Java heap space in the executor log | code 52 (JVM OOM) | Objects Spark does not count: a huge collectlist array, a hot key in groupByKey, a UDF's cache | Spread the key, aggregate instead of collecting, fewer cores or more memory per core |
| Container killed (Thursday) | Container killed by YARN for exceeding physical memory limits; on Kubernetes the pod is OOMKilled | 137 (SIGKILL) on Kubernetes, status -104 on YARN; no Java stack trace | Memory outside the heap: Python workers, Arrow batches, native libraries | Raise spark.executor.memoryOverhead or set spark.executor.pyspark.memory; hold less per worker |
| Driver out of memory | OutOfMemoryError in the driver log; the application dies | the driver exits | collect() or toPandas() on big data, building a big broadcast | Aggregate or write instead; a smaller broadcast; more spark.driver.memory |
| Not a crash: the result guard | Total size of serialized results ... is bigger than spark.driver.maxResultSize | job stopped, application lives | A big collect() | As for the driver: the guard did its job |
The driver often reports only a vague ExecutorLostFailure ... Remote RPC client disassociated. The executor's own log, the exit code and the cluster manager (kubectl describe pod, YARN diagnostics) tell the kinds apart.
Remember: read the error text and the exit code before you touch a setting. Inside the heap, outside the heap, or the driver: each has its own fix.
A bigger heap does not fix a container kill. Exceeding physical memory limits or exit code 137 means the memory outside the heap ran out, and a bigger spark.executor.memory grows the overhead by only 10% of what you add. And do not set spark.driver.maxResultSize=0 to silence the result guard: you swap a clear job failure for a dead driver.
Sizing the new nodes
Nora's last question: the new nodes have 16 cores and 128 GB. How do you cut them up?
- Keep 1 core and 8 GB for the operating system: 15 cores and 122,880 MB are left.
- 5 cores per executor (4 to 5 is usual): 3 executors on a node.
- Each container: 122,880 / 3 = 40,960 MB.
- Heap: 40,960 / 1.10 = 37,236 MB. That is past 32 GB, where Java's pointers grow from 4 to 8 bytes and a bigger heap holds little more. Cap it at
30g(30,720 MB). - Overhead: the rest, 10,240 MB (
spark.executor.memoryOverhead=10g), room for 5 Python workers. - Per task: (30,720 − 300) × 0.6 / 5 = 3,650 MB at most.
A partition that needs more than about 3.6 GB to sort will spill. Make partitions smaller before you make executors bigger.
Numbers to remember
| Setting | Default | What it is |
|---|---|---|
| spark.executor.memory | 1g | The executor's Java heap (passed to Java as -Xmx). |
| spark.executor.memoryOverhead | 10% of the heap, at least 384 MB | Room outside the heap. The 10% is spark.executor.memoryOverheadFactor (since Spark 3.3), the floor spark.executor.minMemoryOverhead (since 4.0). Kubernetes uses 40% for non-JVM jobs such as PySpark. |
| Reserved memory | 300 MB, fixed | Spark's own room. It is why the smallest heap Spark accepts is 450 MB (1.5 times 300). |
| spark.memory.fraction | 0.6 | The share of (heap − 300 MB) that is unified memory. The rest is user memory. Unified memory arrived in Spark 1.6. |
| spark.memory.storageFraction | 0.5 | The share of unified memory promised to the cache. Raise it and more cache is safe, with less room left for joins. |
| spark.memory.offHeap.enabled, .size | false, 0 | Puts the workbench outside the heap, where Java's garbage collector does not look. The size is added to the container; it does not shrink the heap, so lower spark.executor.memory yourself. |
| spark.executor.pyspark.memory | not set | A separate allowance for the Python workers, added to the container. |
| spark.buffer.pageSize | 1 to 64 MB, picked by Spark | The workbench hands out memory in blocks called pages. Spark picks a power of two from the execution memory, the cores and a safety factor of 16. On the 8 GB, 4-core executor: 2,368 / 4 / 16 = 37 MB, rounded up to 64 MB. |
| spark.driver.memory | 1g | The driver's heap. |
| spark.driver.maxResultSize | 1g | The guard on results coming back to the driver. 0 removes it. |
| spark.task.maxFailures | 4 | How many times one task may fail before the job fails. |
| Garbage collection | G1 (Java 17, the default since Spark 4.0) | Java pauses every task in the executor to clean up. The Executors tab turns task time red past 10% in the GC Time column. For large heaps the tuning guide suggests a bigger -XX:G1HeapRegionSize. |
| Heap size | stay under about 32 GB | Past it, Java loses compressed pointers: a 36 GB heap holds little more than a 31 GB one. Huge executors (16 cores, 64 GB) also mean long pauses. |
Spark reads the heap size from Java itself (Runtime.maxMemory), a little under -Xmx, so the Spark UI shows slightly smaller numbers than these. YARN rounds the container up to its allocation step; Kubernetes sets the pod's memory request and limit to the total.
On Databricks you pick a worker type, and Databricks sets the executor memory and the overhead from it: one executor per worker. Serverless compute hides it all. Databricks' own test for a suspected memory problem is to double the memory per core and keep the cores (4 cores and 16 GB become 4 cores and 32 GB). If the job now fails later, or succeeds, memory was the problem. On YARN and Kubernetes you size by hand, as above.
What changed at SwiftKart
Two deaths, two fixes. Which one struck first depended on the night's data.
Tuesday was your room. You swapped the collect_list for a count and a sum, so no task builds a giant list. The heap error is gone.
Thursday was the balcony. You set spark.executor.memoryOverhead=3g, room for four Python workers. No more kills.
Nora adds one line to the runbook: read the error text and the exit code first.
One thing is still odd. On Thursday, after the executor was killed, a stage that had already finished ran again. To see why, you need to know what a join leaves on disk between two stages. That is Lesson 12.9, Inside a shuffle.
In one line
An executor's heap has four rooms and an overhead outside it: the cache and the running tasks share one pool, each of N tasks may hold at most 1/N of it and spills beyond that, and the error text and exit code tell you whether the heap (52), the container (137) or the driver ran out.
Interview corner
How is an 8 GB executor's memory divided?
The container is the 8,192 MB heap plus overhead of max(384 MB, 10%) = 819 MB, about 9,011 MB, more if off-heap or PySpark memory is set. In the heap, 300 MB is reserved; 60% of the remaining 7,892 MB, 4,735 MB, is the unified region shared by execution and storage; the other 3,157 MB is user memory that Spark does not track. Half of the unified region, 2,368 MB, is R, where cached blocks cannot be evicted. With 4 cores each task may hold 592 to 1,184 MB of execution memory.
What happens when a join needs memory that the cache is using?
Storage may have borrowed idle execution memory. When execution needs it back, the memory manager evicts cached blocks, oldest first, until storage is down to R (storageFraction of the unified region), never further. MEMORY_AND_DISK blocks are written to local disk and MEMORY_ONLY blocks are dropped and recomputed later. Storage can never evict execution, so a cache request that finds the region full of running hash tables spills to disk or evicts other cached blocks.
An executor running PySpark dies with exit code 137 on Kubernetes. Walk through the diagnosis.
137 is SIGKILL, so the container passed its memory limit and was killed from outside; there is no Java stack trace and the heap may have been half empty. I check kubectl describe pod for OOMKilled, then what runs outside the heap: Python workers, one per core, holding Arrow batches or whole groups from applyInPandas. The fix is more spark.executor.memoryOverhead or a spark.executor.pyspark.memory allowance, and less held per worker: smaller arrow.maxRecordsPerBatch, fewer columns, no huge groups. A bigger heap does not help.
How would you size executors on 16-core, 128 GB nodes?
Leave a core and about 8 GB for the OS and agents, so 15 cores and 120 GB. Five cores per executor gives three executors of 40 GB each. A 36 GB heap would lose compressed pointers, so I would cap the heap at 30 GB and give 10 GB to overhead, which suits PySpark. Each task then may hold up to (30,720 − 300) × 0.6 / 5 = 3,650 MB, and I size shuffle partitions so a task's data fits in that.