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

Debug the OOM Killer: Read dmesg and cgroup v2 memory.events

Diagnose out-of-memory kills by parsing kernel dmesg ring buffers and tracking cgroup v2 memory.events to pinpoint memory leaks and container evictions.

masdzub@website:~$ cat ~/articles/debug-the-oom-killer-read-dmesg-and-cgroup-v2-memoryevents.aspx.md
# 1 file · 28 min read · topic: linux · status: published

Introduction

When a process abruptly terminates with exit code 137 without writing an application stack trace, the Linux kernel Out-Of-Memory (OOM) killer or a cgroup memory controller invoked SIGKILL. Diagnosing these silent terminations requires reading two distinct diagnostic interfaces: the kernel ring buffer via dmesg (or journalctl -k) for global and cgroup-level invocation logs, and the cgroup v2 interface files (memory.events, memory.stat, and memory.pressure) to determine exact container-level allocations at the point of exhaustion.

Modern Linux distributions running systemd, Docker, containerd, and Kubernetes enforce memory boundaries through cgroup v2 (the unified control group hierarchy). Relying solely on free -m or standard application-level profiling fails because these utilities miss page cache dirtying, slab growth, socket buffers, and hierarchical parent limits that trigger eviction long before total host physical memory drops to zero.

+-----------------------------------------------------------------------+
| Physical RAM / Swap |
+-----------------------------------------------------------------------+
^
| Allocations evaluated against
+----------------------------------v------------------------------------+
| cgroup v2 Controller Hierarchy (memory.*) |
| - memory.min / memory.low (Reclaim protection) |
| - memory.high (Throttle boundary, async reclaim) |
| - memory.max (Hard limit, sync reclaim -> OOM) |
+----------------------------------+------------------------------------+
|
+-------------------------+-------------------------+
| Limit breached |
v v
+-----------------------------+ +-------------------------------+
| kernel out_of_memory() | | mem_cgroup_out_of_memory() |
| (Global memory starved) | | (cgroup memory.max breached) |
+--------------+--------------+ +---------------+---------------+
| |
v v
+-----------------------------+ +-------------------------------+
| Writes dump to dmesg: | | Increments counters: |
| - GFP mask, order | | - /sys/fs/cgroup/.../ |
| - Node/Zone watermark stats | | memory.events |
| - Task list with anon/file | | (oom, oom_kill, max) |
| - Chosen victim PID & score | | Sends SIGKILL to chosen task |
+-----------------------------+ +-------------------------------+

Anatomy of a Kernel OOM Event in dmesg

The Linux kernel invokes the OOM killer through two main paths: out_of_memory() for system-wide physical memory starvation, and mem_cgroup_out_of_memory() when a specific cgroup exceeds its configured memory.max. Both code paths write a detailed diagnostic record into the kernel log buffer.

Understanding every block of this log reveals whether the failure stemmed from heap allocation, page cache bloat, slab exhaustion, or memory fragmentation.

The Invocation Header and GFP Mask

The log begins by identifying the process that triggered the page allocation failure, along with the memory allocation context:

[84129.314205] python3 invoked oom-killer: gfp_mask=0x1100cca(GFP_HIGHUSER_MOVABLE), order=0, oom_score_adj=0
[84129.314212] CPU: 3 PID: 48291 Comm: python3 Not tainted 6.8.0-49-generic #49-Ubuntu
[84129.314216] Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 1.16.2-debian-1.16.2-1 04/01/2014
[84129.314218] Call Trace:
[84129.314220] <TASK>
[84129.314223] dump_stack_lvl+0x48/0x70
[84129.314228] dump_header+0x50/0x250
[84129.314233] oom_kill_process+0x108/0x1a0
[84129.314237] out_of_memory+0x245/0x5b0
[84129.314242] __alloc_pages_slowpath.constprop.0+0x9e1/0xdb0
[84129.314248] __alloc_pages+0x32d/0x350
[84129.314252] alloc_pages_mpol+0x91/0x1f0
[84129.314257] vma_alloc_zeroed_movable_folio+0x39/0x80
[84129.314262] do_anonymous_page+0x259/0x3b0
[84129.314267] __handle_mm_fault+0x879/0xbb0
[84129.314272] handle_mm_fault+0x12c/0x380
[84129.314277] do_user_addr_fault+0x212/0x690
[84129.314282] exc_page_fault+0x7b/0x180
[84129.314288] asm_exc_page_fault+0x27/0x30
[84129.314294] </TASK>

Key fields in this header:

  1. gfp_mask: The Get Free Page flags passed to the buddy allocator. In this example, 0x1100cca decodes to GFP_HIGHUSER_MOVABLE (__GFP_WAIT | __GFP_IO | __GFP_FS | __GFP_HARDWALL | __GFP_HIGHMEM | __GFP_MOVABLE). This indicates standard user-space anonymous memory or page cache allocation that can be relocated. If you see flags like GFP_ATOMIC or masks omitting __GFP_FS or __GFP_IO, the allocation occurred in an interrupt handler or kernel storage driver that could not sleep or write back dirty pages to disk to free space.
  2. order: The allocation order, representing 2order2^{\text{order}} contiguous physical pages. order=0 requests a single 4 KB4\text{ KB} page. High orders (order=3 for 32 KB32\text{ KB}, order=9 for 2 MB2\text{ MB} huge pages) can trigger the OOM killer even if plenty of free memory exists, provided that memory is fragmented and lacks sufficiently large contiguous spans.
  3. oom_score_adj: The heuristic adjustment score of the allocating task, ranging from -1000 (completely disabled) to 1000 (first target).
  4. invoked oom-killer: Notice that the process named (python3) is simply the task that requested the allocation that crossed the threshold. It is not necessarily the process responsible for the memory consumption.

