Under the Hood 10: The Linux OOM Killer: Why Your Process (or Pod) Got Killed
Why Linux kills processes when memory runs out, how the OOM killer chooses its victim, and why Kubernetes pods get OOMKilled while the node still has free memory. With the exact commands to prove it and fix it.
It's Friday evening, two hours after a routine deploy. Your payments-api pods have restarted seven times, dropping in-flight checkout requests and firing bursts of 502 errors across the ingress layer.
kubectl get pods -l app=payments-api
NAME READY STATUS RESTARTS AGE
payments-api-7d9f8c6b5-x2k4q 1/1 Running 7 (4m ago) 2h
payments-api-7d9f8c6b5-q8h1m 1/1 Running 6 (11m ago) 2h
You pull up Grafana, and the memory chart sits at a calm 62% of the container limit, nowhere near 100%. Someone in the incident channel immediately rules out memory, so you inspect the pod status directly to see what actually happened:
kubectl describe pod payments-api-7d9f8c6b5-x2k4q
...
Last State: Terminated
Reason: OOMKilled
Exit Code: 137
It was memory after all. Your metrics pipeline scrapes container usage every 30 seconds, while a new report-export endpoint allocated 400 MiB in under two seconds and triggered a kill before the next scrape ran. The kernel saw the spike; your dashboard never did. Fixing OOM kills permanently rather than guessing a larger limit and hoping it holds requires understanding how the Linux kernel accounts for memory and decides what dies when limits are breached.
The Misconception: "OOM Means the Node Ran Out of Memory"
Most engineers picture an OOM event as a single scenario where the underlying server fills up with data and the kernel starts killing processes to survive. In Kubernetes, however, memory-related terminations stem from three distinct mechanisms, each with different triggers, actors, and diagnostic trails:
These three events are not escalating stages of the same code path. A cgroup OOM is kernel-enforced isolation inside a container's control group, a global OOM is a node-wide physical memory exhaustion event in kernel space, and Pod eviction is a proactive user-space policy enforced by the kubelet.
Because they operate independently, a node under gradual memory pressure can have Pods evicted by the kubelet without the kernel ever invoking the OOM killer. Conversely, a sudden allocation burst can exhaust physical pages and trigger a kernel OOM kill faster than the kubelet's housekeeping loop can evict Pods. In Kubernetes, cgroup OOMs are by far the most common case: a node can sit with 40 GiB of unallocated RAM while a container gets killed for crossing a 512 MiB limit.
Why Linux Needs an OOM Killer: Memory Overcommit
When a process calls malloc() or mmap() to request anonymous memory, Linux rarely reserves physical RAM pages on the spot. Instead, the kernel grants virtual address space immediately and backs those addresses with physical page frames lazily when the process actually reads or writes to them, triggering a minor page fault.
This behavior is governed by Linux's memory overcommit policy, which defaults to heuristic overcommit (0):
cat /proc/sys/vm/overcommit_memory
# 0 = heuristic overcommit (default)
# 1 = always overcommit
# 2 = strict overcommit (never exceed CommitLimit)
grep -E 'CommitLimit|Committed_AS' /proc/meminfo
Overcommitting works much like an airline selling 190 tickets for a 180-seat flight because historical data shows several passengers miss their connection. Most of the time, the plane takes off without issue because processes routinely allocate large virtual buffers that they never fully touch. On the rare occasion when every passenger shows up at the gate or every process faults in its virtual pages simultaneously, the kernel has already promised more physical memory than exists. When page reclaim cannot free enough frames to honor a page fault, the kernel must forcibly terminate a process to recover pages and keep the system alive.
What Happens Before the Kill: Reclaim and cgroup Boundaries
The OOM killer is strictly a fallback when all non-destructive recovery options fail. Before terminating any task, the kernel runs page reclaim: dropping clean file-backed page cache, shrinking reclaimable kernel slab caches (such as dentries and inodes), flushing dirty pages to disk, and swapping out anonymous pages if swap is enabled. Inside a cgroup v2 hierarchy, this lifecycle follows a predictable sequence against the container's configured thresholds:
Container allocates memory
│
▼
memory.high configured and exceeded?
│
├── yes ──► throttling + direct reclaim
│
▼
memory usage approaches memory.max
│
▼
Reclaim inside this cgroup
│
├── enough freed ──► allocation succeeds
│
└── not enough
│
▼
[ cgroup OOM handling ]
│
▼
[ select eligible task(s) ]
On cgroup v2, memory.high acts as a soft throttling boundary that slows down allocating threads and forces direct reclaim without killing processes, whereas memory.max (mapped from your Kubernetes container resources.limits.memory) is the hard ceiling. On older cgroup v1 nodes, Kubernetes enforces this hard ceiling through memory.limit_in_bytes.
Two accounting details regularly trip up engineering teams during cgroup investigations. First, file-backed page cache is charged to the container's cgroup, which means reading a large file pushes memory.current up, but because clean page cache is reclaimable, the kernel can silently discard it under pressure without triggering an OOM kill. Second, tmpfs volumes including Kubernetes emptyDir volumes configured with medium: Memory and /dev/shm are backed by RAM and billed as shared memory (shmem) inside the cgroup. Unlike clean file cache, tmpfs pages cannot be dropped without losing data, so writing temporary files into a memory-backed volume consumes your container limit just like an application heap leak.
How the OOM Killer Picks a Victim
When reclaim fails, the kernel's oom_badness() function evaluates every eligible process in the OOM scope and assigns each a score. The baseline score reflects the proportion of allowed memory (resident set size, page tables, and swap usage) the task consumes relative to the available memory in that context, either the cgroup's memory.max during a cgroup OOM or total allocatable node RAM during a global OOM. The kernel then adds the process's oom_score_adj value to shift its priority:
oom_score ≈ (process memory usage / allowed memory scope) × 1000
+ oom_score_adj
Every Linux process exposes both its live calculated score and its adjustment offset under /proc:
cat /proc/<pid>/oom_score
cat /proc/<pid>/oom_score_adj
oom_score_adj accepts integers from -1000 to +1000. Positive values penalize a process and make it an earlier target, negative values shield it, and -1000 exempts the task from the OOM killer entirely. You can list the top OOM candidates on any Linux host by sorting /proc entries by score:
for p in /proc/[0-9]*; do
printf "%6s %6s %8s %s\n" "$(cat $p/oom_score 2>/dev/null)" \
"$(cat $p/oom_score_adj 2>/dev/null)" "${p#/proc/}" "$(cat $p/comm 2>/dev/null)"
done | sort -rn | head
Crucially, the candidate pool is bounded by the type of OOM. During a cgroup OOM, the kernel only evaluates tasks inside the specific cgroup that breached memory.max, ensuring a runaway container cannot cause the kernel to kill an unrelated neighbor on the same node.
cgroup v2 and Group OOM Handling
cgroup v2 introduces memory.oom.group, a boolean control file that changes how multi-process containers behave during an OOM event. When memory.oom.group is set to 1, the kernel treats the entire cgroup as an indivisible unit: if any process triggers an OOM kill, the kernel sends SIGKILL to every eligible process in that cgroup and its descendants (except tasks pinned at oom_score_adj = -1000).
Modern Kubernetes releases enable this by default on cgroup v2 nodes via the kubelet setting singleProcessOOMKill: false. This prevents a broken, half-alive state where the kernel kills a background worker or helper process inside a container while the main process continues running without it. If you run legacy multi-process containers that intentionally supervise and restart child workers, setting singleProcessOOMKill: true in the kubelet configuration restores single-process termination.
How Kubernetes Uses oom_score_adj: QoS Classes
During node-level memory pressure, the kubelet relies on oom_score_adj to protect high-priority workloads over best-effort batch jobs. Whenever a Pod is scheduled, Kubernetes assigns it one of three Quality of Service (QoS) classes based on its container resource specifications:
You can inspect any Pod's assigned QoS class directly with kubectl:
kubectl get pod payments-api-7d9f8c6b5-x2k4q \
-o jsonpath='{.status.qosClass}{"\n"}'
Keep in mind that QoS classes govern victim ordering during a node-wide global OOM. Giving a Pod Guaranteed QoS shields it from being sacrificed when another workload starves the node, but it offers zero immunity against the container's own memory.max limit. A Guaranteed container that exceeds its memory limit will still be OOM-killed immediately.
Reading the Evidence: Confirming an OOM Kill
Seeing exit code 137 on a terminated container does not automatically prove an OOM kill occurred. Under POSIX exit conventions, codes above 128 indicate termination by a signal (128 + signal_number), so 137 (128 + 9) simply means the process received SIGKILL. That signal could have come from the OOM killer, an operator running kill -9, or the container runtime forcibly terminating a container that ignored SIGTERM past terminationGracePeriodSeconds.
Always verify the explicit termination reason reported by the kubelet:
kubectl get pod payments-api-7d9f8c6b5-x2k4q \
-o jsonpath='{range .status.containerStatuses[*]}{.name}{"\t"}{.lastState.terminated.reason}{"\t"}{.lastState.terminated.exitCode}{"\n"}{end}'
Look for the pair OOMKilled and 137. To distinguish a container cgroup breach from a node-level exhaustion event, check cluster-wide SystemOOM events and inspect the kernel ring buffer on the host node:
kubectl get events -A --field-selector reason=SystemOOM
sudo dmesg -T | grep -iE 'killed process|out of memory'
sudo journalctl -k --since "2 hours ago" | grep -i oom
A container limit breach logs a cgroup-scoped message, whereas host exhaustion logs a global OOM line:
# cgroup OOM
Memory cgroup out of memory: Killed process 48211 (java) total-vm:5243120kB, anon-rss:1046528kB, file-rss:18764kB, shmem-rss:0kB, UID:1000 pgtables:2412kB oom_score_adj:984
# Global OOM
Out of memory: Killed process 3120 (node) total-vm:2961044kB, anon-rss:1873220kB, ...
Pay close attention to the resident memory breakdown in that log line: a high anon-rss points to application heap or native allocations, while an unusually high shmem-rss indicates heavy tmpfs or shared-memory usage.
Finding the Spike Your Dashboard Missed
When time-series graphs miss a transient memory spike between scrapes, the cgroup v2 filesystem on the node retains the exact high-water mark and event counters. Locate the container's host PID via crictl, resolve its cgroup v2 path, and inspect its memory control files:
CID=$(sudo crictl ps --name payments-api -q | head -1)
PID=$(sudo crictl inspect --output go-template --template '{{.info.pid}}' "$CID")
CG=/sys/fs/cgroup$(awk -F: '$1=="0"{print $3}' /proc/$PID/cgroup)
cat $CG/memory.max
cat $CG/memory.current
cat $CG/memory.peak
grep -E '^(anon|file|shmem) ' $CG/memory.stat
cat $CG/memory.events
Each file answers a specific forensic question: memory.max shows the configured hard limit, memory.current shows instantaneous usage, memory.peak (Linux 5.19+) records the highest memory footprint reached since the cgroup was created, memory.stat breaks down anonymous heap (anon), page cache (file), and shared memory (shmem), and memory.events tracks cumulative oom, oom_kill, and oom_group_kill counters.
Comparing memory.current (620 MiB) against memory.peak (1021 MiB) on a 1 GiB container immediately exposes sub-scrape allocation bursts that Grafana smooths over. Note that because memory.events is hierarchical on cgroup v2, inspecting the parent Pod-level cgroup (when present in your runtime's cgroup driver layout) preserves aggregate OOM counters even after an individual container restarts and recreates its leaf cgroup.
Alerting on OOM Events and Memory Pressure
Because gauge metrics only sample point-in-time usage, you should never rely solely on a "memory > 85%" alert to catch OOM kills. Pair utilization dashboards with counter-based alerts from cAdvisor and kube-state-metrics that fire whenever the kernel increments an OOM counter or records an OOMKilled termination:
increase(container_oom_events_total[15m]) > 0
kube_pod_container_status_last_terminated_reason{reason="OOMKilled"} == 1
Combine those post-mortem counters with Linux Pressure Stall Information (PSI) metrics (container_memory_psi_some_seconds_total / memory.pressure). PSI measures the percentage of wall-clock time tasks spend stalled waiting for page reclaim, giving you an early warning when reclaim is struggling before the kernel crosses memory.max and invokes the OOM killer.
Four Real-World Production Scenarios
1. The Limit Is Too Low (or the App Is Leaking)
When memory.stat shows anon growing monotonically after every restart until it hits memory.max hours or days later, your workload either has a genuine steady-state working set larger than its limit or an unbounded memory leak. Capture a heap or allocation profile (pprof, jcmd, or V8 heap snapshots) before bumping limits; raising memory.max on a true leak simply delays the next crash.
2. The Sub-Scrape Memory Spike
This was the root cause in our payments-api incident: dashboards hovered at 62%, while memory.peak hit 1.0 GiB against a 1.0 GiB limit. Short-lived bursts typically happen when an endpoint loads an entire SQL result set into memory, deserializes a massive JSON payload at once, warms an in-memory cache, or processes too many heavy exports concurrently. Rather than over-provisioning every replica for a rare spike, stream database cursors, paginate large responses, cap request concurrency, or offload heavy batch exports to dedicated worker queues.
3. The Runtime Doesn't Respect the Container Boundary
Managed runtimes frequently misjudge available memory inside containers if configured carelessly. On the JVM, setting -Xmx1g inside a 1 GiB container guarantees an OOM kill because the heap leaves zero headroom for Metaspace, thread stacks, direct byte buffers, JIT code cache, and native libraries. Instead, use percentage-based ergonomics on modern container-aware JDKs (JDK 11.0.16+ and 17+ fully support cgroup v2) so native allocations have breathing room:
# Leave ~25% headroom for Metaspace, thread stacks, and direct buffers
JAVA_TOOL_OPTIONS="-XX:MaxRAMPercentage=75.0"
# Go 1.19+: trigger aggressive GC before hitting the cgroup hard limit
GOMEMLIMIT=900MiB
# Node.js: cap V8 old-space heap below the container limit
NODE_OPTIONS="--max-old-space-size=768"
4. The Disk That Was Actually RAM
If anon memory remains completely flat while memory.current climbs steadily toward memory.max, check shmem in memory.stat. Applications writing temporary uploads, SQLite databases, or scratch files to /dev/shm or a Kubernetes emptyDir volume with medium: Memory are consuming RAM billed directly to the container's cgroup. Either switch those scratch paths to disk-backed ephemeral storage or enforce an explicit sizeLimit on the memory-backed volume.
How to Fix OOM Kills Properly
Effective remediation starts with sizing limits from empirical evidence rather than guesswork. Measure memory.peak and anon working-set usage under realistic peak traffic and concurrency, then add deliberate headroom for runtime overhead and traffic bursts. For latency-sensitive services, set resources.requests.memory equal to resources.limits.memory (alongside matching CPU requests and limits) so the Pod receives Guaranteed QoS and stays protected during node-level contention.
Make sure your language runtime knows where the container boundary sits using MaxRAMPercentage, GOMEMLIMIT, or --max-old-space-size, and back those settings up with counter alerts on container_oom_events_total and PSI memory pressure. Equally important, resist the urge to work around OOM kills by forcing oom_score_adj = -1000 on application Pods or blindly doubling memory limits. Making one workload immune to the OOM killer does not create more physical RAM it merely forces the kernel to kill critical system daemons or neighboring Pods when pressure hits.
5 Common Mistakes Engineers Make
- Treating every exit code
137as an OOM kill: Exit code137only proves the process receivedSIGKILL. Always inspectlastState.terminated.reasonanddmesgbefore changing memory limits. - Trusting 30-second Prometheus graphs exclusively: Sub-second allocation spikes routinely cross
memory.maxand terminate a container between scrape intervals. Checkmemory.peakandmemory.eventson the host cgroup. - Setting
-Xmxequal to the container memory limit: The Java heap is only one slice of a JVM's RSS. Native memory, thread stacks, and direct buffers will push total usage pastmemory.max. - Forgetting
tmpfsand/dev/shmaccounting: Files written to memory-backedemptyDirvolumes count against the container's memory cgroup and cannot be reclaimed like clean page cache. - Raising limits without inspecting
memory.stat: Blindly increasingmemory.maxmasks leaks, concurrency bottlenecks, and misconfigured runtimes until the next traffic surge hits the new ceiling.
The OOM Investigation Cheat Sheet
Key Takeaways
- Overcommit makes OOM necessary: Linux commits physical RAM lazily on page faults, requiring an OOM killer when physical pages run short after reclaim fails.
- Container OOMs are scoped to the cgroup: An
OOMKilledPod usually means the container hit its ownmemory.maxboundary, not that the host node ran out of memory. - Victim selection is deterministic: The kernel ranks tasks using proportional memory usage plus
oom_score_adj, confined to the offending cgroup during container OOMs. - QoS protects against node pressure, not self-inflicted spikes:
GuaranteedPods receiveoom_score_adj = -997for node-level survival, but are still killed if they cross their ownmemory.max. - Exit code
137requires verification: ConfirmReason: OOMKilledand inspectdmesg,memory.peak, andmemory.statto separate anonymous heap spikes fromshmemusage. - Eviction and OOM killing are separate layers: Kubelet eviction is a proactive user-space safeguard, whereas OOM killing is immediate kernel enforcement.
Final Thoughts
The Linux OOM killer is neither a kernel bug nor a random crash it is the kernel enforcing hard resource guarantees at the exact moment page reclaim fails, and an allocation still has to be satisfied. Every OOMKilled container is a clear diagnostic signal pointing to a specific boundary in your memory hierarchy.
Start with the Pod's termination reason, check dmesg to confirm whether the breach occurred inside a container cgroup or across the entire node, and inspect memory.peak, memory.stat, and memory.events on the host to catch the spikes your monitoring dashboards missed. Once you separate steady-state growth, transient bursts, runtime ergonomics, and tmpfs usage, OOM kills stop being mysterious Friday-night restarts and become one of the most predictable issues to fix in Kubernetes.
If you haven't read it yet, check out Under the Hood #6: Linux Memory Pressure Explained, which covers the page reclaim and PSI mechanics that run right before the kernel reaches for the OOM killer.