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

Understanding Linux Memory Pressure and the OOM Killer in Production

Diagnose Linux memory pressure, read PSI metrics, interpret OOM killer logs, and tune sysctl and cgroup settings to prevent out-of-memory kills.

masdzub@website:~$ cat ~/articles/understanding-linux-memory-pressure-and-the-oom-killer.aspx.md
# 1 file · 25 min read · topic: linux · status: published

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.

Terminal window
free -h
total used free shared buff/cache available
Mem: 15Gi 6.2Gi 402Mi 312Mi 8.9Gi 8.1Gi
Swap: 4.0Gi 202Mi 3.8Gi

In 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:

Terminal window
cat /proc/meminfo
MemTotal: 16384256 kB
MemFree: 412340 kB
MemAvailable: 8234512 kB
Buffers: 234120 kB
Cached: 7123456 kB
SwapCached: 12400 kB
Active: 6234512 kB
Inactive: 3456789 kB
Active(anon): 2123456 kB
Inactive(anon): 823456 kB
Active(file): 4111056 kB
Inactive(file): 2633333 kB
SwapTotal: 4194304 kB
SwapFree: 3987654 kB
Dirty: 1024 kB
Writeback: 0 kB
AnonPages: 2845123 kB
Mapped: 512340 kB
Shmem: 412345 kB
KReclaimable: 412345 kB
Slab: 623456 kB
SReclaimable: 412345 kB
SUnreclaim: 211111 kB
CommitLimit: 12386432 kB
Committed_AS: 9876543 kB

Several 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.

Terminal window
cat /proc/pressure/memory
some avg10=2.45 avg60=1.10 avg300=0.35 total=18423012
full avg10=0.50 avg60=0.20 avg300=0.05 total=3210456

The 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:

Terminal window
vmstat 1 5
procs -----------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 0

The 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:

Terminal window
grep -E 'pgscan|pgsteal|pgmajfault|pswpin|pswpout|oom_kill' /proc/vmstat
pgmajfault 18422
pswpin 90341
pswpout 112004
pgscan_kswapd 8831204
pgscan_direct 1293340
pgsteal_kswapd 8123401
pgsteal_direct 1102234
oom_kill 3

pgscan 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.

Terminal window
sysctl vm.min_free_kbytes vm.watermark_scale_factor
cat /proc/zoneinfo | grep -E 'Node|zone|pages free|min|low|high' | head -n 20

Swap 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.

Terminal window
sysctl vm.swappiness vm.vfs_cache_pressure
vm.swappiness = 60
vm.vfs_cache_pressure = 100

vm.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.

Terminal window
cat /proc/1/oom_score /proc/1/oom_score_adj
pidof 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=-900

Several kernel parameters change OOM behavior globally:

Terminal window
sysctl vm.panic_on_oom vm.oom_kill_allocating_task vm.oom_dump_tasks
vm.panic_on_oom = 0
vm.oom_kill_allocating_task = 0
vm.oom_dump_tasks = 1

With 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.

Terminal window
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=0
Nov 19 08:42:17 app01 kernel: CPU: 2 PID: 18342 Comm: java Not tainted 6.8.0-48-generic #48-Ubuntu
Nov 19 08:42:17 app01 kernel: Mem-Info:
Nov 19 08:42:17 app01 kernel: active_anon:1834210 inactive_anon:41234 isolated_anon:0
Nov 19 08:42:17 app01 kernel: active_file:18234 inactive_file:20456 isolated_file:0
Nov 19 08:42:17 app01 kernel: Node 0 DMA free:15836kB boost:0kB min:32kB low:44kB high:56kB reserved_highatomic:0KB
Nov 19 08:42:17 app01 kernel: Node 0 DMA32 free:120456kB boost:0kB min:1204kB low:1504kB high:1804kB reserved_highatomic:0KB
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:0
Nov 19 08:42:17 app01 kernel: oom_reaper: reaped process 18321 (java), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB

The 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.

Terminal window
docker inspect --format '{{.State.OOMKilled}} {{.State.ExitCode}}' my-container
true 137

On cgroup v2 systems, the memory events file for the workload provides a direct counter:

Terminal window
cat /sys/fs/cgroup/system.slice/myapp.service/memory.events
low 0
high 4
max 2
oom 1
oom_kill 1
oom_group_kill 0

high 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:

/etc/sysctl.d/99-memory.conf
# 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 = 0

Apply and verify the settings:

Terminal window
sudo sysctl -p /etc/sysctl.d/99-memory.conf
sysctl vm.min_free_kbytes vm.watermark_scale_factor vm.swappiness vm.overcommit_memory

The 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.

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

