Skip to main content
KBY Technologies Logo

Stopping Swap Thrashing With OOM Killer Tuning

How PSI thresholds, oom_score_adj weighting and systemd-oomd close the gap the kernel OOM killer leaves open during swap thrashing.

KBY Technologies12 min read
Stopping Swap Thrashing With OOM Killer Tuning

Underlined words are defined in the KBY Lexicon. Tap or click one to see what it means.

A desktop or build server locking up under memory pressure while free -h still reports available swap is one of the most misdiagnosed failures in systems administration. The machine becomes unresponsive for thirty to ninety seconds, the mouse cursor freezes, sessions time out, and then — eventually — something gets killed.

The instinctive fix is to add more swap. The correct fix is OOM killer tuning, because the default kernel out-of-memory killer is a reactive, last-resort mechanism that only fires once allocation genuinely fails. It does nothing to stop the minutes of unusable thrashing that precede that failure.

The stock OOM killer arrives too late, but Pressure Stall Information (PSI) changes the detection model, and you can configure oom_score_adj, cgroups v2 memory controls, and systemd-oomd to intervene before the box livelocks.

#The Bottleneck: Reclaim Livelock, Not Allocation Failure

The kernel’s memory reclaim path prioritises staying alive over staying responsive.

When anonymous memory pressure rises, the kernel does not immediately invoke the OOM killer — it first tries to reclaim page cache, then it starts swapping anonymous pages out under vm.swappiness control, and only escalates to the killer when __alloc_pages_slowpath() exhausts every reclaim attempt and still cannot satisfy an allocation.

On a system with several gigabytes of swap, that exhaustion point can be minutes away, and during those minutes every process touching a swapped-out page blocks on I/O. This is reclaim livelock: the system is technically making progress, but at a rate too slow for anything interactive to function.

Standard OOM killer tuning approaches that only adjust oom_score_adj values do not solve this, because the killer simply is not being invoked yet. The actual fix requires detecting pressure earlier, via PSI, and killing before the kernel’s own thresholds are breached.

#Architectural Breakdown: PSI, Badness Scores, and the Kill Decision Chain

Effective OOM killer tuning rests on three separate subsystems that must be understood as layers, not a single control knob.

#
1. The Kernel OOM Killer’s Badness Algorithm

When invoked, the kernel computes a badness score per process based on RSS, swap usage, and page table size, then applies oom_score_adj as a linear bias between -1000 and +1000. A value of -1000 makes a process immune; +1000 makes it the most likely first candidate. This is the only tuning surface most administrators touch, and it is necessary but not sufficient.

#
2. Pressure Stall Information (PSI)

Since kernel 4.20, /proc/pressure/memory exposes some and full percentages representing the proportion of time tasks spend stalled waiting on memory reclaim over rolling 10s, 60s, and 300s windows. This is the earliest reliable signal of thrashing, and it is what modern OOM killer tuning strategies key off, because it detects the stall before allocation failure, not after.

#
3. Userspace OOM Daemons

systemd-oomd and Facebook’s oomd poll PSI and cgroup memory pressure and kill proactively when thresholds are breached. systemd-oomd works on whole cgroups, not individual processes, and chooses victims by cgroup memory or swap usage and pressure; it does not use oom_score_adj for that choice. It acts far earlier than vmscan would, and this is the layer that actually closes the livelock gap.

Stopping Swap Thrashing With OOM Killer Tuning architecture diagram 1
1watch -n1 cat /proc/pressure/memory
2# some avg10=12.40 avg60=8.10 avg300=2.05 total=184213820
3# full avg10=4.20 avg60=1.90 avg300=0.44 total=52011932

An avg10 value on the full line sustained above roughly 5-10% under normal desktop load is a strong indicator that reclaim livelock has already begun, well before the kernel’s own OOM killer will act. Treat this as a starting point and calibrate against your own workload.

#OOM Killer Tuning via oom_score_adj and PSI Thresholds