Memory Zone and Watermark Dumps

Immediately following the stack trace, the kernel prints physical node and zone metrics:

[84129.314301] Mem-Info:
[84129.314304] active_anon:1958434 inactive_anon:12480 isolated_anon:0
[84129.314304] active_file:128 inactive_file:241 isolated_file:0
[84129.314304] unevictable:0 dirty:0 writeback:0
[84129.314304] slab_reclaimable:14205 slab_unreclaimable:28410
[84129.314304] mapped:1840 shmem:1295 pagetables:8492
[84129.314304] sec_pagetables:0 bounce:0
[84129.314304] kernel_misc_reclaimable:0
[84129.314304] free:32488 free_pcp:412 local_pcp:98
[84129.314311] Node 0 active_anon:7833736KB inactive_anon:49920KB active_file:512KB inactive_file:964KB unevictable:0KB dirty:0KB writeback:0KB slab_reclaimable:56820KB slab_unreclaimable:113640KB mapped:7360KB shmem:5180KB pagetables:33968KB free:129952KB
[84129.314319] Node 0 DMA32 free:64216KB boost:0KB min:1824KB low:2280KB high:2736KB reserved_highatomic:0KB active_anon:1842016KB inactive_anon:12000KB active_file:0KB inactive_file:0KB unevictable:0KB writeback:0KB slab_reclaimable:12400KB slab_unreclaimable:24800KB mapped:1200KB shmem:1200KB pagetables:8400KB
[84129.314326] Node 0 Normal free:65736KB boost:0KB min:18432KB low:23040KB high:27648KB reserved_highatomic:0KB active_anon:5991720KB inactive_anon:37920KB active_file:512KB inactive_file:964KB unevictable:0KB writeback:0KB slab_reclaimable:44420KB slab_unreclaimable:88840KB mapped:6160KB shmem:3980KB pagetables:25568KB

To interpret these numbers:

  • All values inside the top Mem-Info block are reported in pages (usually 4 KB4\text{ KB} on x86_64). Multiply by 4 to get values in kilobytes.
  • active_anon vs inactive_anon: Memory allocated by user applications via malloc, heap expansion, or stack growth. Anonymous memory cannot be discarded; it can only be freed or swapped out to disk. High active_anon indicates application working sets.
  • active_file vs inactive_file: Page cache containing files read from or written to disk. In this dump, file pages are nearly zero (512KB and 964KB). The kernel had already reclaimed every discardable page cache block before giving up and invoking the OOM killer.
  • slab_reclaimable vs slab_unreclaimable: Memory used by the kernel for internal data structures (inodes, dentries, network socket buffers). If slab_unreclaimable dominates, the issue is not user-space heap allocation, but kernel allocations such as directory entry leaks caused by walking millions of distinct file paths.
  • Watermarks (min, low, high): Reclaim initiates when a zone drops below low. Synchronous allocation stalls occur when memory drops below min. If free is below min, as shown across DMA32 and Normal zones, the allocator cannot satisfy non-blocking requests.

The Task State Table

Next, the kernel dumps a process table listing candidates evaluated for termination:

[84129.314410] Tasks state (memory values in pages):
[84129.314411] [ pid ] uid tgid total_vm rss pgtables_bytes swapents oom_score_adj name
[84129.314413] [ 412] 0 412 12845 1120 135168 0 0 systemd-journal
[84129.314417] [ 450] 0 450 6421 850 81920 0 -1000 systemd-udevd
[84129.314420] [ 890] 101 890 4210 610 65536 0 0 systemd-resolved
[84129.314424] [ 1201] 0 1201 54120 3210 385024 0 0 dockerd
[84129.314428] [ 1250] 0 1250 41200 2890 311296 0 0 containerd
[84129.314432] [ 48100] 1000 48100 2841920 1924102 16121856 0 0 node
[84129.314436] [ 48291] 1000 48291 45210 8200 147456 0 0 python3

Calculate exact sizes from these column definitions:

  • total_vm: Virtual memory size in pages. This counts all virtual memory areas (VMAs), including memory mapped files, allocated address spaces that were never touched, and shared libraries. A high total_vm with low rss is harmless (common in Go or Java runtimes reserving address space).
  • rss: Resident Set Size in pages. This is physical memory currently mapped to the page table of this process. In this example, PID 48100 (node) has rss = 1924102 pages. 1924102×4096=7,881,121,792 bytes≈7.34 GB1924102 \times 4096 = 7,881,121,792\text{ bytes} \approx 7.34\text{ GB}.
  • pgtables_bytes: The memory spent strictly storing the page tables mapping virtual addresses to physical pages. For PID 48100, page tables alone consume 16 MB16\text{ MB}.
  • swapents: The number of pages belonging to this process that have been written out to swap space.
  • oom_score_adj: Heuristic modifier. Notice systemd-udevd has -1000, making it immune to selection.

