Containers, Kubernetes and memory limits
Part of the free LogicWiz Data Engineering course, Module 10: Working like an engineer. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 2:20 a.m. SwiftKart's nightly PySpark job moved from YARN to Kubernetes last week, and its executors die every night: exit code 137, reason: OOMKilled. Yesterday someone doubled spark.executor.memory from 8g to 16g. Tonight the executors still die, and half of them never start at all: Pending. Nora reads the change and says: "You doubled the one number that was not the problem."
You'll learn to
- Read a container's limits and counters from its cgroup files
- Say what the kernel does when a container reaches its memory limit
- Set requests and limits, and predict which pod is killed first
- Work out the memory a Spark executor pod asks for
Learn
A pod is a box with numbers
SwiftKart's Spark job now runs on Kubernetes: a system that runs containers across a fleet of machines, called nodes. Its unit is the pod: one or more containers placed on a node together. Each of the job's workers, which Spark calls executors (Module 12), is one pod.
Last lesson you met the memory ceiling. This is where it lives. To the Linux kernel, the core of the operating system, a container is ordinary processes with two extras. Namespaces decide what it can see: its own process ids, files and network. cgroups decide what it may use.
A cgroup is nothing more than a folder of small text files. The limit is a number in one file, and the usage right now is a number in another. You can read them.
Read the ceiling from inside a pod
Runs in the cloud:
kubectl exec swiftkart-loader-7d9f -- sh -c '
cd /sys/fs/cgroup
cat memory.max memory.current cpu.max
cat memory.events
grep -E "^(anon|file) " memory.stat'
4294967296
3758096384
200000 100000
low 0
high 0
max 1284
oom 1
oom_kill 1
oom_group_kill 0
anon 2684354560
file 1073741824
Line by line. memory.max is the limit: 4 GiB, in bytes. memory.current is the usage now: 3.5 GiB. cpu.max is the CPU limit: 200 ms of CPU time in every 100 ms, which is 2 CPUs. In memory.events, max 1284 counts how often the container reached its limit, and oom_kill 1 says the kernel has already killed one process here. The last two lines split the usage: anon is the program's own memory, file is page cache. The pod was created with limits: {memory: 4Gi, cpu: "2"}.
What the kernel does at the ceiling
Everything the container touches is charged to its cgroup. That means the program's own memory: its objects, its threads' stacks, its buffers. It also means the page cache: the kernel's in-memory copies of files the container has read or written.
When the next request for memory would push the usage past memory.max, the kernel does not say no, and it does not warn. First it reclaims: it frees what it can inside this container. Only if that is not enough does it kill.
The difference between the two kinds of memory decides everything. Page cache can be dropped, because the files are still on disk. The program's own memory cannot.
The road to an OOM kill
One bar of 4,096 MiB, the container's memory limit, in four steps: 2,560 MiB of program memory and 1,024 MiB of page cache with 512 MiB free, the kernel dropping half the page cache to make room, then all of it, and finally the program memory filling the whole limit and the process being killed.
Now. The container uses 3,584 MiB of its 4,096: 2,560 MiB of its own memory and 1,024 MiB of page cache. 512 MiB is free. These are the numbers from the files above.
The program needs 1 GiB more. Only 512 MiB is free. The kernel reclaims: it drops half of the page cache. Nothing is lost, because those files are still on disk.
It grows again. 512 MiB more, and the rest of the page cache goes. Now everything in the box is the program's own memory. There is nothing left to drop.
One more allocation. The kernel cannot get under the limit, so its OOM killer picks a process in this container and sends SIGKILL. No warning, no error message: exit 137. Kubernetes records
reason: OOMKilledand restarts the container.
The bar is the whole 4 GiB the pod may use. A container full of page cache is safe: reclaim frees it. One full of its own memory is one allocation away from the kill. Reclaim also writes changed pages back to disk first, and swaps if the container may (most Kubernetes nodes run without swap).
Request and limit: two different promises
Every container in a pod can carry two numbers for memory, and two for CPU.
A request is a reservation. Kubernetes places a pod only on a node that still has room for the requests of everything already there.
A limit is the ceiling the kernel enforces. A memory limit becomes memory.max: pass it, and the OOM killer comes. A CPU limit becomes cpu.max: pass it, and you are slowed down, not killed.
Between the two there is a gap. A container may use more than it requested for as long as the node has room. But when the node itself runs short, someone has to go, and pods using more than they asked for go first. Kubernetes sorts pods into three quality of service (QoS) classes for this.
One container, three numbers
Three bars for one container: a memory request of 2 GiB, a current usage of 3 GiB, and a memory limit of 4 GiB.
Read the three bars as one container: 2 GiB is reserved for it, it is using 3, and it is killed at 4. The gigabyte between the first two bars is borrowed, and borrowed memory is the first to be called back.
Three classes: who goes first
| QoS class | When | oomscoreadj | Under node memory pressure |
|---|---|---|---|
| Guaranteed | every container has CPU and memory requests equal to its limits | -997 | rarely: its use cannot pass its request |
| Burstable | anything between: some request or limit set | min(max(2, 1000 - 1000 x request / node memory), 999) | early if it uses more than it requested |
| BestEffort | no requests or limits at all | 1000 | first: any use is above its zero request |
When a node runs out of memory, the kernel's OOM killer gives every process a score from the share of memory it uses, adds oom_score_adj, and kills the highest. So a low number in the third column is protection.
Who the OOM killer picks first
GiB = 1024 ** 3
def oom_score_adj(qos, memory_request, node_memory):
"""What the kubelet writes for a container, by the pod's QoS class."""
if qos == 'Guaranteed':
return -997
if qos == 'BestEffort':
return 1000
return min(max(2, 1000 - (1000 * memory_request) // node_memory), 999)
node = 64 * GiB
pods = [('spark-exec-1', 'Guaranteed', 16 * GiB), ('notebook', 'Burstable', 32 * GiB),
('airflow-worker', 'Burstable', 8 * GiB), ('debug-shell', 'BestEffort', 0)]
for name, qos, request in pods:
print(f"{name:<15} {qos:<11} request {request // GiB:>2} GiB -> oom_score_adj {oom_score_adj(qos, request, node)}")
Before you run it, guess which of the four pods goes first. When this 64 GiB node runs out, the debug shell goes first and the Guaranteed executor last. A Burstable pod with a small request is nearly as exposed as BestEffort: an 8 GiB request scores 875.
Java in a box: more than the heap
Spark's executors are Java programs, and Java adds a trap of its own.
A Java program keeps its objects in the heap, and you set the heap's size with -Xmx. But the heap is only part of the process. Each thread has its own stack. The compiled code needs room. So do the buffers used for network and files. All of that sits outside the heap, and all of it counts against memory.max.
So -Xmx4g in a 4 GiB pod is a kill waiting to happen. The heap may fill the whole limit, the rest has nowhere to go, and the kernel kills the process before Java can report anything.
The opposite mistake wastes memory: with no -Xmx at all, Java takes only 25% of the limit for its heap.
Three ways to size a JVM in a 4 GiB pod
Three bars on one scale: with the default 25 percent the heap is 1 GiB and most of the pod is unused; with 75 percent the heap is 3 GiB with room left for native memory; with Xmx equal to the limit, heap plus native memory overshoots the 4 GiB limit.
Compare the three bars against the 4,096 MiB line: the last one is longer than the pod. The 600 MiB outside the heap is an example: 200 threads x 1 MiB of stack, a 240 MB code cache, and 160 MiB of metaspace, buffers and GC data. A common setting is the middle bar, -XX:MaxRAMPercentage=75.
What a Spark executor pod asks for
Spark knows about the trap. It sets -Xmx itself, from spark.executor.memory, and then asks Kubernetes for a pod that is bigger than the heap. The extra room is called the overhead.
The pod's memory is a sum of up to four parts:
- the heap:
spark.executor.memory; - the overhead: a share of the heap, never under 384 MiB. The share is 10% for a Java or Scala job and 40% for a PySpark job, because Python runs outside the heap and needs the room;
- off-heap memory, if you turned it on;
- a separate allowance for Python, if you set one.
That sum is both the request and the limit. For SwiftKart's job and its 8 GiB heap: 8,192 + 0.40 × 8,192 = 8,192 + 3,276 = 11,468 MiB.
Two executor pods with the same 8g heap
Two bars on one scale: a PySpark executor whose 8 GiB heap is joined by 3,276 MiB of overhead, 2 GiB off-heap and 2 GiB for Python workers, for a 15,564 MiB pod; and a Scala executor with the same heap and 819 MiB of overhead, a 9,011 MiB pod.
Both pods have the same blue heap; everything to its right is what the pod asks for on top. Same heap, a pod 1.7 times larger. The 384 MiB minimum applies only below a 960 MiB heap for PySpark, or 3,840 MiB for JVM jobs.
How many executors fit on a node
allocatable_mib, allocatable_cores = 60 * 1024, 15 # an example 64 GiB, 16-core node after system reservations
cores = 2
jobs = {
'Scala, 8g': 8192 + max(int(0.10 * 8192), 384),
'PySpark, 8g': 8192 + max(int(0.40 * 8192), 384),
'PySpark, 8g + 2g off-heap + 2g Python': 8192 + max(int(0.40 * 8192), 384) + 2048 + 2048,
'PySpark, 16g': 16384 + max(int(0.40 * 16384), 384),
}
for name, pod_mib in jobs.items():
fit = min(allocatable_mib // pod_mib, allocatable_cores // cores)
print(f"{name:<40} pod {pod_mib:>6,} MiB -> {fit} per node")
This is last night's Pending. Doubling the heap of the PySpark job to 16g makes a 22,937 MiB pod: two per node instead of three, and the pods that no longer fit wait with 0/5 nodes are available: 5 Insufficient memory. CPU would allow 7 (15 cores at 2 per executor), so memory decides.
CPU limits make you wait
Memory has a cliff. CPU has a brake.
A CPU limit is a budget of running time per window. A limit of 2 CPUs means 200 ms of CPU time in every 100 ms window, shared by all the container's threads. Four busy threads spend that in 50 ms. Then every one of them stands still until the window ends. That is throttling.
On average it looks like 2 cores of work. But every burst is cut short: a request that needs 60 ms of CPU takes 110 ms, pauses stretch, and the "I am alive" messages Spark executors send arrive late.
So many teams give batch jobs a CPU request and no CPU limit: idle cores get used. Spark on Kubernetes does that unless you tell it otherwise.
Four threads under a 2-CPU limit
A timeline of 300 milliseconds and four threads: in every 100 millisecond period each thread runs for 50 milliseconds and is then throttled for the remaining 50, because together they use the 200 millisecond quota.
Time runs left to right, one row per thread. The quota is 200 ms per 100 ms period, and 4 threads x 50 ms uses it all. For half of every period, the whole container is frozen.
Read throttling from cpu.stat
cpu_stat = """usage_usec 2520000000
user_usec 2380000000
system_usec 140000000
nr_periods 36000
nr_throttled 9000
throttled_usec 360000000"""
stat = {key: int(value) for key, value in (line.split() for line in cpu_stat.splitlines())}
print(f"throttled in {stat['nr_throttled'] / stat['nr_periods']:.0%} of periods")
print(f"waited {stat['throttled_usec'] / 1e6:,.0f} s in all, {stat['throttled_usec'] / stat['nr_throttled'] / 1000:.0f} ms per throttled period")
print(f"used {stat['usage_usec'] / 1e6:,.0f} s of CPU in {stat['nr_periods'] / 10:,.0f} s: {stat['usage_usec'] / (stat['nr_periods'] * 100000):.2f} cores on average")
One hour of a container limited to 2 CPUs. An average of 0.70 cores looks safe, yet a quarter of all 100 ms windows were cut short by 40 ms: the work comes in bursts. Averages hide throttling. These counters do not.
Which kill is it, and which knob to turn
| Evidence | What ran out | Turn |
|---|---|---|
| java.lang.OutOfMemoryError: Java heap space in the executor log; pod not OOMKilled | the JVM heap | spark.executor.memory, or fewer cores per executor (Lesson 12.8) |
| pod OOMKilled, exit 137, GC logs show the heap half empty | memory outside the heap: native, Netty, Python workers | spark.executor.memoryOverhead, or set spark.executor.pyspark.memory |
| MemoryError raised inside a Python worker | the spark.executor.pyspark.memory cap | spark.executor.pyspark.memory, or smaller batches into pandas UDFs |
| pod Evicted, not OOMKilled | the node, under memory pressure | requests that match real use; fewer pods per node |
| pod Pending: Insufficient memory | no node fits the request | a smaller executor, or bigger nodes |
SwiftKart's job is the second row. On YARN the same overhead problem reads Container killed by YARN for exceeding memory limits, and the fix is the same knob.
Raising spark.executor.memory is the reflex, and often the wrong fix for an OOMKilled executor. The heap was not what ran out. Doubling it doubles the overhead too, but it also doubles the pod: half as many executors fit on a node, the rest stay Pending, and the new heap sits unused while the Python workers that caused the kill get no more room of their own. Read the evidence first. When the pod is OOMKilled with a half-empty heap, raise spark.executor.memoryOverhead or set spark.executor.pyspark.memory.
Remember: the pod is bigger than the heap. Kubernetes counts heap plus overhead, and the overhead is where Python lives.
Numbers to remember
| What | Value | Notes |
|---|---|---|
| cgroup v2 files | under /sys/fs/cgroup | Memory: memory.max, memory.current, memory.high, memory.events (max, oom, oomkill), memory.stat (anon, file). CPU: cpu.max (quota period in microseconds; max 100000 when unlimited), cpu.stat (usageusec, nrperiods, nrthrottled, throttledusec). |
| memory.high | a softer line | Crossing it slows the container down with forced reclaim. It never kills. |
| Units | Mi, Gi and M, G | Mi and Gi are powers of two, M and G powers of ten. Lower-case m means milli: memory: 400m asks for 0.4 bytes. For CPU, 500m is half a core. |
| A limit with no request | request = limit | Kubernetes copies the limit into the request. |
| Node-pressure eviction | memory.available<100Mi | A different mechanism from the OOM killer: the kubelet (Kubernetes' agent on each node), not the kernel, evicts whole pods (status Evicted) when the node's free memory falls under this threshold. |
| JVM heap with no -Xmx | 25% of the limit | -XX:MaxRAMPercentage. The JVM has read its cgroup's limits since JDK 10 (-XX:+UseContainerSupport, on by default on Linux). |
| Outside the Java heap | 1 MiB per thread stack; code cache up to 240 MB | Also metaspace (unlimited by default), NIO direct buffers, GC structures and native libraries. Measure with -XX:NativeMemoryTracking=summary and jcmd <pid VM.nativememory summary. |
| Spark's overhead | max(factor x heap, 384 MiB) | spark.executor.memoryOverhead. The factor, spark.executor.memoryOverheadFactor, is 0.10 for JVM jobs and 0.40 for PySpark and R jobs on Kubernetes. The minimum is spark.executor.minMemoryOverhead since Spark 4.0. |
| Spark's other parts | added to the pod when set | spark.memory.offHeap.size (if spark.memory.offHeap.enabled is true) and spark.executor.pyspark.memory. Spark sets -Xmx itself, so MaxRAMPercentage does not apply. |
| Spark and CPU | request = spark.executor.cores | A CPU limit exists only if you set spark.kubernetes.executor.limit.cores. With no CPU limit the pod is Burstable, not Guaranteed. |
| Throttling in Prometheus | containercpucfsthrottledperiodstotal | Compare it with containercpucfsperiodstotal: the same ratio as nrthrottled to nrperiods. |
The arithmetic is the same wherever Spark meets Kubernetes: the Spark Operator, Amazon EMR on EKS, Dataproc on GKE. A common setup sizes executors to divide a node's allocatable memory and cores evenly, sets spark.executor.memoryOverhead for PySpark from measured peaks, not from the 0.40 default, and leaves CPU limits off.
What changed at SwiftKart
You put spark.executor.memory back to 8g. The heap had never been full.
What ran out was the room outside it, where the Python workers live. You measured their peak and set spark.executor.memoryOverhead to match. The pod grew a little, not to double. Every executor fits on a node again, nothing is Pending, and nothing has been OOMKilled since.
Nora's line for the runbook: "A kill is a question. Which memory ran out?"
That closes this module. Your pipeline is in Git, tested on every pull request, packed into an image, and running under limits you can read. What it needs next is an engine for data too big for one machine. Module 11, PySpark DataFrames, starts with SparkSession and DataFrames.
In one line
A container's limits are numbers in its cgroup files: past the memory limit the kernel reclaims what it can and then kills (exit 137, OOMKilled), while a CPU limit only slows you down; requests reserve room and decide who is killed first, and a Spark executor pod is its heap plus an overhead, which is where Python lives.
Interview corner
Spark executors on Kubernetes keep dying with exit code 137. How do you diagnose and fix it?
137 is SIGKILL. First I tell the kills apart: kubectl describe pod showing OOMKilled means the kernel hit memory.max; Evicted means the kubelet evicted it under node pressure; a Java heap space error with no OOMKilled is the heap itself. For OOMKilled with a heap that GC logs show half empty, the memory outside the heap ran out: for PySpark that is often the Python workers, which count against the overhead. The pod is heap + max(0.40 x heap, 384 MiB) for PySpark, so 8g is an 11,468 MiB pod; I would raise spark.executor.memoryOverhead or set spark.executor.pyspark.memory, not the heap, and check the new pod still fits the node.
Explain requests, limits and QoS classes. How would you set them for a batch job and for a service?
Requests are what the scheduler reserves to place a pod; limits are enforced by the kernel, memory by OOM kill and CPU by throttling. Equal requests and limits for CPU and memory in every container make a pod Guaranteed (oom_score_adj -997), nothing at all makes it BestEffort (1000), anything else Burstable, scored by its request. For a memory-hungry batch job I set memory request equal to limit at the measured peak plus margin, so it is never overcommitted, and a CPU request with no CPU limit so it can use idle cores. For a latency-sensitive service I would consider Guaranteed, accepting that a CPU limit can throttle it.
How does a JVM decide its heap size in a container, and how should you size it?
A container-aware JVM (JDK 10 and later, UseContainerSupport on by default) reads the cgroup memory limit and, with no -Xmx, takes MaxRAMPercentage of it, 25% by default, so a 4 GiB pod gets a 1 GiB heap. Setting -Xmx to the full limit gets the pod OOM-killed, because thread stacks, metaspace, the code cache and direct buffers live outside the heap. I set -XX:MaxRAMPercentage around 70 to 75, measure native use with Native Memory Tracking, and adjust. Spark is the exception: it sets -Xmx from spark.executor.memory and adds the overhead to the pod instead.
A service has a CPU limit of 2 and its p99 latency is bad, but average CPU use is 0.7 cores. What is going on?
Probably CFS throttling. The limit becomes a quota of 200 ms of CPU per 100 ms period; bursts with several busy threads use it up early in the period and then every thread waits until the period ends, so a request needing 60 ms of CPU can take over 100 ms. The average hides it. I would read cpu.stat (nr_throttled over nr_periods, throttled_usec) or container_cpu_cfs_throttled_periods_total, and then raise or remove the CPU limit while keeping a sensible request, or cut the number of busy threads, for example the JVM's GC threads with -XX:ActiveProcessorCount.