Correct OOM killer tuning treats oom_score_adj as a per-service policy, not a one-off manual override. exposes this directly through unit files, which is the durable way to apply it, since raw /proc/<pid>/oom_score_adj writes do not survive process restarts. Use a drop-in (systemctl edit <unit>) so the vendor unit stays intact, and record the current value (systemctl show <unit> -p OOMScoreAdjust) so you can revert.

1[Service]
2# Protect the display compositor from early kills
3OOMScoreAdjust=-500
4
5[Unit]
6Description=Wayland compositor session

For batch or build workloads that are expendable — CI runners, transient compile jobs, cache warmers — the inverse policy applies:

1[Service]
2OOMScoreAdjust=800
3MemoryAccounting=yes
4ManagedOOMMemoryPressure=kill
5ManagedOOMMemoryPressureLimit=50%

The ManagedOOMMemoryPressure directive is what opts the unit’s cgroup in to systemd-oomd monitoring. systemd-oomd kills only descendant cgroups of that unit, never the unit itself, so on a plain service with no child cgroups set it on the slice that holds the expendable services instead.

It requires a running systemd-oomd, the unified cgroup v2 hierarchy and memory accounting, and swap should be enabled for systemd-oomd to behave as intended. OOMScoreAdjust only biases the kernel’s own late-stage killer; it plays no part in systemd-oomd‘s choice, which is based on cgroup usage and pressure.

Combining both is still a reasonable layered policy: bias the kernel killer for the worst case, and let the PSI-aware daemon act first. Pilot on one host before rolling out widely.

#
Configuring the Daemon Itself

1# Inspect current settings (read-only)
2cat /etc/systemd/oomd.conf
3oomctl
4systemctl status systemd-oomd
5
6# To change defaults, edit /etc/systemd/oomd.conf (or a drop-in in
7# /etc/systemd/oomd.conf.d/), e.g. DefaultMemoryPressureDurationSec under [OOM]
8sudo systemctl restart systemd-oomd

Back up oomd.conf before editing; reverting is a matter of restoring it and restarting the service. On distributions without systemd-oomd enabled by default (many desktop images ship it disabled), earlyoom is a lighter-weight alternative that monitors available memory from /proc/meminfo. Check the earlyoom documentation for the version you install, and verify behaviour on cgroups v1 hosts before relying on it.

#cgroups v2 memory.max as a Hard Boundary

PSI-driven killing is probabilistic and reactive by nature. For workloads where predictability matters more than graceful degradation — multi-tenant build servers, containerised student lab environments — pairing OOM killer tuning with a hard cgroup v2 ceiling removes ambiguity entirely.

Stopping Swap Thrashing With OOM Killer Tuning architecture diagram 2
1# Enable the memory controller for child cgroups of the root
2echo +memory > /sys/fs/cgroup/cgroup.subtree_control
3mkdir -p /sys/fs/cgroup/build-jobs
4echo "4096M" > /sys/fs/cgroup/build-jobs/memory.max
5echo "3584M" > /sys/fs/cgroup/build-jobs/memory.high
6# Moves the CURRENT shell into the cgroup; its children inherit the limits
7echo $$ > /sys/fs/cgroup/build-jobs/cgroup.procs

systemd owns the cgroup tree on systemd hosts and documents that you must not create cgroups directly under the root, so there use systemd-run --scope -p MemoryMax=4096M -p MemoryHigh=3584M <command> and keep these manual steps for hosts where systemd does not manage cgroups. Use integer values; fractional sizes such as 3.5G are rejected.

Test in a throwaway shell, and to undo, move the shell back to the root cgroup (echo $$ > /sys/fs/cgroup/cgroup.procs) and remove the empty directory with rmdir. memory.high triggers aggressive reclaim and throttling within the slice before memory.max forces a scoped OOM kill confined to that cgroup only — the rest of the host is untouched.