The Victim Selection Log

Finally, the kernel states its decision:

[84129.314502] Out of memory: Killed process 48100 (node) total-vm:11367680kB, anon-rss:7696408kB, file-rss:0kB, shmem-rss:0kB, UID:1000 pgtables:15744kB oom_score_adj:0
[84129.328912] oom_reaper: reaped process 48100 (node), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB

The kernel calculates an internal badness score based on the proportion of RAM consumed by the process rss, adjusted by oom_score_adj. Although PID 48291 (python3) pushed the system over the limit, the kernel picked PID 48100 (node) because its resident memory was overwhelmingly the largest contributor to starvation.

The oom_reaper line confirms that an asynchronous kernel thread immediately detached the process memory space, unmapping its anonymous pages to return them to the buddy allocator before the process fully exited and completed user-space signal handling.


Memory Control in cgroup v2 Architecture

In modern environments, the global OOM killer path described above is less common than cgroup-scoped memory limits. Cgroup v2 unifies resource management under a single hierarchical tree, typically mounted at /sys/fs/cgroup.

/sys/fs/cgroup (Root)
|
+-----------------------+-----------------------+
| |
system.slice user.slice
| |
docker-<id>.scope user-1000.slice
(memory.max = 2G) |
- memory.events session-2.scope
- memory.stat - memory.events
- memory.pressure - memory.stat

Unlike cgroup v1, which had separate trees for memory, cpu, and blkio, cgroup v2 uses a single hierarchy where every process lives in exactly one leaf cgroup. Resource controls are configured per node and inherited downward.

The Cgroup v2 Memory Interface Files

Inside any cgroup directory (e.g., /sys/fs/cgroup/system.slice/my-app.service/), several control and status files dictate memory allocation:

FilePurpose
memory.currentCurrent total memory usage in bytes (includes anon, file cache, slab, sock).
memory.minHard memory protection boundary. Memory below this is never reclaimed under any conditions.
memory.lowBest-effort protection boundary. Memory below this is reclaimed only if no other memory can be freed.
memory.highThrottling limit. If breached, the kernel slows down allocations and forces synchronous reclaim, but does not invoke OOM.
memory.maxHard limit. If memory cannot be reclaimed to stay under this limit, the cgroup OOM killer executes.
memory.eventsCounters tracking limit breaches, reclaim pressure, and OOM invocations.
memory.statComprehensive breakdown of memory types within the cgroup.
memory.pressurePressure Stall Information (PSI) reporting time lost to memory starvation.

Decoupling memory.high from memory.max

One of the largest architectural improvements in cgroup v2 is the separation of proactive throttling (memory.high) from fatal enforcement (memory.max).

When an application crosses memory.high:

  1. The kernel does not execute SIGKILL.
  2. Allocating processes within that cgroup are forced into synchronous direct page reclaim.
  3. The kernel adds intentional delays (clamping execution time) to the allocating threads proportional to the overage.
  4. The metric high in memory.events increments.

When an application crosses memory.max:

  1. The kernel attempts aggressive, synchronous page reclaim, dropping page caches and swapping anonymous memory if swap is available.
  2. If memory usage remains above memory.max after reclaim fails, the kernel invokes mem_cgroup_out_of_memory().
  3. The counter oom increments in memory.events.
  4. A victim process within that specific cgroup hierarchy is killed, incrementing oom_kill.

Reading and Monitoring cgroup v2 memory.events

The primary interface for monitoring cgroup evictions is the memory.events file located within each cgroup directory.

Structure of memory.events

To inspect a service running under systemd or a container runtime:

Terminal window
cat /sys/fs/cgroup/system.slice/api-gateway.service/memory.events

The output contains monotonic counters:

low 0
high 14210
max 821
oom 3
oom_kill 3
oom_group_kill 0

Field meanings:

  • low: The number of times processes in the cgroup ventured below the memory.low boundary and were subject to reclaim due to system-wide pressure.
  • high: The number of times processes crossed memory.high. This indicates that your application suffered allocation latency penalties because the kernel throttled thread execution to force reclaim.
  • max: The number of times processes attempted to allocate memory beyond memory.max. Each increment corresponds to a direct reclaim attempt to prevent an OOM kill.
  • oom: The number of times the memory cgroup entered the OOM condition. This counter increments when reclaim fails and the kernel must initiate victim selection.
  • oom_kill: The number of processes successfully terminated by the cgroup OOM killer.
  • oom_group_kill: The number of times the entire cgroup was torn down at once because memory.oom.group was enabled.

There is also a related file named memory.events.local. The standard memory.events aggregates counts from all descendant cgroups in the subtree. In contrast, memory.events.local counts only events occurring within that exact cgroup level, ignoring children.

Setting Up a Non-polling Event Watcher

You do not need to poll memory.events in a shell loop. The kernel implements notifications via poll(), select(), and epoll() on the memory.events file descriptor. When a counter increments, the kernel signals POLLPRI and POLLERR on the file descriptor.

