FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Linux Swap Subsystem & OOM Killer

Page swappiness, Out-Of-Memory (OOM) killer scoring (oom_score), and memory pressure cgroups.

Freshness: current•15 min read•Computer Science and Programming

Key Learning Outcomes

  • ✓Configure swappiness and memory pressure thresholds
  • ✓Protect critical daemon processes from OOM killer termination
Full Technical Reference Document

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.

Physical RAM / cgroup limit tightens
Kernel reclaims Page Cache vs anonymous Swap
PSI memory pressure spikes cleanly
Zero reclaim -> Trigger kernel / cgroup OOM
Select highest oom_score + oom_score_adj
Issue uncatchable SIGKILL to sacrifice process
Conceptual teaching model synthesized from:Linux Kernel Kernel.org Official Architecture & Systems DocumentationSite Reliability Engineering

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 = -1000 on critical system daemons) cleanly from Kubernetes cgroup v2 per-container OOM (OOMKilled Exit 137) cleanly!
  • Prevent catastrophic "wrong target killed" database outages (Postgres killed cleanly while leaking log daemon survived) using explicit oom_score_adj, memory.min / memory.low cgroup guarantees, and PSI monitoring 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 ControlMechanism & RangeProduction BehaviorWhen / 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 panicSet 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 firstProtect systemd, sshd, postgresql, kubelet (always leave container workers killable cleanly!)
Cgroup v2 memory.max & memory.oom.groupHard 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 cleanlyEnforced 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 bash
set -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 exhaustion
sysctl -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" ]]; then
echo -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 claim 70–85% of host RAM cleanly, default oom_score marks PostgreSQL/Redis cleanly as Victim #1 whenever any minor neighbor leaks memory!
  • Assuming vm.swappiness = 0 Disables Swap Completely (Modern Kernels): On modern Linux (>= 3.5), setting 0 still permits emergency anonymous swapping when memory runs critically scarce (whereas cgroup limits / swapoff controls swap usage completely); 1 preserves 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 SIGKILL crashes cleanly whenever transient idle linker/compiler pages could safely page out briefly cleanly.
  • Putting -1000 on Untrusted Worker Subprocesses: Marking leaky child workers -1000 leaves 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.

Reflect before revealing the guide

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next