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:
gfp_mask: The Get Free Page flags passed to the buddy allocator. In this example,0x1100ccadecodes toGFP_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 likeGFP_ATOMICor masks omitting__GFP_FSor__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.order: The allocation order, representing contiguous physical pages.order=0requests a single page. High orders (order=3for ,order=9for 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.oom_score_adj: The heuristic adjustment score of the allocating task, ranging from-1000(completely disabled) to1000(first target).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:25568KBTo interpret these numbers:
- All values inside the top
Mem-Infoblock are reported in pages (usually on x86_64). Multiply by 4 to get values in kilobytes. active_anonvsinactive_anon: Memory allocated by user applications viamalloc, heap expansion, or stack growth. Anonymous memory cannot be discarded; it can only be freed or swapped out to disk. Highactive_anonindicates application working sets.active_filevsinactive_file: Page cache containing files read from or written to disk. In this dump, file pages are nearly zero (512KBand964KB). The kernel had already reclaimed every discardable page cache block before giving up and invoking the OOM killer.slab_reclaimablevsslab_unreclaimable: Memory used by the kernel for internal data structures (inodes, dentries, network socket buffers). Ifslab_unreclaimabledominates, 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 belowlow. Synchronous allocation stalls occur when memory drops belowmin. Iffreeis belowmin, 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 python3Calculate 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 hightotal_vmwith lowrssis 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, PID48100(node) hasrss = 1924102pages. .pgtables_bytes: The memory spent strictly storing the page tables mapping virtual addresses to physical pages. For PID 48100, page tables alone consume .swapents: The number of pages belonging to this process that have been written out to swap space.oom_score_adj: Heuristic modifier. Noticesystemd-udevdhas-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:0kBThe 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.statUnlike 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:
| File | Purpose |
|---|---|
memory.current | Current total memory usage in bytes (includes anon, file cache, slab, sock). |
memory.min | Hard memory protection boundary. Memory below this is never reclaimed under any conditions. |
memory.low | Best-effort protection boundary. Memory below this is reclaimed only if no other memory can be freed. |
memory.high | Throttling limit. If breached, the kernel slows down allocations and forces synchronous reclaim, but does not invoke OOM. |
memory.max | Hard limit. If memory cannot be reclaimed to stay under this limit, the cgroup OOM killer executes. |
memory.events | Counters tracking limit breaches, reclaim pressure, and OOM invocations. |
memory.stat | Comprehensive breakdown of memory types within the cgroup. |
memory.pressure | Pressure 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:
- The kernel does not execute
SIGKILL. - Allocating processes within that cgroup are forced into synchronous direct page reclaim.
- The kernel adds intentional delays (clamping execution time) to the allocating threads proportional to the overage.
- The metric
highinmemory.eventsincrements.
When an application crosses memory.max:
- The kernel attempts aggressive, synchronous page reclaim, dropping page caches and swapping anonymous memory if swap is available.
- If memory usage remains above
memory.maxafter reclaim fails, the kernel invokesmem_cgroup_out_of_memory(). - The counter
oomincrements inmemory.events. - 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:
cat /sys/fs/cgroup/system.slice/api-gateway.service/memory.eventsThe output contains monotonic counters:
low 0high 14210max 821oom 3oom_kill 3oom_group_kill 0Field meanings:
low: The number of times processes in the cgroup ventured below thememory.lowboundary and were subject to reclaim due to system-wide pressure.high: The number of times processes crossedmemory.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 beyondmemory.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 becausememory.oom.groupwas 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 python3import selectimport sysimport 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 statelast_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:
python3 watch_cgroup_oom.py /sys/fs/cgroup/system.slice/docker-$(docker inspect --format '{{.Id}}' worker-app).scope/memory.eventsExtracting 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 and , 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:
- Verify that
systemd-journaldis configured to persist kernel logs to disk. In/etc/systemd/journald.conf:[Journal]Storage=persistentRateLimitIntervalSec=0 - Pull kernel events strictly by facility through systemd journal:
Terminal window journalctl -k --grep="oom-killer|Out of memory" --since "2 hours ago" - 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:
dmesg --time-format=isoOutput:
2026-11-23T08:14:29,314205+00:00 python3 invoked oom-killer: gfp_mask=0x1100cca(GFP_HIGHUSER_MOVABLE), order=0, oom_score_adj=0If parsing older raw dumps saved in text files that contain only relative offsets:
# Calculate absolute event time: system boot time + dmesg offsetboot_timestamp=$(date -d "$(uptime -s)" +%s)dmesg_offset=84129date -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:
cat /sys/fs/cgroup/system.slice/analytics.service/memory.statExample production output:
anon 2147483648file 4294967296kernel_stack 1638400pagetables 67108864sec_pagetables 0percpu 204800sock 10485760shmem 3221225472file_mapped 134217728file_dirty 524288file_writeback 0swapcached 0anon_thp 536870912file_thp 0shmem_thp 0inactive_anon 0active_anon 2147483648inactive_file 1073741824active_file 3221225472unevictable 0slab_reclaimable 268435456slab_unreclaimable 134217728slab 402653184workingset_refault_anon 0workingset_refault_file 142018workingset_activate_anon 0workingset_activate_file 98210workingset_nodereclaim 0pgscan 4210940pgsteal 3981200pgfault 8912401pgmajfault 1240Categorization 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:
- Anonymous Memory (
anon): The memory directly allocated by application execution (heap, stack, thread locals, mmap private). Ifanonconstitutes the vast majority ofmemory.currentand reachesmemory.max, your code has a classical software memory leak (e.g., retaining object references, caching without eviction, or unconstrained collection growth). - Shared Memory (
shmem): Files allocated in temporary file systems (tmpfs), POSIX shared memory (shm_open), or/dev/shm. Notice that inmemory.stat,shmemis counted under bothfileandshmem. Iffileis high, checkshmem. Ifshmemis equal tofile, the memory is not disk-backed cache. It is memory-backed disk space, which cannot be dropped during reclaim unless swap is available. - 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).
- 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,sockcan grow large enough to force an OOM kill. - Page Cache Thrashing (
workingset_refault_file): Ifworkingset_refault_fileis 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:
# Retrieve container IDCONTAINER_ID=$(crictl ps --name my-microservice -q)
# Inspect the pod memory limitcrictl inspect $CONTAINER_ID | jq '.info.runtimeSpec.linux.resources.memory'Output:
{ "limit": 1073741824}The runtime set memory.max to ().
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:
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=9982026-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:9982026-11-23T08:42:10+00:00 kernel: oom_reaper: reaped process 182941 (node), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kBNotice 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 limit (anon-rss:1042004kB ). 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 . 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 of active allocations.
Investigation Steps
Log into the container namespace and query memory.stat from the cgroup filesystem:
cat /sys/fs/cgroup/memory.stat | grep -E "^(anon|file|shmem) "Output:
anon 314572800file 3825205248shmem 3800000000Convert to human-readable values:
anon: (matches the Go runtime heap profile).file: .shmem: .
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:
df -h /dev/shmOutput:
Filesystem Size Used Avail Use% Mounted onshm 3.6G 3.6G 0 100% /dev/shmThe 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 . However, after running for several hours inside a systemd service with MemoryMax=1G, the service gets terminated.
Investigation Steps
Check the systemd service state:
systemctl status file-indexer.serviceOutput:
● 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 boundary.
Now check the global slab allocator to see where memory went:
slabtop -oTop 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 NAME3891000 3891000 100% 0.19K 185285 21 741140K dentry 320140 320140 100% 0.70K 29103 11 232824K ext4_inode_cacheReview 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:891240kBThe dmesg output reveals that slab_unreclaimable within the cgroup reached . 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 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:
cat /proc/pressure/memoryOutput:
some avg10=74.20 avg60=68.10 avg300=45.12 total=841294102full avg10=52.80 avg60=41.20 avg300=21.05 total=412918204Reading PSI output:
some avg10=74.20: During the last 10 seconds, 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:812KBThe 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:
echo "1" > /sys/fs/cgroup/system.slice/my-complex-app.service/memory.oom.groupWhen memory.oom.group is set to 1:
- The kernel does not pick a single victim task.
- The moment any process inside the cgroup triggers an OOM condition, the kernel issues
SIGKILLto every process belonging to that cgroup hierarchy. - The counter
oom_group_killincrements inmemory.events. - 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=execExecStart=/opt/bin/cluster-nodeMemoryMax=4GMemoryOOMGroup=trueRestart=alwaysRestartSec=5sAutomated 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:
sudo bpftrace oom_trace.btWhen 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.pyConfiguration 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 = 0Global 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 AnalyzeWatermarks memory.stat memory.stat& Fragmentation (anon vs file vs slab) (Target root cause)1. Identify the Exact Event Timestamp and Termination Reason
Run:
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 runningkill -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/:
# Locate unit cgroupSYSTEMD_UNIT="my-backend.service"CGROUP_PATH=$(systemctl show -p ControlGroup --value $SYSTEMD_UNIT)
# Read memory eventscat "/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 increasingMemoryMaxor scaling the service horizontally.oom > 0andoom_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:
awk '{printf "%-25s %12.2f MB\n", $1, $2/1024/1024}' "/sys/fs/cgroup${CGROUP_PATH}/memory.stat" | head -n 20Action plan based on the largest allocation type:
- If
anondominates: 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
shmemdominates: Check files inside/dev/shmor directory trees usingtmpfs. Remove stale temporary files or adjust caching lifetimes. - If
filedominates andshmemis 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_unreclaimabledominates: Inspect kernel object handles. Check whether the application leaks open files, sockets, or thread handles usinglsof -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 hard limit, set memory.high to approximately of that threshold ():
# In systemd service configuration:[Service]MemoryHigh=3400MMemoryMax=4000MWhen memory usage crosses , 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:
- Every anonymous page allocated is permanently locked into physical RAM until the process explicitly frees it or exits.
- Even idle, cold anonymous memory (such as initialization code executed once during startup) cannot be swapped out to disk.
- 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 ( to 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:
# Limit the cgroup to 512 MB of swap usageecho "536870912" > /sys/fs/cgroup/system.slice/my-app.service/memory.swap.maxSetting 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=20sThen configure individual systemd service units to opt in:
[Service]ManagedOOMMemoryPressure=killManagedOOMMemoryPressureLimit=50%ManagedOOMPreference=avoidWith this configuration:
- If memory stall pressure inside the service cgroup stays above for longer than 20 seconds,
systemd-oomdintervenes proactively. - Setting
ManagedOOMPreference=avoidtells 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:
TARGET_PID=$(pgrep -f "my-app-binary")
# Check OOM score adjustmentcat /proc/$TARGET_PID/oom_score_adj
# Check effective OOM score calculated by the kernelcat /proc/$TARGET_PID/oom_score
# Check cgroup membershipcat /proc/$TARGET_PID/cgroup
# Check effective limits applied to the process cgroupCGROUP_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.