The following Python script uses low-level system calls to block indefinitely without consuming CPU until the kernel registers an OOM or high-watermark event:

#!/usr/bin/env python3
import select
import sys
import time
if len(sys.argv) < 2:
print(f"Usage: {sys.argv[0]} /sys/fs/cgroup/.../memory.events")
sys.exit(1)
event_file_path = sys.argv[1]
try:
fd = open(event_file_path, "r")
except OSError as e:
print(f"Failed to open {event_file_path}: {e}")
sys.exit(1)
# Register with epoll on Priority Out (exceptional condition)
epoll = select.epoll()
epoll.register(fd.fileno(), select.EPOLLPRI | select.EPOLLERR)
print(f"Monitoring {event_file_path} for memory events...")
# Read initial file state
last_content = fd.read()
fd.seek(0)
try:
while True:
events = epoll.poll(timeout=-1)
for fileno, event in events:
if event & (select.EPOLLPRI | select.EPOLLERR):
# Seek to start to re-read updated cgroup event data
fd.seek(0)
current_content = fd.read()
print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] Memory Event Triggered:")
for line in current_content.strip().split("\n"):
print(f" {line}")
print("-" * 50)
except KeyboardInterrupt:
print("\nExiting watcher.")
finally:
epoll.unregister(fd.fileno())
epoll.close()
fd.close()

Save this as watch_cgroup_oom.py and run it against a suspect container or service slice:

Terminal window
python3 watch_cgroup_oom.py /sys/fs/cgroup/system.slice/docker-$(docker inspect --format '{{.Id}}' worker-app).scope/memory.events

Extracting and Correlating Logs in Production

When diagnosing a failure after the fact, engineers often find that dmesg output was overwritten by later logs, or the container was removed by the orchestrator before its cgroup could be inspected. The following workflow avoids these pitfalls.

Preventing Kernel Ring Buffer Rollover

The kernel ring buffer has a finite byte size (typically set at compile time between 256 KB256\text{ KB} and 4 MB4\text{ MB}, controlled by CONFIG_LOG_BUF_SHIFT). On high-traffic systems, network packet drops, firewall logging, or disk errors can overwrite the OOM dump within minutes.

To prevent log loss:

  1. Verify that systemd-journald is configured to persist kernel logs to disk. In /etc/systemd/journald.conf:
    [Journal]
    Storage=persistent
    RateLimitIntervalSec=0
  2. Pull kernel events strictly by facility through systemd journal:
    Terminal window
    journalctl -k --grep="oom-killer|Out of memory" --since "2 hours ago"
  3. Read the exact timestamp and context by extracting the 50 lines before and after the OOM invocation:
    Terminal window
    journalctl -k -o short-iso -B 0 | grep -B 20 -A 40 "invoked oom-killer"

Correlating Timestamps Between dmesg and System Wall Clock

The output of raw dmesg defaults to seconds since system boot (e.g., [84129.314205]). To align this with application-level distributed tracing (such as OpenTelemetry logs or database slow-query logs), translate the boot time to an absolute UTC or local timestamp:

Terminal window
dmesg --time-format=iso

Output:

2026-11-23T08:14:29,314205+00:00 python3 invoked oom-killer: gfp_mask=0x1100cca(GFP_HIGHUSER_MOVABLE), order=0, oom_score_adj=0

If parsing older raw dumps saved in text files that contain only relative offsets:

Terminal window
# Calculate absolute event time: system boot time + dmesg offset
boot_timestamp=$(date -d "$(uptime -s)" +%s)
dmesg_offset=84129
date -d "@$((boot_timestamp + dmesg_offset))" "+%Y-%m-%d %H:%M:%S"

Deep Dive: Analyzing memory.stat to Identify Leak Sources

When memory.events shows an increase in oom_kill, checking memory.stat in that same cgroup reveals what class of allocation caused the breach. Many developers assume every OOM kill is an application heap leak. In reality, issues often trace back to the page cache, kernel slab objects, or shared memory.

Inspect the complete allocation matrix:

Terminal window
cat /sys/fs/cgroup/system.slice/analytics.service/memory.stat

Example production output:

anon 2147483648
file 4294967296
kernel_stack 1638400
pagetables 67108864
sec_pagetables 0
percpu 204800
sock 10485760
shmem 3221225472
file_mapped 134217728
file_dirty 524288
file_writeback 0
swapcached 0
anon_thp 536870912
file_thp 0
shmem_thp 0
inactive_anon 0
active_anon 2147483648
inactive_file 1073741824
active_file 3221225472
unevictable 0
slab_reclaimable 268435456
slab_unreclaimable 134217728
slab 402653184
workingset_refault_anon 0
workingset_refault_file 142018
workingset_activate_anon 0
workingset_activate_file 98210
workingset_nodereclaim 0
pgscan 4210940
pgsteal 3981200
pgfault 8912401
pgmajfault 1240

Categorization Framework

Total cgroup Memory (memory.current)
|
+---------------------------------+---------------------------------+
| | |
User Allocations Shared / Dynamic Kernel Structures
- anon (Heap/Stack) - shmem (/dev/shm, IPC) - slab (dentry/inode)
- file_mapped (Executables/so) - file (Page Cache) - pagetables
- sock (TCP buffers)

