Mental model
When Linux free physical DRAM tightens cleanly under workload spikes, kernel kswapd and direct reclaim evict clean filesystem Page Cache cleanly or write idle anonymous heap pages out cleanly to disk Swap (controlled by vm.swappiness). If neither cache reclaim nor swap clears allocation deficits—or a container breaches its hard cgroup v2 memory.max wall cleanly—the kernel Out-Of-Memory (OOM) Killer computes per-process oom_score metrics and immediately sends uncatchable SIGKILL cleanly to protect kernel stability.
Learning outcomes
- Contrast filesystem Page Cache eviction cleanly against anonymous heap swapping via
vm.swappiness(0–200, noting modern zram vs SSD swap trade-offs cleanly). - Distinguish global host OOM (
protected via oom_score_adj = -1000on critical system daemons) cleanly from Kubernetescgroup v2per-container OOM (OOMKilledExit 137) cleanly! - Prevent catastrophic
"wrong target killed"database outages (Postgres killed cleanly while leaking log daemon survived) using explicitoom_score_adj,memory.min/memory.lowcgroup guarantees, andPSImonitoring cleanly.
Theory
Teams routinely discover Linux OOM semantics painfully at 2 AM cleanly cleanly when a tiny runaway log collector pushes node memory to 100%, prompting the kernel OOM Killer cleanly to shoot postgresql (consuming 70% RAM -> highest oom_score!) directly in the head rather than killing the tiny leaking culprit! Mastering three core controls avoids both silent database assassinations and 10-second swap freezes:
| Memory Pressure Control | Mechanism & Range | Production Behavior | When / How to Apply |
|---|---|---|---|
vm.swappiness (0..200, default 60) | Relative preference reclaiming anon heap pages (swap) vs. disk cache (file) | High values swap heap aggressively cleanly even while Page Cache stays cached; 1 swaps almost solely under severe panic | Set low (1–10) on latency-strict DBs / AI serving (keeping heap in RAM) |
oom_score_adj (-1000 .. +1000) | Signed bias added onto base oom_score (% RAM used) | -1000 exempts critical PIDs from global OOM killing; +500 targets disposable batch caches cleanly first | Protect systemd, sshd, postgresql, kubelet (always leave container workers killable cleanly!) |
Cgroup v2 memory.max & memory.oom.group | Hard container memory cap (exceeding kills inside cgroup cleanly without harming neighbors!) | memory.oom.group=1 kills entire leaky worker group cleanly instead of leaving half-dead zombie parent processes cleanly | Enforced automatically by Kubernetes resources.limits.memory cleanly |
Watch out too for Linux PSI (Pressure Stall Information at /proc/pressure/memory): tracking some / full microsecond stall percentages detects slow thrashing death minutes before an actual OOMKilled (Exit 137) hits cleanly—giving autoscalers or admission circuits cleanly time to shed requests gracefully!
bash#!/usr/bin/env bashset -euo pipefail# Inspect real Linux Pressure Stall Information (thrashing precedes OOM!)cat /proc/pressure/memory# Keep application heap pages strictly off slow swap unless near exhaustionsysctl -w vm.swappiness=10# Protect primary Postgres server PID from global host OOM Killer cleanly (-1000 = exempt)PG_PID="$(pgrep -o postgres || true)"if [[ -n "$PG_PID" ]]; thenecho -1000 > "/proc/${PG_PID}/oom_score_adj"fi# Inspect top OOM candidates (score out of ~1000+ after adjustment)ps -eo pid,comm,oom_score,oom_score_adj --sort=-oom_score | head -n 10
Trade-offs
Configuring modest high-speed compressed in-RAM swap (zram) or fast NVMe swap with low vm.swappiness = 1..10 absorbs brief temporary memory allocations gracefully cleanly on general app nodes instead of jumping straight onto instant process SIGKILL crashes cleanly. Conversely, inside ultra-low-latency GPU inference workers and dedicated transactional Postgres servers cleanly (where major swap page faults destroy SLA predictability cleanly), keeping swap tightly bounded or disabled cleanly while enforcing strict cgroup admission caps (Guaranteed QoS) cleanly fails overloaded edge jobs early instead of hanging entire nodes in 20-second swap thrashing!
Failure modes and misconceptions
- Allowing Unprotected Master Databases (
oom_score_adj = 0): Because healthy databases intentionally claim70–85%of host RAM cleanly, defaultoom_scoremarks PostgreSQL/Redis cleanly as Victim #1 whenever any minor neighbor leaks memory! - Assuming
vm.swappiness = 0Disables Swap Completely (Modern Kernels): On modern Linux (>= 3.5), setting0still permits emergency anonymous swapping when memory runs critically scarce (whereas cgroup limits / swapoff controls swap usage completely);1preserves safer last-resort emergency guard cleanly. - Disabling Swap Blindly on Tiny Dev VPS Hosts Without Headroom: Running zero swap on memory-tight containers forces abrupt instant
SIGKILLcrashes cleanly whenever transient idle linker/compiler pages could safely page out briefly cleanly. - Putting
-1000on Untrusted Worker Subprocesses: Marking leaky child workers-1000leaves the kernel OOM Killer zero legal targets except locking up or killing SSH/kubelet!
Decision scenario
A shared Kubernetes inference/data host (128 GB RAM) crashed PostgreSQL cleanly with SIGKILL (dmesg: Out of memory: Killed process postgres) after an ETL container briefly consumed an unexpected 24 GB cache surge, while earlier DB queries experienced 12-second freezes cleanly from anonymous swapping. Harden Postgres cleanly via dedicated cgroup v2 QoS (requests == limits, oom_score_adj = -997), tune vm.swappiness = 10, monitor /proc/pressure/memory PSI alarms cleanly, and bound ETL workers inside strict container memory.max walls cleanly.