This is the mechanism behind Kubernetes memory limits and is documented in detail in the kernel’s own cgroup v2 admin guide. This approach is directly relevant to the broader architectural patterns used in containerised platform design, where per-tenant memory isolation is non-negotiable.

#Escalation Flow

Loading diagram...

#Failure Modes and Edge Cases

OOM killer tuning introduces its own failure surface if applied carelessly. The most common production incident is false-positive termination of the wrong process — a database connection pooler with a negative oom_score_adj survives while its parent supervisor, left at the default of 0, gets killed instead, leaving orphaned children and broken health checks. Always audit the entire process tree’s scores, not just the leaf process.

A second edge case involves containers. systemd-oomd kills whole cgroups, and only leaf cgroups (or ones with memory.oom.group set) below a unit set to kill are candidates, so a container is covered only if its cgroup sits under such a unit. Check where your container runtime places its cgroups before relying on host policies.

A third, subtler failure appears on hosts using zram-backed swap. Because zram compresses pages in memory rather than writing to a block device, swapping is much faster and costs CPU time instead, so PSI thresholds tuned on disk-swap hosts may not transfer. Systems relying purely on PSI thresholds for OOM killer tuning on zram hosts should calibrate their trigger thresholds by measurement on zram itself, and watch CPU pressure as well.

#Mechanism Comparison

MechanismTrigger SignalTypical LatencyScopeBest Fit
Kernel OOM killerAllocation failureSeconds to minutes (post-thrash)System-wideLast-resort safety net
earlyoomAvailable memory (/proc/meminfo)1-2sSystem-wideSimple desktops; hosts without systemd-oomd
systemd-oomdPSI (memory.pressure)Sub-second to a few secondsPer-slice / per-unitsystemd-managed services and desktops
cgroups v2 memory.maxHard byte ceilingImmediateScoped to cgroupMulti-tenant containers, CI runners

#Scaling and Security Trade-offs

  • Aggressive PSI thresholds reduce thrash duration but increase the rate of false-positive kills on bursty, legitimate workloads such as compilers or JVM garbage collection pauses.
  • Hard memory.max ceilings give predictable multi-tenant isolation but push failure onto the application layer, requiring retry and backoff logic that not every service implements correctly.
  • Negative oom_score_adj on privileged daemons improves system stability but, if applied too broadly, can starve the kernel of any killable candidate, forcing a full system freeze rather than a targeted kill.
  • zram/zswap combined with OOM killer tuning reduces disk I/O and extends effective memory headroom, but shifts pressure detection onto CPU metrics that most default dashboards do not surface.
  • Per-container cgroup delegation for PSI visibility improves kill accuracy inside orchestrated environments but expands the attack surface for cgroup escape if delegation is misconfigured with excessive controller permissions.

None of these mechanisms are mutually exclusive, and treating OOM killer tuning as a single configuration change rather than a layered policy is where most deployments go wrong.

A resilient host pairs PSI-aware daemon intervention for early, low-impact kills with hard cgroup ceilings for tenants that must never affect their neighbours, and reserves the kernel’s own badness-score killer purely as the mechanism of absolute last resort.

Getting the layering right is less about memorising flag names and more about understanding which subsystem sees the pressure signal first — and ensuring that subsystem is the one authorised to act.

Evidence trail

Sources and verification

Primary documentation and external technical references used in this article.

  1. 01cgroup v2 admin guidedocs.kernel.org

About this page

Credited to

Dates

Published

Last updated

Corrections

  • : Corrected during a review of published articles. Details
  • : Corrected during a review of published articles. Details

Found this useful? Follow KBY for more like it.

Reader Interaction

Comments

Add a thoughtful note on Stopping Swap Thrashing With OOM Killer Tuning. Comments are checked for spam and held for moderation before appearing.

Loading comments...

More from KBY that goes with this article.

Discover more

Was this useful?

Reports go to the site owner and are used to correct pages. Corrections are listed at /corrections.

Engineering insights, direct to you.

Receive the latest Systems Engineering tutorials, production guides, Engineering Labs and operational best practices.