Analyze the breakdown using these relationships:

  1. Anonymous Memory (anon): The memory directly allocated by application execution (heap, stack, thread locals, mmap private). If anon constitutes the vast majority of memory.current and reaches memory.max, your code has a classical software memory leak (e.g., retaining object references, caching without eviction, or unconstrained collection growth).
  2. Shared Memory (shmem): Files allocated in temporary file systems (tmpfs), POSIX shared memory (shm_open), or /dev/shm. Notice that in memory.stat, shmem is counted under both file and shmem. If file is high, check shmem. If shmem is equal to file, the memory is not disk-backed cache. It is memory-backed disk space, which cannot be dropped during reclaim unless swap is available.
  3. Slab Allocations (slab): Memory held by kernel internal caches allocated on behalf of the cgroup. This subdivides into:
    • slab_reclaimable: Mostly dentry (directory cache) and inode caches. Can be reclaimed by the kernel under memory pressure.
    • slab_unreclaimable: Structures like task handles, file descriptor tables, and epoll sets. If this is high, the application is leaking operating system handles (e.g., opening sockets or files without closing them).
  4. Network Buffers (sock): Memory dedicated to network input/output buffers for sockets associated with processes in this cgroup. If an application fails to read from TCP sockets while clients send high-volume payloads with large socket buffer limits, sock can grow large enough to force an OOM kill.
  5. Page Cache Thrashing (workingset_refault_file): If workingset_refault_file is rising rapidly, the cgroup is continually evicting file pages and immediately re-reading them from disk. This condition, known as refault thrashing, generates intense disk I/O and CPU overhead right before the kernel gives up and calls the OOM killer.

Production Scenarios and Diagnostic Walkthroughs

The following four real-world scenarios show how to diagnose common failure patterns using these tools.


Scenario A: Silent Container Eviction in Kubernetes or Docker

A microservice running in a Kubernetes pod crashes. Kubernetes marks the pod status as OOMKilled with exit code 137. The container logs show nothing except an abrupt cutoff in the middle of processing an HTTP request.

Investigation Steps

First, locate the container ID and verify the cgroup path on the underlying node where the pod was scheduled:

Terminal window
# Retrieve container ID
CONTAINER_ID=$(crictl ps --name my-microservice -q)
# Inspect the pod memory limit
crictl inspect $CONTAINER_ID | jq '.info.runtimeSpec.linux.resources.memory'

Output:

{
"limit": 1073741824
}

The runtime set memory.max to 1 GB1\text{ GB} (1073741824 bytes1073741824\text{ bytes}).

Next, examine the kernel logs on the host to determine whether the host ran out of physical memory or if the container hit its cgroup boundary:

Terminal window
journalctl -k -o short-iso --since "10 minutes ago" | grep -E "(oom-killer|Killed process|oom_reaper)"

Output:

2026-11-23T08:42:10+00:00 kernel: node invoked oom-killer: gfp_mask=0xcc0(GFP_KERNEL), order=0, oom_score_adj=998
2026-11-23T08:42:10+00:00 kernel: Memory cgroup out of memory: Killed process 182941 (node) total-vm:1894200kB, anon-rss:1042004kB, file-rss:4120kB, shmem-rss:0kB, UID:1000 pgtables:2400kB oom_score_adj:998
2026-11-23T08:42:10+00:00 kernel: oom_reaper: reaped process 182941 (node), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB

Notice the distinction:

Memory cgroup out of memory: Killed process 182941 (node)

The presence of Memory cgroup out of memory confirms this was a cgroup-level enforcement (mem_cgroup_out_of_memory()), not a host-wide resource exhaustion (out_of_memory()).

The host still had available physical RAM, but this container exceeded its 1 GB1\text{ GB} limit (anon-rss:1042004kB ≈1017 MB\approx 1017\text{ MB}). Kubernetes set oom_score_adj=998, prioritizing this container for termination over non-containerized system daemons.


Scenario B: The Shared Memory (shmem) Masked Leak

A Go application uses a local cache implemented via a memory-mapped file stored in /dev/shm to pass data between worker processes. The developer sets the container limit to 4 GB4\text{ GB}. Over two days, memory usage steadily grows until the process is killed. The developer runs a heap profiler (pprof), but the Go heap shows only 300 MB300\text{ MB} of active allocations.

Investigation Steps

Log into the container namespace and query memory.stat from the cgroup filesystem:

Terminal window
cat /sys/fs/cgroup/memory.stat | grep -E "^(anon|file|shmem) "

Output:

anon 314572800
file 3825205248
shmem 3800000000

Convert to human-readable values:

  • anon: 314,572,800 bytes≈300 MB314,572,800\text{ bytes} \approx 300\text{ MB} (matches the Go runtime heap profile).
  • file: 3,825,205,248 bytes≈3.56 GB3,825,205,248\text{ bytes} \approx 3.56\text{ GB}.
  • shmem: 3,800,000,000 bytes≈3.53 GB3,800,000,000\text{ bytes} \approx 3.53\text{ GB}.

The Go heap profiler is not wrong; it accounts only for heap objects requested via runtime allocator calls (runtime.mallocgc). It cannot track memory-mapped files or POSIX shared memory backing /dev/shm.

