Skip to content
masdzub.com
~/articles/linux — one from the notebook

Debugging OOM Kills on Linux: Reading dmesg, cgroup Memory Limits, and vm.overcommit_memory

A practical guide to diagnosing Linux OOM kills: parse dmesg reports, check cgroup v1/v2 memory limits, and understand vm.overcommit_memory behavior.

masdzub@website:~$ cat ~/articles/debugging-oom-kills-on-linux-reading-dmesg-cgroup-memory-limits-and-vmovercommitmemory.aspx.md
# 1 file · 19 min read · topic: linux · status: published

Introduction

When a Linux process disappears with Killed and no stack trace, the kernel’s OOM (out of memory) killer terminated it, and the full explanation sits in the kernel ring buffer. Run dmesg -T | grep -i -E "killed process|out of memory" or journalctl -k --since "1 hour ago" and you will find the exact process, its memory footprint, the cgroup it belonged to, and the limit that triggered the kill. Most OOM investigations end in under ten minutes once you know how to read that report; the rest of this article walks through the report line by line, explains how cgroup memory limits change the picture, and covers what vm.overcommit_memory actually does to your risk of getting killed in the first place.

The three usual suspects look different in the logs. A global OOM kill (the whole machine ran out of memory and swap) produces the classic Out of memory: Killed process banner with a long memory state dump. A cgroup-limited kill produces Memory cgroup out of memory: Killed process and names the cgroup. A vm.overcommit_memory=2 system refuses allocations instead of killing, so you see Cannot allocate memory errors from malloc in application logs rather than a kernel kill. Knowing which of the three you are facing determines the fix.

How the OOM killer decides whom to kill

The kernel invokes the OOM killer when a memory allocation cannot be satisfied after reclaim has failed. The path matters. On a global OOM, __alloc_pages exhausts reclaim, compaction, and the shrinkers, then calls out_of_memory() in mm/oom_kill.c. The killer scans all eligible tasks and picks the one with the highest badness score. That score is roughly the process’s RSS plus swap usage plus page table size, scaled by oom_score_adj, with root processes getting a small discount.

The cgroup path is different and trips up a lot of people. If a workload hits memory.max in its cgroup and reclaim within that cgroup fails, the kernel runs the OOM killer restricted to tasks inside that cgroup only. The system as a whole may have gigabytes free, yet your container dies. This is why “the box had 40 GB free, why did it kill my 2 GB Java process” is such a common question: the answer is almost always a cgroup limit, not global pressure.

Selection also respects oom_group. On cgroup v2, if the killed task belongs to a cgroup with memory.oom.group=1, the kernel kills every process in that cgroup instead of one victim. This is deliberate: for containers, killing one thread out of twenty usually leaves the service broken anyway, so a full-group kill gives the supervisor a clean restart signal.

One more selection detail worth knowing: the killer never kills a task with oom_score_adj set to -1000 (the value oom_score_adj uses for “unkillable”), and it prefers tasks that share the memory context of the allocation requester in some paths. It also skips kthreadd and other kernel threads. If everything eligible is protected, you will see Out of memory and no killable processes in the log, which means the system thrashes instead of recovering. That state is worse than a kill.

Reading the OOM report in dmesg, line by line

A real report (trimmed from a 4 GB VM running a leaky Node.js service) looks like this:

node invoked oom-killer: gfp_mask=0xcc0(GFP_KERNEL), order=0, oom_score_adj=0
CPU: 1 PID: 2317 Comm: node Kdump: loaded Tainted: G ...
Mem-Info:
active_anon:902113 inactive_anon:88012 isolated_anon:0
active_file:112 inactive_file:89 isolated_file:0
unevictable:0 dirty:0 writeback:0 ...
Node 0 DMA free:15756kB min:64kB ...
Node 0 Normal free:22160kB min:2244kB low:2804kB high:3364kB ...
swap_free: 0kB
858345 pages RAM
0 pages reserved
0 pages hwpoisoned
[ pid ] uid tgid total_vm rss rss-anon rss-file shmem-pfswap oom_score_adj name
[ 856] 0 856 10421 145 0 145 0 0 systemd-journal
[ 1201] 998 1201 318872 21904 21000 904 0 0 node
[ 2317] 998 2317 812445 378812 370000 8812 0 0 node
Out of memory: Killed process 2317 (node) total-vm:3249780kB, anon-rss:1480000kB, shmem-rss:0kB, UID 998, pgtables:7524kB
oom_reaper: reaped process 2317 (node), now anon-rss:0kB, user-rss:0kB

Work through it in this order:

First, the header line. node invoked oom-killer names the process whose allocation failed, which is not necessarily the process that gets killed. gfp_mask tells you the allocation type; GFP_NOWAIT or GFP_ATOMIC failures can trigger OOM handling without the caller being the memory hog. oom_score_adj=0 means the invoking process had no protection adjustment.

Second, the free memory lines. Node 0 Normal free:22160kB min:2244kB shows the zone below its min watermark, meaning even the page allocator’s emergency reserve is gone. If swap_free: 0kB, swap was already full. This section tells you whether the kill was a genuine whole-system exhaustion or something else.

Third, the task table. It is sorted by badness, so the top entry is the intended victim. The columns that matter are rss-anon (anonymous memory, the stuff that cannot be dropped), rss-file (page cache mapped from files, cheap to reclaim), and oom_score_adj. In the example, PID 2317 holds 370 MB of anonymous RSS versus 21 MB for the other node process, so the choice is correct even though both share a name. A common false conclusion is blaming the top process when the top process is merely the largest legitimate consumer while a short-lived fork did the actual damage and has already exited.

Fourth, the kill line: Out of memory: Killed process 2317 (node) total-vm:3249780kB, anon-rss:1480000kB. Note the mismatch between total-vm (3.2 GB of virtual address space) and anon-rss (1.4 GB resident). Virtual size is nearly meaningless for OOM diagnosis; a 64-bit process reserves address space freely. Judge by anon-rss and the pgtables value.

Fifth, oom_reaper: reaped process 2317. Since kernel 4.14 the reaper asynchronously frees the victim’s anonymous memory without waiting for it to exit. If you do not see a reaper line and the victim hangs in D state (uninterruptible sleep, often stuck on NFS or a FUSE mount), memory is not actually freed and the killer may fire again for the next allocation.

To pull the full report rather than the truncated dmesg default:

Terminal window
sudo dmesg -T | grep -A 60 "invoked oom-killer" | head -120
# or, on systemd systems, with boot context:
journalctl -k -b -g "out of memory" --no-pager

The -g grep flag on journalctl matches kernel messages across the current boot, which is more reliable than dmesg when the ring buffer has rotated past the event. If the machine rebooted after the kill (some clusters run kernel.panic_on_oom=1), check the previous boot with journalctl -k -b -1.

cgroup v2 memory limits: memory.max, memory.events, and oom_group

Modern distributions (Debian 11+, Ubuntu 21.10+, RHEL 9, Fedora 31+) default to cgroup v2, unified hierarchy. Every service, container, and session lives in a cgroup under /sys/fs/cgroup/. The controls that matter for OOM:

/sys/fs/cgroup/system.slice/myservice.service/
├── memory.max # hard limit, "max" means unlimited
├── memory.high # soft throttle limit, triggers reclaim not kills
├── memory.current # current usage
├── memory.events # counters: oom, oom_kill, max, high
├── memory.oom.group # kill whole group on OOM
└── memory.swap.max # swap limit for this cgroup

When a cgroup hits memory.max, the kernel first tries to reclaim pages belonging to that cgroup (dropping clean file cache, swapping anonymous pages if the cgroup has swap access). If reclaim cannot free enough, it OOM-kills inside the cgroup. The dmesg report then reads Memory cgroup out of memory: Killed process ... and includes an oom-kill: constraint line showing CONSTRAINT_MEMCG.

Check whether a cgroup has been OOM-killed without digging through dmesg:

Terminal window
CG=/sys/fs/cgroup/system.slice/myservice.service
cat $CG/memory.events
# high 0
# max 341
# oom 2
# oom_kill 2

oom 2 means the OOM killer ran twice inside this cgroup; oom_kill 2 means two processes (or group kills) actually died. The max counter counts allocations that failed and were retried because of the limit, which is a leading indicator: a rising max count with zero oom_kill means the workload is bumping against the ceiling and reclaim is still coping. Watch that number before it becomes an oom_kill number.

To find which cgroup a dead PID lived in, you need the PID before it dies, or a supervisor log. After the fact, journalctl on systemd systems shows the unit:

systemd[1]: myservice.service: A process of this unit has been killed by the OOM killer.

For containers, the equivalent is visible in the runtime’s events (docker events --filter event=oom or crictl events) plus the kernel log.

A practical debugging loop for a service that keeps dying:

Terminal window
# 1. Watch usage against the limit live
CG=$(systemd show -p ControlGroup --value myservice.service)
watch -n1 "cat /sys/fs/cgroup/$CG/memory.current /sys/fs/cgroup/$CG/memory.max"
# 2. See what is inside the cgroup, sorted by RSS
for pid in $(cat /sys/fs/cgroup/$CG/cgroup.procs); do
printf "%s %s\n" "$pid" "$(grep VmRSS /proc/$pid/status 2>/dev/null)"
done | sort -k2 -rn -t' ' | head
# 3. Confirm the kill source
journalctl -k -g "Memory cgroup out of memory" --no-pager | tail -5

Two cgroup v2 behaviors that change your diagnosis. First, memory.high does not kill. Crossing it throttles the workload via reclaim pressure, which shows up as latency spikes and some throttled events in memory.stat (pgscan, pgsteal under the cgroup), not as a kill. If your service is slow but alive, check memory.events for high counts. Second, swap interacts with the limit: a cgroup with memory.swap.max unset shares the system swap pool, and kernel 5.19+ added memory.swap.high. A cgroup can OOM on memory.max even when swap is technically available if memory.swap.max is already saturated, so read both counters.

cgroup v1 differences you will still hit in the wild

Plenty of production hosts still run cgroup v1 (RHEL 7, CentOS 7, older Kubernetes nodes, and any system booted with systemd.unified_cgroup_hierarchy=0). The model differs in ways that matter for debugging. Memory and swap are separate controllers, so limits live in two places:

/sys/fs/cgroup/memory/myservice/
├── memory.limit_in_bytes # hard limit
├── memory.usage_in_bytes # current usage
├── memory.failcnt # times the limit caused a failure
├── memory.oom_control # 0 = OOM killer active, 1 = kill disabled
└── memory.memsw.limit_in_bytes # RAM+swap combined limit

The v1 memory.failcnt is the direct ancestor of v2’s max counter and is often the first sign of trouble. The v1 memory.oom_control=1 option disables the kill entirely, making the cgroup’s allocations block or fail instead; v2 removed this in favor of memory.max being settable to max.

The classic v1 trap is memory.memsw.limit_in_bytes. If you set memory.limit_in_bytes to 2 GB but leave memsw unlimited, the cgroup can consume 2 GB of RAM plus unlimited swap. If you set memsw equal to the RAM limit, the cgroup has zero swap allowance and OOM-kills as soon as it touches 2 GB, even though the host has free swap. Docker’s --memory and --memory-swap flags map to exactly these files, and --memory-swap being the combined total (not the swap extra) confuses everyone at least once.

Check which version a system runs:

Terminal window
stat -fc %T /sys/fs/cgroup/
# cgroup2fs = v2 unified, tmpfs = v1 with systemd hybrid/nested

vm.overcommit_memory: what the three modes actually do

Linux by default overcommits memory: malloc succeeds for more virtual memory than RAM plus swap can back. This is vm.overcommit_memory=0, the heuristic mode. The kernel refuses only obviously impossible allocations (a single allocation larger than total RAM plus swap), otherwise it hands out address space and hopes pages get freed before every one is touched. When the hope fails, the OOM killer is the backstop. This is why a process can allocate 3 GB of virtual space on a 4 GB box and run fine, and also why the failure mode is a sudden kill instead of a clean error.

Setting vm.overcommit_memory=1 means never refuse (except for addressing limits). Allocations always succeed until the page fault itself cannot be satisfied, at which point the OOM killer runs. Databases and HPC jobs sometimes want this for huge sparse mappings; it makes the kill risk strictly higher, not lower.

Setting vm.overcommit_memory=2 enables strict accounting with vm.overcommit_ratio (default 50):

CommitLimit = (swap + RAM * overcommit_ratio / 100)

On a 16 GB RAM, 4 GB swap machine with ratio 50, CommitLimit is 12 GB. Any allocation that would push Committed_AS past 12 GB fails with ENOMEM at malloc time. The process gets an error it can handle, log, and retry, instead of being shot later. Check your current state:

Terminal window
sysctl vm.overcommit_memory vm.overcommit_ratio
grep -E 'CommitLimit|Committed_AS' /proc/meminfo

The trade-off is real and often fatal for careless deployments. Strict mode counts committed virtual memory, so processes that reserve large sparse structures they never touch (JVM reserved heaps with AlwaysPreTouch off, Go arenas, some malloc arenas with generous margins) will fail allocation immediately under mode 2 even though they would run fine under mode 0. The JVM is a known offender: its reserved heap counts against the commit limit. If you enable mode 2, either lower -Xmx to what the process actually touches or accept that malloc failures will surface in the JVM in ugly ways.

