Introduction
When a Linux system exhausts reclaimable memory, the kernel evicts page cache, swaps anonymous pages if swap is available, and invokes the Out of Memory (OOM) killer to terminate one or more processes when reclaim cannot satisfy an allocation. Diagnosing and preventing these events requires reading the right kernel signals, understanding how the reclaim path behaves under pressure, and applying limits that fail predictably instead of taking down unrelated workloads. This article walks through memory accounting, Pressure Stall Information (PSI), swap and watermark tuning, OOM victim selection, log analysis, cgroup and systemd controls, and concrete recovery steps for real production failures.
How the Linux Kernel Accounts for Memory
Linux manages physical RAM in fixed-size pages, typically 4 kB on x86_64 systems. Each page is either anonymous or file-backed. Anonymous pages hold process-private data such as heap, stack, and memory mappings created without a file backing. File-backed pages hold data read from disk and are usually kept in the page cache so subsequent reads avoid disk I/O. When memory runs low, the kernel can discard clean file-backed pages immediately because the data still exists on disk. Dirty file-backed pages must be written back before they can be reclaimed. Anonymous pages cannot be discarded; they must be written to swap or kept in RAM.
This distinction explains why a server with very little “free” memory is often healthy. The kernel intentionally uses spare RAM for cache and buffers to improve performance. The metric that matters for capacity planning is available memory, not free memory. On kernels 3.14 and later, MemAvailable in /proc/meminfo estimates how much memory can be allocated without swapping, accounting for reclaimable page cache and slab memory.
free -h total used free shared buff/cache availableMem: 15Gi 6.2Gi 402Mi 312Mi 8.9Gi 8.1GiSwap: 4.0Gi 202Mi 3.8GiIn this example, only 402 MiB is free, but 8.1 GiB is available because most of the buffer and cache memory can be reclaimed. Treating low free as a memory leak is a common misdiagnosis that leads to unnecessary restarts.
For a detailed view, inspect /proc/meminfo directly:
cat /proc/meminfoMemTotal: 16384256 kBMemFree: 412340 kBMemAvailable: 8234512 kBBuffers: 234120 kBCached: 7123456 kBSwapCached: 12400 kBActive: 6234512 kBInactive: 3456789 kBActive(anon): 2123456 kBInactive(anon): 823456 kBActive(file): 4111056 kBInactive(file): 2633333 kBSwapTotal: 4194304 kBSwapFree: 3987654 kBDirty: 1024 kBWriteback: 0 kBAnonPages: 2845123 kBMapped: 512340 kBShmem: 412345 kBKReclaimable: 412345 kBSlab: 623456 kBSReclaimable: 412345 kBSUnreclaim: 211111 kBCommitLimit: 12386432 kBCommitted_AS: 9876543 kBSeveral fields are useful during an incident. Active and Inactive track recently and less recently used pages, split into anonymous and file-backed categories. A large Active(file) value indicates warm cache that may be reclaimable under pressure. Slab, SReclaimable, and SUnreclaim describe kernel object caches; high unreclaimable slab usage can point to kernel-side memory growth. Committed_AS represents the total memory requested by processes under the current overcommit policy, while CommitLimit is the ceiling when strict overcommit is enabled. Comparing these values over time provides a baseline for deciding whether a workload needs more RAM, tighter limits, or different reclaim behavior.
Reading Memory Pressure with PSI and vmstat
Memory pressure begins before the OOM killer runs. The kernel may spend significant CPU time reclaiming pages, and processes may stall waiting for allocations or page-ins. Pressure Stall Information (PSI), introduced in kernel 4.20 and enabled on most modern distributions, quantifies that stall time.
cat /proc/pressure/memorysome avg10=2.45 avg60=1.10 avg300=0.35 total=18423012full avg10=0.50 avg60=0.20 avg300=0.05 total=3210456The some line reports the percentage of time at least one task was stalled on memory. The full line reports the percentage of time all non-idle tasks were stalled simultaneously, which indicates severe contention where the system is making little forward progress. The avg10, avg60, and avg300 fields are exponentially weighted moving averages over 10, 60, and 300 seconds. The total field is the cumulative stall time in microseconds.
Sustained non-zero some pressure with low full pressure often means the system is reclaiming aggressively but still serving work. Rising full pressure, especially when paired with swap I/O, usually precedes application timeouts or an OOM kill. PSI is also available per cgroup v2 at memory.pressure, which makes it possible to identify which workload group is under pressure instead of blaming the entire host.
The traditional vmstat tool complements PSI by showing paging, swapping, and CPU wait behavior in real time:
vmstat 1 5procs -----------memory---------- ---swap-- -----io---- -system-- -------cpu------- r b swpd free buff cache si so bi bo in cs us sy id wa st 2 0 206848 312456 12044 7234512 0 0 12 34 420 812 12 3 85 0 0 3 1 206848 198234 11892 7112345 4 12 240 120 980 1420 18 5 62 15 0 4 2 212992 154120 11720 6988123 18 64 820 240 1320 1880 16 7 44 33 0 2 1 221184 142008 11604 6876540 12 48 640 180 1104 1602 14 6 51 29 0 1 0 221184 168900 11580 6891020 2 0 120 60 760 1210 11 4 78 7 0The si and so columns show swap-in and swap-out activity in kilobytes per second. Non-zero values during a steady workload indicate that anonymous pages are being moved between RAM and swap. The b column counts processes blocked on I/O, and high wa time shows CPUs waiting for disk. If swap lives on a slow disk, reclaim can degrade latency long before the OOM killer intervenes.
For deeper reclaim counters, read /proc/vmstat:
grep -E 'pgscan|pgsteal|pgmajfault|pswpin|pswpout|oom_kill' /proc/vmstatpgmajfault 18422pswpin 90341pswpout 112004pgscan_kswapd 8831204pgscan_direct 1293340pgsteal_kswapd 8123401pgsteal_direct 1102234oom_kill 3pgscan counts pages scanned for reclaim and pgsteal counts pages successfully reclaimed. When scans grow much faster than steals, the kernel is struggling to find reclaimable pages. pgmajfault increments when a page fault requires disk access, which often rises during cache churn or swap-in. oom_kill provides a quick host-level count of OOM events since boot.
The Reclaim Path: Watermarks, kswapd, and Swap
The kernel uses per-zone watermarks to decide when to reclaim memory in the background and when to block allocating processes. Each memory zone maintains minimum, low, and high watermark levels. When free pages fall below the low watermark, kswapd wakes up and reclaims pages until the free count reaches the high watermark. If an allocation occurs while free pages are below the minimum watermark, the allocating task may perform direct reclaim, stalling in the allocation path until enough memory is freed.
These thresholds can be influenced by vm.min_free_kbytes and vm.watermark_scale_factor. Increasing vm.min_free_kbytes reserves more memory for atomic allocations and reduces the risk of sudden allocation failures, but it also reduces memory available to applications and cache. vm.watermark_scale_factor (default 10, representing 0.1% units) controls the gap between watermarks; larger values make background reclaim start earlier and can reduce direct reclaim latency at the cost of more aggressive background activity.
sysctl vm.min_free_kbytes vm.watermark_scale_factorcat /proc/zoneinfo | grep -E 'Node|zone|pages free|min|low|high' | head -n 20Swap behavior is governed primarily by vm.swappiness. The value ranges from 0 to 200 on modern kernels. A higher value makes the kernel more willing to swap anonymous pages, preserving file cache. A lower value makes the kernel prefer reclaiming file cache before swapping anonymous pages. Setting vm.swappiness to 0 does not disable swap on kernels 3.5 and later; it tells the kernel to avoid swapping unless file cache reclaim is not sufficient.
sysctl vm.swappiness vm.vfs_cache_pressurevm.swappiness = 60vm.vfs_cache_pressure = 100vm.vfs_cache_pressure controls how aggressively the kernel reclaims dentries and inode caches relative to page cache and swap. Values above 100 favor reclaiming directory and inode metadata, which can help on systems with many small files. Values below 100 retain metadata longer, which can improve workloads that repeatedly traverse large directory trees.
Tuning reclaim involves trade-offs. Lower swappiness can keep latency-sensitive processes in RAM, but it increases the chance of dropping hot cache and can trigger OOM kills sooner on bursty anonymous memory usage. Higher swappiness can absorb short spikes by moving cold anonymous pages to disk, but swap on rotational disks or contended network storage can cause severe latency. Early direct reclaim is often less visible than an OOM kill but more damaging to tail latency. The right configuration depends on workload shape, storage speed, and whether the service can tolerate slowdowns better than abrupt termination.
How the OOM Killer Chooses a Process
When reclaim cannot free enough pages to satisfy a request, the kernel enters the OOM path. It can either panic, kill the allocating task, or scan tasks to select a victim. The default behavior on most systems is to select and kill a process, then retry the allocation.
The kernel assigns each task an OOM score exposed in /proc/<pid>/oom_score. This score reflects memory usage factors such as resident set size, swap usage, and memory shared with child processes. Administrators influence selection through /proc/<pid>/oom_score_adj, which accepts values from -1000 to 1000. A value of -1000 marks a process as exempt from OOM killing. A high positive value makes a process a preferred victim.
cat /proc/1/oom_score /proc/1/oom_score_adjpidof postgres | head -n 1 | xargs -I{} sh -c 'echo PID {}; cat /proc/{}/oom_score; cat /proc/{}/oom_score_adj'Systemd services can set this value declaratively:
[Service]OOMScoreAdjust=-900Several kernel parameters change OOM behavior globally:
sysctl vm.panic_on_oom vm.oom_kill_allocating_task vm.oom_dump_tasksvm.panic_on_oom = 0vm.oom_kill_allocating_task = 0vm.oom_dump_tasks = 1With vm.panic_on_oom=0, the kernel invokes the OOM killer. With vm.panic_on_oom=1, it panics, which may be appropriate for clustered systems where a fast reboot and failover is safer than running in a degraded state. vm.oom_kill_allocating_task=1 kills the task that triggered the allocation failure instead of scanning for the highest scoring victim, which can be faster and more predictable in some workloads. vm.oom_dump_tasks=1 prints a task list in the kernel log during OOM events, providing useful context when diagnosing which processes contributed to pressure.
Protecting a critical process with oom_score_adj=-1000 has a clear downside: if that process is the main memory consumer, the kernel will kill other processes instead, potentially destabilizing the system or leaving the protected process running without its dependencies. On database servers, protecting the database process while leaving backup agents, exporters, and sidecars unprotected is sometimes reasonable. On application hosts, it is usually better to enforce memory limits per service so the offending service is contained.
Finding and Interpreting OOM Events
OOM investigations should start with kernel logs because they record the trigger, the selected victim, and the memory state at the time of the kill. On systems using systemd-journald, journalctl provides the most convenient access. On other systems, /var/log/kern.log or /var/log/messages may contain the same entries.
journalctl -k -b -p err | grep -i "out of memory"journalctl -k -b -1 | grep -iE "oom-killer|killed process|oom_reaper"dmesg -T | grep -iE "invoked oom-killer|Out of memory|Killed process"A typical kernel OOM report looks like this:
Nov 19 08:42:17 app01 kernel: java invoked oom-killer: gfp_mask=0x140cca(GFP_HIGHUSER_MOVABLE|__GFP_COMP), order=0, oom_score_adj=0Nov 19 08:42:17 app01 kernel: CPU: 2 PID: 18342 Comm: java Not tainted 6.8.0-48-generic #48-UbuntuNov 19 08:42:17 app01 kernel: Mem-Info:Nov 19 08:42:17 app01 kernel: active_anon:1834210 inactive_anon:41234 isolated_anon:0Nov 19 08:42:17 app01 kernel: active_file:18234 inactive_file:20456 isolated_file:0Nov 19 08:42:17 app01 kernel: Node 0 DMA free:15836kB boost:0kB min:32kB low:44kB high:56kB reserved_highatomic:0KBNov 19 08:42:17 app01 kernel: Node 0 DMA32 free:120456kB boost:0kB min:1204kB low:1504kB high:1804kB reserved_highatomic:0KBNov 19 08:42:17 app01 kernel: Out of memory: Killed process 18321 (java) total-vm:12582912kB, anon-rss:7340032kB, file-rss:2048kB, shmem-rss:0kB, UID:1001 pgtables:16384kB oom_score_adj:0Nov 19 08:42:17 app01 kernel: oom_reaper: reaped process 18321 (java), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kBThe first line identifies which task triggered the allocation that led to the OOM path, not necessarily the task that was killed. The Out of memory line identifies the victim and reports memory usage. total-vm is the total virtual memory mapped by the process, which can be much larger than physical usage. anon-rss is the anonymous resident memory and usually the most relevant number when investigating heap growth. file-rss and shmem-rss show file-backed and shared memory resident pages. oom_score_adj confirms whether the process was biased for or against killing.
In containerized environments, the kernel log may be on the host, while the container runtime reports a simplified status. A container terminated by a memory limit often shows exit code 137, which corresponds to SIGKILL.
docker inspect --format '{{.State.OOMKilled}} {{.State.ExitCode}}' my-containertrue 137On cgroup v2 systems, the memory events file for the workload provides a direct counter:
cat /sys/fs/cgroup/system.slice/myapp.service/memory.eventslow 0high 4max 2oom 1oom_kill 1oom_group_kill 0high counts throttling or reclaim events at the memory.high boundary. max counts hits against memory.max. oom and oom_kill distinguish between an OOM condition and an actual kernel kill, which is useful when memory.oom.group or userspace OOM handling is involved.
Tuning the Kernel with sysctl Parameters
Kernel memory behavior can be adjusted at runtime with sysctl and persisted in configuration files under /etc/sysctl.d/. Changes should be applied incrementally and validated under load, because a value that protects one workload can harm another.
A baseline configuration for a general-purpose Linux server might look like this:
# Keep a moderate reserve for burst allocations and kernel needs.vm.min_free_kbytes = 131072
# Start background reclaim earlier to reduce direct reclaim stalls.vm.watermark_scale_factor = 200
# Prefer reclaiming page cache before swapping anonymous pages.vm.swappiness = 10
# Use heuristic overcommit unless the workload requires strict accounting.vm.overcommit_memory = 0
# Dump task list on OOM for easier diagnosis.vm.oom_dump_tasks = 1
# Let the kernel choose a victim instead of panicking.vm.panic_on_oom = 0Apply and verify the settings:
sudo sysctl -p /etc/sysctl.d/99-memory.confsysctl vm.min_free_kbytes vm.watermark_scale_factor vm.swappiness vm.overcommit_memoryThe vm.overcommit_memory setting deserves careful consideration. Mode 0 applies a heuristic that allows overcommit but rejects obviously excessive requests. Mode 1 allows allocations to succeed until memory is truly exhausted, which can increase memory utilization for sparse allocations but makes OOM kills more likely. Mode 2 enforces a strict commit limit calculated from RAM, swap, and vm.overcommit_ratio.
sysctl vm.overcommit_memory vm.overcommit_ratiogrep -E 'CommitLimit|Committed_AS' /proc/meminfoMode 2 is useful for systems that need allocation failures instead of surprise kills, such as certain batch hosts or environments where applications handle ENOMEM correctly. Many applications do not handle allocation failures gracefully, so strict overcommit can replace an OOM kill with application crashes or error paths that are equally disruptive. The operational choice is between explicit capacity limits and optimistic allocation with late failure.
Controlling Memory with cgroups and systemd
Host-level tuning cannot isolate noisy neighbors. Cgroups provide per-service or per-container memory boundaries so one workload cannot consume all host memory unnoticed. On modern systems using cgroup v2, the relevant controls are memory.current, memory.high, memory.max, memory.swap.max, and memory.events.
memory.max is a hard limit. When a cgroup reaches it, the kernel tries reclaim within the cgroup; if reclaim fails, it triggers an OOM condition for that cgroup. memory.high is a throttle limit. Exceeding it causes aggressive reclaim and throttling, which slows the workload but can avoid an immediate kill. This distinction is useful for services that can tolerate backpressure better than abrupt termination.
A systemd service can declare these limits in a unit file:
[Unit]Description=Example memory-limited applicationAfter=network.target
[Service]ExecStart=/usr/local/bin/myappUser=myappGroup=myappRestart=on-failure
# Hard cap: kernel OOM kills within the service when exceeded and unreclaimable.MemoryMax=2G
# Soft cap: throttle and reclaim before the hard cap.MemoryHigh=1700M
# Limit swap usage for this service.MemorySwapMax=256M
# Make the service a likely victim inside its scope if limits are hit.OOMPolicy=kill
[Install]WantedBy=multi-user.targetAfter changing the unit, reload and restart the service:
sudo systemctl daemon-reloadsudo systemctl restart myapp.servicesystemctl show myapp.service -p MemoryCurrent -p MemoryHigh -p MemoryMaxYou can inspect the live cgroup values directly:
systemctl status myapp.servicecat /sys/fs/cgroup/system.slice/myapp.service/memory.currentcat /sys/fs/cgroup/system.slice/myapp.service/memory.highcat /sys/fs/cgroup/system.slice/myapp.service/memory.maxcat /sys/fs/cgroup/system.slice/myapp.service/memory.eventsCgroup limits do not remove the need for application sizing. A Java process with -Xmx4g running inside a 2 GiB cgroup will fail because the JVM heap is only part of its total footprint. Native memory, thread stacks, metaspace, direct buffers, and libraries also consume RAM. In containers, runtime flags such as docker run -m 2g or Kubernetes resource limits map to cgroup constraints, so the same accounting rules apply.
Userspace OOM Protection: earlyoom and systemd-oomd
The kernel OOM killer acts when the system is already in a critical state. Userspace daemons can intervene earlier by monitoring memory pressure and terminating selected processes or cgroups before the host becomes unresponsive.
earlyoom is a lightweight daemon that polls available memory and swap. When both fall below configured thresholds, it sends signals (usually SIGTERM, then SIGKILL) to processes with high oom_score. It works on systems with or without cgroup v2 and is straightforward to deploy.
sudo apt-get install earlyoomsystemctl status earlyoomcat /etc/default/earlyoomA common configuration on Debian or Ubuntu looks like:
EARLYOOM_ARGS="-r 3600 -m 5 -s 5 -n --avoid '(^|/)(sshd|systemd|systemd-logind)$' --prefer '(^|/)(java|node|python)$'"In this example, -m 5 triggers when available memory falls below 5 percent, and -s 5 triggers when available swap falls below 5 percent. The --avoid and --prefer patterns influence target selection. The trade-off is that earlyoom uses polling and heuristics rather than kernel-level pressure accounting, so thresholds must be tuned to avoid killing workloads during brief, recoverable spikes.
systemd-oomd integrates with cgroup v2 and PSI. Instead of polling global memory percentages alone, it can act on sustained memory pressure for a cgroup. On Ubuntu 22.04 and later, it is commonly enabled for desktop user slices to prevent a runaway application from freezing the session. Fedora also enables it by default on supported releases.
systemctl status systemd-oomdcat /etc/systemd/oomd.conf[OOM]SwapUsedLimit=90%DefaultMemoryPressureLimit=60%DefaultMemoryPressureDurationSec=20sA systemd-oomd kill is logged differently from a kernel OOM kill:
Nov 19 09:18:44 laptop systemd-oomd[652]: Killed /user.slice/user-1000.slice/user@1000.service/app.slice/firefox.service due to memory pressure for /user.slice/user-1000.slice/user@1000.service/app.slice/firefox.service being 62.34% > 60.00% for > 20s with reclaim activityThis distinction matters during troubleshooting. A kernel OOM log points to host or cgroup memory exhaustion at the allocator level. A systemd-oomd log points to a pressure policy decision. Disabling systemd-oomd without addressing the underlying memory pressure usually restores the older failure mode: a frozen system followed by a kernel OOM kill.
Troubleshooting Real Memory Failures
Memory incidents often present as application crashes, slowdowns, or SSH sessions that become unresponsive. The fastest path to a fix is to identify the failure layer: kernel OOM, cgroup limit, userspace OOM daemon, application-level allocation error, or swap-induced thrashing.
Kernel OOM kill of an application process
The kernel log shows the victim and its resident memory usage:
Nov 19 08:42:17 app01 kernel: Out of memory: Killed process 18321 (java) total-vm:12582912kB, anon-rss:7340032kB, file-rss:2048kB, shmem-rss:0kB, UID:1001 pgtables:16384kB oom_score_adj:0The immediate cause is host or cgroup memory exhaustion at the time of allocation. The root cause is usually an undersized memory budget for the workload’s real footprint. For a Java service, -Xmx controls heap size, but the process also uses metaspace, thread stacks, compiled code, garbage collector structures, direct byte buffers, and native libraries. In a 8 GiB container, setting -Xmx8g leaves no room for non-heap memory.
ps -p 18321 -o pid,rss,vsz,cmdgrep -iE 'VmRSS|VmSize|VmSwap' /proc/18321/statusIf the process is no longer running, inspect the service manager and kernel counters:
systemctl status myapp.servicejournalctl -u myapp.service -bgrep oom_kill /proc/vmstatA practical fix is to set a container-aware heap limit and keep total JVM usage below the cgroup limit. For example, on JDK 11 or later:
java -XX:MaxRAMPercentage=75.0 -XX:InitialRAMPercentage=50.0 -jar /opt/myapp/app.jarThis does not guarantee safety for every workload, so the limit must be validated with production-like traffic and monitored through memory.current, heap metrics, and native memory tracking when available.
Container terminated with exit code 137
A container runtime may report a kill without showing kernel details in the application logs:
docker logs my-containerdocker inspect --format '{{.State.Status}} {{.State.OOMKilled}} {{.State.ExitCode}}' my-containerexited true 137Exit code 137 indicates SIGKILL. When OOMKilled is true, the cgroup memory limit was exceeded. In Kubernetes, the same event appears as OOMKilled in pod status and kubectl describe pod output. The fix is to measure actual usage, raise the limit, reduce the working set, or add a MemoryHigh throttle below MemoryMax so the workload slows before it is killed. Raising limits without profiling can simply delay the next failure and increase node-level pressure.
Fork fails despite visible free memory
A shell session may fail to create processes even when free reports available memory:
-bash: fork: Cannot allocate memoryThis error can come from several conditions. Strict overcommit (vm.overcommit_memory=2) may reject the allocation because Committed_AS is near CommitLimit. The system may have hit process or thread limits (nproc, PID exhaustion), or memory cgroups may be constrained. Start by checking commit accounting and limits:
sysctl vm.overcommit_memorygrep -E 'CommitLimit|Committed_AS' /proc/meminfoulimit -ucat /sys/fs/cgroup/user.slice/user-1000.slice/pids.currentcat /sys/fs/cgroup/user.slice/user-1000.slice/pids.maxIf Committed_AS is close to CommitLimit, either reduce reserved allocations, increase swap and vm.overcommit_ratio under mode 2, or switch to a policy that matches application behavior. If PID or cgroup process counts are at their limit, the problem is not RAM capacity and increasing memory will not help.
systemd-oomd kills user applications under pressure
On a desktop or developer workstation, the session may lose applications with a log entry like:
Nov 19 09:18:44 laptop systemd-oomd[652]: Killed /user.slice/user-1000.slice/user@1000.service/app.slice/firefox.service due to memory pressure for /user.slice/user-1000.slice/user@1000.service/app.slice/firefox.service being 62.34% > 60.00% for > 20s with reclaim activityThe root cause is sustained PSI pressure inside the user cgroup, often from browsers, build tools, or IDEs competing for memory. The policy is working as designed, but the threshold or workload mix may not match the system’s capacity. You can inspect pressure directly:
cat /sys/fs/cgroup/user.slice/user-1000.slice/memory.pressurecat /sys/fs/cgroup/user.slice/user-1000.slice/memory.currentAdjusting /etc/systemd/oomd.conf to a higher duration or different pressure limit can reduce premature kills, but it may also bring back UI freezes. Adding swap on fast storage, reducing parallel build jobs, or lowering per-application memory use addresses the underlying pressure more directly.
Severe slowdown without an OOM kill
Not every memory incident ends with a kill. A host can enter a state where reclaim and swap activity dominate, causing high latency for all workloads. Symptoms include elevated load, blocked processes, and rising PSI full averages.
cat /proc/pressure/memoryvmstat 1 5pidstat -d 1 5some avg10=48.20 avg60=35.10 avg300=12.40 total=982340112full avg10=22.30 avg60=14.80 avg300=5.10 total=401223998When si and so are active and disk wait is high, the system is thrashing. The fix depends on whether the working set exceeds physical RAM. Adding RAM or reducing concurrency is the durable solution. Short-term mitigation can include lowering swap usage for specific services with MemorySwapMax=0, increasing MemoryHigh throttling to slow memory growth earlier, or stopping nonessential jobs. Disabling swap entirely can prevent swap thrashing but removes a buffer that might have absorbed temporary spikes, so the next pressure event is more likely to end in an OOM kill.
Distribution and Kernel Version Differences
Memory management behavior is consistent at the kernel level, but defaults, userspace tooling, and OOM policies vary across distributions and releases. These differences affect where to look for logs and which protection mechanisms are active by default.
| Distribution | Typical kernel | Cgroup default | Userspace OOM handling | Notes |
|---|---|---|---|---|
| Ubuntu 22.04 LTS | 5.15 | Unified cgroup v2 | systemd-oomd enabled in common desktop installs | PSI available; user slice pressure kills can surprise server-style workflows on desktops |
| Ubuntu 24.04 LTS | 6.8 | Unified cgroup v2 | systemd-oomd with updated systemd defaults | Improved cgroup and PSI integration in newer systemd releases |
| Debian 12 | 6.1 | Unified cgroup v2 | No default aggressive desktop OOM daemon in minimal server installs | Kernel OOM killer behavior remains the primary backstop unless additional tools are installed |
| RHEL 9 | 5.14 (backported features) | Unified cgroup v2 | Kernel OOM killer by default | Enterprise environments often rely on systemd resource controls and monitoring policies |
| RHEL 8 | 4.18 (heavily backported) | cgroup v1 common in older setups, v2 available | Kernel OOM killer by default | PSI and cgroup v2 workflows differ from newer releases; verify with `mount |
| Fedora 34 and later | Varies by release | Unified cgroup v2 | systemd-oomd enabled by default | Early adopter of cgroup v2 based pressure management |
To confirm the active cgroup mode and PSI support on a running system:
stat -fc %T /sys/fs/cgroup/cat /proc/filesystems | grep cgrouptest -r /proc/pressure/memory && echo "PSI supported" || echo "PSI not available"On a unified cgroup v2 system, stat -fc %T /sys/fs/cgroup/ reports cgroup2fs. On hybrid or v1 systems, memory controls may live under paths such as /sys/fs/cgroup/memory/ with different file names (memory.limit_in_bytes, memory.usage_in_bytes). Automation scripts should detect the hierarchy before reading or writing control files.
Case Study: Recovering a Database Server from Repeated OOM Kills
Consider a 16 GiB virtual machine running PostgreSQL 15 on Ubuntu 24.04, with 4 GiB of swap on an SSD and no per-service memory cap. Every few days during batch reporting, the database process disappears and applications report connection failures. The service restarts automatically, but the incident repeats.
The first step is to confirm the kill source and identify the victim:
journalctl -k -b -1 | grep -iE "oom-killer|Out of memory|Killed process"Nov 18 02:14:09 db01 kernel: postgres invoked oom-killer: gfp_mask=0x140cca(GFP_HIGHUSER_MOVABLE|__GFP_COMP), order=0, oom_score_adj=0Nov 18 02:14:09 db01 kernel: Out of memory: Killed process 14231 (postgres) total-vm:12485632kB, anon-rss:8234512kB, file-rss:1024kB, shmem-rss:409600kB, UID:114 pgtables:18240kB oom_score_adj:0The kernel killed a PostgreSQL backend with roughly 8 GiB anonymous RSS and 400 MiB shared memory resident. The next step is to check host pressure around the event window:
sar -r -f /var/log/sysstat/sa18grep -E 'pgscan|pgsteal|pswpin|pswpout|oom_kill' /proc/vmstatcat /proc/pressure/memoryIf sar shows available memory collapsing during the reporting window and PSI full averages spiking, the issue is not a single rogue process but a workload peak exceeding the host budget. PostgreSQL memory usage is influenced by shared_buffers, work_mem, maintenance_work_mem, and the number of concurrent connections. A reporting burst that runs many parallel queries can multiply work_mem allocations, even when baseline usage looks stable.
sudo -u postgres psql -c "SHOW shared_buffers;"sudo -u postgres psql -c "SHOW work_mem;"sudo -u postgres psql -c "SHOW max_connections;"Suppose the configuration uses shared_buffers = 4GB, work_mem = 64MB, and max_connections = 200. Under a burst of complex reporting queries, dozens of operations can each allocate work memory, and total usage can exceed what remains after shared buffers, OS needs, page cache, and other agents. The fix is layered. Reducing work_mem for reporting roles, limiting concurrency with a pooler, and scheduling heavy reports outside peak hours reduce peak demand. Adding MemoryHigh and MemoryMax to noncritical side services (exporters, backup agents, ad hoc jobs) prevents them from contributing to host exhaustion.
[Service]MemoryHigh=300MMemoryMax=400MFor the database itself, setting oom_score_adj to a lower value can protect it from being the first victim, but only if the remaining workload can be sacrificed safely. A more durable approach is to keep total host allocation below physical RAM with headroom for spikes, monitor memory.pressure in the PostgreSQL service cgroup, and alert on sustained some pressure before it becomes full pressure. After applying changes, validation should include replaying the reporting workload while watching vmstat 1, cat /proc/pressure/memory, and journalctl -kf.
Building a Practical Memory Safety Baseline
A reliable memory baseline combines measurement, limits, and alerting. Measurement starts with collecting MemAvailable, swap usage, PSI averages, pgscan and pgsteal rates, and cgroup memory.events counters. These signals distinguish a healthy cache-heavy system from a host that is spending its time reclaiming memory. Alerting on a single “low free memory” threshold produces noise; alerting on sustained PSI pressure, rising swap activity, or repeated memory.max hits is more actionable.
Limits should be explicit wherever possible. Systemd MemoryHigh and MemoryMax, container memory limits, and database connection controls turn unbounded memory growth into a contained failure. The trade-off is that strict limits require accurate sizing and ongoing review as workloads change. A limit set too low causes throttling or kills during legitimate peaks. A limit set too high provides no protection.
Kernel tuning should remain conservative unless measurements justify a change. A small increase to vm.min_free_kbytes, earlier background reclaim through vm.watermark_scale_factor, and a workload-appropriate vm.swappiness value can reduce direct reclaim stalls. Enabling vm.oom_dump_tasks improves post-incident visibility. Userspace OOM daemons such as earlyoom or systemd-oomd can improve responsiveness on systems where a complete host stall is worse than terminating a selected workload, but they add another policy layer that must be understood when reading logs.
The operational goal is not to eliminate every OOM kill at any cost. It is to make memory exhaustion visible early, constrain the blast radius to the workload that exceeded its budget, and preserve enough diagnostic evidence to correct the underlying sizing or configuration problem before the next pressure event.