Verify by checking the disk usage of the shared memory mount:

Terminal window
df -h /dev/shm

Output:

Filesystem Size Used Avail Use% Mounted on
shm 3.6G 3.6G 0 100% /dev/shm

The application was creating caching files under /dev/shm without removing obsolete entries. Because /dev/shm is implemented using tmpfs, the memory pages are accounted as shmem inside the cgroup. The kernel cannot reclaim these pages under pressure because they represent active filesystem data. Once total usage hit memory.max, the kernel invoked the OOM killer.


Scenario C: Kernel Slab Dentry Exhaustion

A Python script scans deep directory hierarchies across network-attached mounts, evaluating file metadata (os.stat). The total heap usage of Python remains under 150 MB150\text{ MB}. However, after running for several hours inside a systemd service with MemoryMax=1G, the service gets terminated.

Investigation Steps

Check the systemd service state:

Terminal window
systemctl status file-indexer.service

Output:

● file-indexer.service - File System Indexer
Loaded: loaded (/etc/systemd/system/file-indexer.service; enabled)
Active: failed (Result: oom-kill) since Mon 2026-11-23 09:12:04 UTC; 4min ago
Main PID: 89124 (code=killed, signal=KILL)
CPU: 12min 41.201s
Memory: 12.0M (peak: 1.0G)

Systemd reports Result: oom-kill and confirms peak memory usage reached the 1.0 GB1.0\text{ GB} boundary.

Now check the global slab allocator to see where memory went:

Terminal window
slabtop -o

Top output lines:

Active / Total Objects (% used) : 4210920 / 4210920 (100.0%)
Active / Total Size (% used) : 984510K / 984510K (100.0%)
Minimum / Average / Maximum Object : 0.04K / 0.23K / 8.00K
OBJS ACTIVE USE OBJ SIZE SLABS OBJ/SLAB CACHE SIZE NAME
3891000 3891000 100% 0.19K 185285 21 741140K dentry
320140 320140 100% 0.70K 29103 11 232824K ext4_inode_cache

Review the cgroup memory.stat recorded immediately before termination or reconstruct it via dmesg:

[84910.124901] Memory cgroup out of memory: Killed process 89124 (python3) total-vm:210440kB, anon-rss:98400kB, file-rss:1240kB, shmem-rss:0kB
[84910.124905] slab_reclaimable:14200kB slab_unreclaimable:891240kB

The dmesg output reveals that slab_unreclaimable within the cgroup reached 891 MB891\text{ MB}. Every time the Python process touched a new path, the kernel allocated a dentry and an inode structure to track the file.

Because the directory hierarchy contained millions of paths, the kernel memory structures exceeded the cgroup boundary. The process died not from user-space allocations, but from the kernel metadata needed to track the files it inspected.


Scenario D: Page Cache Exhaustion and I/O Thrashing

An Elasticsearch or database container has no explicit memory.max set, but the host system has 16 GB16\text{ GB} of RAM. The node becomes sluggish, latency increases by two orders of magnitude, and tasks begin failing. dmesg shows the OOM killer was invoked.

Investigation Steps

Inspect the Pressure Stall Information (PSI) for memory across the whole host:

Terminal window
cat /proc/pressure/memory

Output:

some avg10=74.20 avg60=68.10 avg300=45.12 total=841294102
full avg10=52.80 avg60=41.20 avg300=21.05 total=412918204

Reading PSI output:

  • some avg10=74.20: During the last 10 seconds, 74.2%74.2\% of processes spent time waiting for memory allocation (such as paging in code or waiting for page reclaim).
  • full avg10=52.80: Over half of the execution threads were completely stalled waiting for memory operations, unable to execute CPU instructions.

Now inspect the zone information in dmesg:

[91204.102410] Node 0 Normal free:18432KB min:18432KB low:23040KB high:27648KB
[91204.102414] active_file:412KB inactive_file:812KB

The database issued massive file reads across multi-gigabyte index files. The page cache grew until available memory hit the zone low watermark. The kernel background reclaim thread (kswapd) attempted to clear clean page caches to keep pace with allocations.

However, the storage subsystem could not service the read/write demands quickly enough. When allocation rates exceeded disk I/O throughput, processes fell into direct reclaim, and memory dropped below the min watermark. At that point, the kernel invoked out_of_memory() to prevent a complete system lockup.


The memory.oom.group Option

By default, when a cgroup breaches its hard limit, the kernel executes mem_cgroup_out_of_memory(), scores every process inside that cgroup, and sends SIGKILL to a single victim process.

This default behavior causes severe bugs in multi-process architectures such as PostgreSQL, JVM wrappers, or systems using sidecar patterns:

my-service.slice (memory.max breached)
|
+-------------------------+-------------------------+
| |
Target Process Sibling Process
(e.g., Worker Node) (e.g., Connection Broker)
| |
Receives SIGKILL Stays alive in broken state
(Memory freed temporarily) (Hangs, drops transactions)

If the victim was a worker process, the primary manager process remains alive in a degraded state, unable to complete tasks or self-heal cleanly.

Enabling Group Fate Sharing

To ensure that an OOM event tears down the entire application stack predictably, enable memory.oom.group:

Terminal window
echo "1" > /sys/fs/cgroup/system.slice/my-complex-app.service/memory.oom.group

When memory.oom.group is set to 1:

  1. The kernel does not pick a single victim task.
  2. The moment any process inside the cgroup triggers an OOM condition, the kernel issues SIGKILL to every process belonging to that cgroup hierarchy.
  3. The counter oom_group_kill increments in memory.events.
  4. Systemd or your container orchestrator detects clean process group termination and restarts the unit according to its restart policy.

In a systemd service file, configure this declaratively:

[Service]
Type=exec
ExecStart=/opt/bin/cluster-node
MemoryMax=4G
MemoryOOMGroup=true
Restart=always
RestartSec=5s

Automated Incident Response with bpftrace

To diagnose intermittent OOM kills that occur during off-hours, you can attach an eBPF tracepoint directly to the kernel function that invokes the OOM killer. This captures exact call stacks, requested page orders, and allocation contexts the instant an event fires.

Create a diagnostic script named oom_trace.bt:

#!/usr/bin/env bpftrace
#include <linux/oom.h>
#include <linux/memcontrol.h>
BEGIN
{
printf("Tracing OOM killer invocations. Press Ctrl-C to end.\n");
printf("%-20s %-8s %-16s %-8s %-10s\n", "TIME", "PID", "COMM", "PAGES", "CGROUP");
}
tracepoint:oom:oom_score_adj_update
{
// Tracks when daemons adjust their survivability
}
kprobe:out_of_memory
{
$oc = (struct oom_control *)arg0;
time("%H:%M:%S ");
printf("%-8d %-16s %-8d [SYSTEM-WIDE]\n",
curtask->pid,
curtask->comm,
$oc->totalpages);
}
kprobe:mem_cgroup_out_of_memory
{
$memcg = (struct mem_cgroup *)arg0;
time("%H:%M:%S ");
printf("%-8d %-16s %-8s [CGROUP-OOM]\n",
curtask->pid,
curtask->comm,
curtask->cgroups->dfl_cgrp->name);
}
tracepoint:oom:mark_victim
{
time("%H:%M:%S ");
printf("--> VICTIM SELECTED: PID %d Comm: %s\n", args->pid, args->comm);
}

Run this tracepoint on a staging or production server experiencing intermittent kills:

Terminal window
sudo bpftrace oom_trace.bt

When an allocation failure triggers an eviction, bpftrace prints the event immediately, bypassing user-space logging delays:

14:22:01 412098 worker.py [CGROUP-OOM]
14:22:01 --> VICTIM SELECTED: PID 412098 Comm: worker.py

Configuration Reference and Practical Troubleshooting Steps

Follow this diagnostic checklist when a service exits unexpectedly with status 137 or reports Killed.

Process Exits Unexpectedly (Code 137)
|
+-------------------------+-------------------------+
| |
Check dmesg / journalctl Check Cgroup Hierarchy
journalctl -k --grep="oom-killer" cat memory.events
| |
+-------+-------+ +-------+-------+
| | | |
Found: Found: oom_kill > 0 oom_kill = 0
Global OOM cgroup OOM (Cgroup max (Non-OOM SIGKILL,
(out_of_memory) (mem_cgroup_out_of_memory) exceeded) e.g., liveness probe)
| | |
Review Node Review cgroup Analyze
Watermarks memory.stat memory.stat
& Fragmentation (anon vs file vs slab) (Target root cause)

1. Identify the Exact Event Timestamp and Termination Reason

Run:

Terminal window
journalctl -k --since "1 hour ago" -o short-iso | grep -B 5 -A 15 -E "(invoked oom-killer|Memory cgroup out of memory)"

Evaluation criteria:

  • Look for invoked oom-killer: Indicates global memory exhaustion. Check the host for runaway processes, unconstrained page caches, or lack of swap.
  • Look for Memory cgroup out of memory: Indicates the process hit a cgroup boundary. The system as a whole had memory available, but this specific container or service slice exceeded its allocation budget.
  • If neither appears in dmesg, the process did not die from an operating system OOM condition. It was killed by an external signal: a container liveness probe, a user running kill -9, an orchestrator timeout, or an unhandled hardware signal (SIGSEGV, SIGBUS).

2. Inspect the Relevant cgroup v2 Events

Navigate directly to the service cgroup inside /sys/fs/cgroup/:

Terminal window
# Locate unit cgroup
SYSTEMD_UNIT="my-backend.service"
CGROUP_PATH=$(systemctl show -p ControlGroup --value $SYSTEMD_UNIT)
# Read memory events
cat "/sys/fs/cgroup${CGROUP_PATH}/memory.events"

Check the counters:

  • high > 0: The application was throttled. Its processing latency increased because the kernel forced allocations into direct synchronous reclaim.
  • max > 0: The application repeatedly hit the ceiling. Consider increasing MemoryMax or scaling the service horizontally.
  • oom > 0 and oom_kill > 0: The application breached limits, reclaim failed, and processes were terminated.

3. Analyze the Memory Category in memory.stat

Read memory.stat to identify the dominant allocation category:

Terminal window
awk '{printf "%-25s %12.2f MB\n", $1, $2/1024/1024}' "/sys/fs/cgroup${CGROUP_PATH}/memory.stat" | head -n 20