My working rules: keep mode 0 on general-purpose servers and desktops, where the heuristic plus swap absorbs normal variance. Use mode 2 on dedicated database or batch hosts with known, stable workloads and no JVM. Never use mode 1 on anything you cannot afford to have killed, unless you have a specific sparse-allocation requirement and monitoring in place.

oom_score, oom_score_adj, and protecting the right process

Per-process tuning lives in /proc/<pid>/oom_score_adj, ranging from -1000 (never kill) to +1000 (kill first). The kernel computes a base badness score from RSS and shows it in /proc/<pid>/oom_score; the adj value is a linear bonus scaled so +1000 guarantees selection and -1000 guarantees immunity.

Terminal window
# See current scores for everything, sorted
for p in /proc/[0-9]*/oom_score_adj; do
pid=${p%/oom_score_adj}; pid=${pid#/proc/}
printf "%s %s %s\n" "$(cat $p)" "$(cat /proc/$pid/oom_score 2>/dev/null)" \
"$(cat /proc/$pid/comm 2>/dev/null)"
done | sort -rn | head -15

Two legitimate uses. Protect a critical daemon that must survive a leak elsewhere:

Terminal window
echo -800 > /proc/$(pidof sshd)/oom_score_adj

Make a sacrificial or easily-restarted worker die first:

Terminal window
echo 500 > /proc/$(pidof my-batch-worker)/oom_score_adj

Systemd units expose this directly with OOMScoreAdjust= in the unit file, which is the right place for it since it survives restarts. Kubernetes maps oomScoreAdj per container in the pod spec.

The trap: oom_score_adj is inherited by children. Setting -1000 on a shell and then starting your leaky app from it makes the leaky app unkillable, and the system will thrash to death instead of recovering. Use the narrowest possible target (the specific PID or unit), never a blanket -1000, and never protect a process that can itself allocate unbounded memory. An unkillable memory hog turns an OOM into a hangover-free but total freeze; the log will show Out of memory and no killable processes.

systemd, oomd, and catching the kill before it happens

Modern systemd gives you three layers of defense, and knowing which one fired matters because the log signatures differ.

MemoryMax= and MemoryHigh= in a unit file set cgroup limits at service start. A MemoryMax kill shows up in the kernel log as a memcg OOM and in the journal as A process of this unit has been killed by the OOM killer. MemoryHigh throttles instead.

OOMPolicy= (systemd 250+) on the unit controls kill scope: OOMPolicy=kill (the default for system services) propagates the kill to the unit’s processes, similar to memory.oom.group.

systemd-oomd is the proactive layer. It monitors pressure stall information (PSI) and kills cgroups before hard OOM, based on sustained memory pressure or swap exhaustion above configured thresholds. Its kills are logged by oomd itself, not the kernel:

Terminal window
journalctl -u systemd-oomd --no-pager | grep -i kill
# systemd-oomd[812]: Killed /user.slice/user-1000.slice/... due to memory pressure for /... of 748.2M > 90.0M for > 20s

If your process dies with no kernel OOM banner at all, check oomd’s log before concluding the kernel did it. PSI thresholds are visible per-cgroup in /sys/fs/cgroup/<path>/memory.pressure; a full 10 20 30 style line with high full averages means tasks are stalling on memory, the condition oomd acts on.

For a quick pre-kill tripwire on any system without oomd, a PSI-based monitor is a few lines:

#!/bin/bash
# alert when 10s memory stall exceeds 5% sustained
while sleep 10; do
read -r _ full10 _ < <(grep full /proc/pressure/memory)
full10=${full10%%.*}
(( ${full10:-0} > 500 )) && logger -t memwatch "memory stall ${full10}us/10s window"
done

Two case studies from real incidents

Case one: a Redis pod on Kubernetes dying every six hours with 30 GB free on the node. The dmesg report said Memory cgroup out of memory: Killed process 47 (redis-server), constraint CONSTRAINT_MEMCG. kubectl describe pod showed Last State: Terminated, Reason: OOMKilled. The container limit was 4 GiB while Redis maxmemory was unset, so Redis grew with the keyspace until it hit the cgroup ceiling. The fix was setting maxmemory 3gb with maxmemory-policy allkeys-lru so Redis evicted keys itself instead of letting the kernel decide, plus raising the container limit to 6 GiB for headroom. The lesson: for anything with its own memory manager (Redis, JVM, PostgreSQL shared buffers), the application limit must sit clearly below the cgroup limit, or the kernel will enforce the limit in the crudest possible way.

Case two: a build server where gcc linking a large binary died with Killed but dmesg showed nothing recent. The ring buffer had rotated. journalctl -k -b -g oom found the event from two hours earlier: the linker had spiked to 11 GB on a 16 GB box while three other builds ran, and the killer chose the linker because it had the highest badness score. The fix was not a sysctl but a build scheduler change: nice and oom_score_adj=200 on the linker wrapper so the killer preferred the right victim, plus Makefile -j reduced from 16 to 8. Total memory used did not change much; the identity of the victim did. This is the practical value of oom_score_adj: when OOM is inevitable under bursty load, you choose who dies.

Troubleshooting: error messages and root causes

Killed in a terminal with exit code 137 (or 143 in some wrappers). Exit 137 is 128 + 9, SIGKILL, and combined with a kernel OOM line it confirms the kill. Check dmesg -T | tail -50 immediately, before the ring buffer rotates. If the process was in a container, exit 137 with OOMKilled: true in docker inspect means the cgroup limit, not global pressure.

Out of memory: Killed process ... but memory.usage_in_bytes is only 2 GB. The killed process is the victim, not necessarily the hog. Look at the task table in the report for the process with the largest rss-anon that exited just before the kill, and check /var/log/syslog or journalctl for the full report. Short-lived spikes (a single tar of a huge tree, a regex on a giant string) are common culprits that never appear as the final victim.

Cannot allocate memory from malloc under vm.overcommit_memory=2. Root cause is Committed_AS exceeding CommitLimit. Verify with grep -E 'Commit|Committed' /proc/meminfo. Fixes, in order of preference: raise vm.overcommit_ratio, add swap (swap counts fully toward the limit), or find the process reserving memory it never touches. Do not flip back to mode 0 to make the error go away; that trades a diagnosable error for a random kill.

oom_reaper never reaps, victim stuck in D state. The victim is blocked in an uninterruptible syscall, typically NFS with a dead server or a hung FUSE mount. Memory stays allocated. Check /proc/<pid>/stack and the storage path. The only recovery is resolving the I/O hang or rebooting. This is a reason to avoid putting swap on network storage.

Memory cgroup out of memory with the cgroup showing low memory.current. Check memory.swap.events and memory.swap.max; the cgroup may be OOM on the swap limit, not the RAM limit. Also check for memory.oom.group=1 killing the whole group when one small helper process leaked.

Kills happen at boot or under kswapd CPU spikes with no single hog. This is the classic no-swap small-RAM pattern: page cache churns, anonymous memory has nowhere to go, reclaim fails. Add swap (even 1 GB changes the dynamics) and set vm.swappiness=10 so it is used only under real pressure. A machine with zero swap OOM-kills on transient spikes that a machine with swap absorbs.

Prevention checklist and the tuning trade-offs

Prevention reduces to three habits. Size cgroup limits from measured peaks, not guesses: run the workload, record memory.peak (v2) or memory.usage_in_bytes high-water, and set the limit at peak plus 20 to 30 percent headroom. Give every server swap, sized to absorb spikes (typically equal to RAM on small hosts, less on large ones), because swap converts a hard kill into a slow, observable degradation. Configure application-level limits (JVM -Xmx, Redis maxmemory, PostgreSQL shared_buffers plus work_mem budgets) to sum to less than the smallest cgroup limit they live under.

The sysctl knobs worth knowing, with honest trade-offs:

Terminal window
# Panic instead of hanging when OOM is unrecoverable (HA pairs, k8s nodes)
sysctl -w kernel.panic_on_oom=1
sysctl -w kernel.panic=10
# Prefer killing the current allocation requester over the global hog
sysctl -w vm.oom_kill_allocating_task=1
# Log every OOM kill detail to a persistent place
echo 'kernel.print-fatal-signals = 1' >> /etc/sysctl.d/99-oom.conf

panic_on_oom trades a reboot (fast on HA systems with automatic failover) for minutes of thrash. oom_kill_allocating_task makes kills predictable (the process that asked for memory dies) at the cost of possibly killing a small requester while a giant hog survives; use it only when the requester is always the right victim, such as single-tenant batch boxes.

None of these settings fix a leak. The sysctls and cgroup limits shape who dies and how loudly; the memory accounting in /proc/meminfo, memory.events, and PSI tells you when you are close. The OOM killer is a last resort, and every kill it performs is a signal that something upstream, an application limit, a container quota, or a capacity plan, was set wrong. Read the report, fix the limit that was actually hit, and the kills stop.

found this useful? share it →
Written by

Dzubayyan Ahmad

System Administrator, SRE & Technical Support Engineer specialising in web hosting infrastructure — Linux servers, automation, and monitoring. Writing these notes since 2015 so future-me can find the fix again.