Mode 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:

/etc/systemd/system/myapp.service
[Unit]
Description=Example memory-limited application
After=network.target
[Service]
ExecStart=/usr/local/bin/myapp
User=myapp
Group=myapp
Restart=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.target

After changing the unit, reload and restart the service:

Terminal window
sudo systemctl daemon-reload
sudo systemctl restart myapp.service
systemctl show myapp.service -p MemoryCurrent -p MemoryHigh -p MemoryMax

You can inspect the live cgroup values directly:

Terminal window
systemctl status myapp.service
cat /sys/fs/cgroup/system.slice/myapp.service/memory.current
cat /sys/fs/cgroup/system.slice/myapp.service/memory.high
cat /sys/fs/cgroup/system.slice/myapp.service/memory.max
cat /sys/fs/cgroup/system.slice/myapp.service/memory.events

Cgroup 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.

Terminal window
sudo apt-get install earlyoom
systemctl status earlyoom
cat /etc/default/earlyoom

A common configuration on Debian or Ubuntu looks like:

/etc/default/earlyoom
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.

Terminal window
systemctl status systemd-oomd
cat /etc/systemd/oomd.conf
/etc/systemd/oomd.conf
[OOM]
SwapUsedLimit=90%
DefaultMemoryPressureLimit=60%
DefaultMemoryPressureDurationSec=20s

A 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 activity

This 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:0

The 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.

Terminal window
ps -p 18321 -o pid,rss,vsz,cmd
grep -iE 'VmRSS|VmSize|VmSwap' /proc/18321/status

If the process is no longer running, inspect the service manager and kernel counters:

Terminal window
systemctl status myapp.service
journalctl -u myapp.service -b
grep oom_kill /proc/vmstat

A 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:

Terminal window
java -XX:MaxRAMPercentage=75.0 -XX:InitialRAMPercentage=50.0 -jar /opt/myapp/app.jar

This 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:

Terminal window
docker logs my-container
docker inspect --format '{{.State.Status}} {{.State.OOMKilled}} {{.State.ExitCode}}' my-container
exited true 137

Exit 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 memory

This 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:

Terminal window
sysctl vm.overcommit_memory
grep -E 'CommitLimit|Committed_AS' /proc/meminfo
ulimit -u
cat /sys/fs/cgroup/user.slice/user-1000.slice/pids.current
cat /sys/fs/cgroup/user.slice/user-1000.slice/pids.max

If 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 activity

The 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:

Terminal window
cat /sys/fs/cgroup/user.slice/user-1000.slice/memory.pressure
cat /sys/fs/cgroup/user.slice/user-1000.slice/memory.current

Adjusting /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.

Terminal window
cat /proc/pressure/memory
vmstat 1 5
pidstat -d 1 5
some avg10=48.20 avg60=35.10 avg300=12.40 total=982340112
full avg10=22.30 avg60=14.80 avg300=5.10 total=401223998

When 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.

DistributionTypical kernelCgroup defaultUserspace OOM handlingNotes
Ubuntu 22.04 LTS5.15Unified cgroup v2systemd-oomd enabled in common desktop installsPSI available; user slice pressure kills can surprise server-style workflows on desktops
Ubuntu 24.04 LTS6.8Unified cgroup v2systemd-oomd with updated systemd defaultsImproved cgroup and PSI integration in newer systemd releases
Debian 126.1Unified cgroup v2No default aggressive desktop OOM daemon in minimal server installsKernel OOM killer behavior remains the primary backstop unless additional tools are installed
RHEL 95.14 (backported features)Unified cgroup v2Kernel OOM killer by defaultEnterprise environments often rely on systemd resource controls and monitoring policies
RHEL 84.18 (heavily backported)cgroup v1 common in older setups, v2 availableKernel OOM killer by defaultPSI and cgroup v2 workflows differ from newer releases; verify with `mount
Fedora 34 and laterVaries by releaseUnified cgroup v2systemd-oomd enabled by defaultEarly adopter of cgroup v2 based pressure management

To confirm the active cgroup mode and PSI support on a running system:

Terminal window
stat -fc %T /sys/fs/cgroup/
cat /proc/filesystems | grep cgroup
test -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:

Terminal window
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=0
Nov 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:0

The 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:

Terminal window
sar -r -f /var/log/sysstat/sa18
grep -E 'pgscan|pgsteal|pswpin|pswpout|oom_kill' /proc/vmstat
cat /proc/pressure/memory

If 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.

Terminal window
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.

/etc/systemd/system/node-exporter.service.d/memory.conf
[Service]
MemoryHigh=300M
MemoryMax=400M

For 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.

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.