Action plan based on the largest allocation type:

  • If anon dominates: Focus on application runtime profiling (e.g., Go pprof, Java jcmd/heap dumps, Node.js heap snapshots). The code is retaining references or leaking memory in user space.
  • If shmem dominates: Check files inside /dev/shm or directory trees using tmpfs. Remove stale temporary files or adjust caching lifetimes.
  • If file dominates and shmem is low: Memory is held by disk page caches. If these pages cannot be reclaimed, ensure disk storage is not stalling, and evaluate whether your workload requires larger memory limits to hold its active working set.
  • If slab_unreclaimable dominates: Inspect kernel object handles. Check whether the application leaks open files, sockets, or thread handles using lsof -p <PID> | wc -l.

Defensive Mitigation Strategies

Tuning memory parameters properly prevents hard SIGKILL events from interrupting production workloads.

Setting Throttling Thresholds with memory.high

Rather than letting an application run unconstrained until it crashes against memory.max, configure a buffer zone using memory.high. This instructs the kernel to throttle the process and reclaim clean pages before an OOM becomes necessary.

Example: For a container with a 4 GB4\text{ GB} hard limit, set memory.high to approximately 85%85\% of that threshold (3.4 GB3.4\text{ GB}):

Terminal window
# In systemd service configuration:
[Service]
MemoryHigh=3400M
MemoryMax=4000M

When memory usage crosses 3400 MB3400\text{ MB}, the kernel slows down allocations from the offending process. This gives background reclaim threads time to free memory, reducing the likelihood of a sudden OOM termination.

Provisioning Swap Space in cgroup v2

A common production mistake is disabling swap entirely in containerized environments. Without swap:

  1. Every anonymous page allocated is permanently locked into physical RAM until the process explicitly frees it or exits.
  2. Even idle, cold anonymous memory (such as initialization code executed once during startup) cannot be swapped out to disk.
  3. When memory pressure spikes, the kernel cannot touch anonymous memory. It can only reclaim file-backed page caches. If page caches are already exhausted, the OOM killer triggers immediately.

Providing even a modest swap allocation (1 GB1\text{ GB} to 2 GB2\text{ GB} on NVMe storage) gives the kernel a pressure release mechanism. It can write out cold anonymous pages, preserving valuable physical RAM for latency-critical page caches and active application working sets.

To control swap consumption per cgroup v2, configure memory.swap.max:

Terminal window
# Limit the cgroup to 512 MB of swap usage
echo "536870912" > /sys/fs/cgroup/system.slice/my-app.service/memory.swap.max

Setting memory.swap.max = 0 disables swap for that specific cgroup while allowing the rest of the host system to utilize swap space normally.

User-Space OOM Handling via systemd-oomd

The kernel OOM killer acts reactively: it intervenes only after memory exhaustion has already occurred and the buddy allocator cannot satisfy an allocation request. By this point, the system may have spent seconds or minutes in a heavily degraded state, thrashing page caches and freezing execution threads.

systemd-oomd provides a proactive, user-space alternative built around Pressure Stall Information (PSI). It monitors /proc/pressure/memory continuously. If memory pressure exceeds configured thresholds for a specified duration, systemd-oomd acts before the kernel runs out of pages entirely. It terminates processes cleanly at the cgroup level, minimizing system-wide latency spikes.

Enable and configure proactive memory defense in /etc/systemd/oomd.conf:

[OOM]
SwapUsedLimit=90%
DefaultMemoryPressureLimit=60%
DefaultMemoryPressureDurationSec=20s

Then configure individual systemd service units to opt in:

[Service]
ManagedOOMMemoryPressure=kill
ManagedOOMMemoryPressureLimit=50%
ManagedOOMPreference=avoid

With this configuration:

  • If memory stall pressure inside the service cgroup stays above 50%50\% for longer than 20 seconds, systemd-oomd intervenes proactively.
  • Setting ManagedOOMPreference=avoid tells the daemon to target other, less critical cgroups first before considering this service for termination.

Verifying Memory Adjustments

To confirm that your cgroup limits and OOM adjustments are applied correctly, inspect the live proc and cgroup trees for your target process:

Terminal window
TARGET_PID=$(pgrep -f "my-app-binary")
# Check OOM score adjustment
cat /proc/$TARGET_PID/oom_score_adj
# Check effective OOM score calculated by the kernel
cat /proc/$TARGET_PID/oom_score
# Check cgroup membership
cat /proc/$TARGET_PID/cgroup
# Check effective limits applied to the process cgroup
CGROUP_DIR="/sys/fs/cgroup/$(awk -F':' '{print $3}' /proc/$TARGET_PID/cgroup)"
echo "Current Usage: $(cat $CGROUP_DIR/memory.current)"
echo "High Threshold: $(cat $CGROUP_DIR/memory.high)"
echo "Hard Max: $(cat $CGROUP_DIR/memory.max)"
echo "Swap Max: $(cat $CGROUP_DIR/memory.swap.max)"

Using this workflow, you can verify whether resource boundaries match your infrastructure specifications, identify whether terminations stemmed from host-wide or cgroup-level exhaustion, and pinpoint the exact memory allocation category responsible for the event.

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.