TExcelTAD
Home › Linux Server Administration › Memory & the OOM Killer

Memory & the OOM Killer

Memory problems on Linux rarely look like "out of memory" errors. They look like a server that gets slow (reclaiming page cache, swapping), and then a process that vanishes: the kernel's OOM killer chose it to save the system. Knowing how Linux counts memory and how the OOM killer picks its victim turns those mysteries into routine.

Reading free

bash
$ free -m
               total        used        free      shared  buff/cache   available
Mem:            3911        2604         181          42        1394        1052
Swap:           2047         312        1735
  • free is memory nobody uses at all; on a healthy server it is small, because Linux uses spare memory as page cache (buff/cache) for files.
  • available is the number that matters: free memory plus cache the kernel can drop right away. Alert on this, not on "free".
  • Swap used isn't bad by itself (idle pages pushed out long ago); swap activity is. Watch si/so in vmstat (Load, vmstat & iostat).

The best early warning is pressure stall information (PSI): the share of time tasks were stalled waiting for memory (also for CPU and I/O). It is in /proc/pressure/ and per cgroup:

bash
$ cat /proc/pressure/memory
some avg10=12.40 avg60=8.91 avg300=3.02 total=91822361
full avg10=4.11 avg60=2.87 avg300=0.95 total=31204480

some = at least one task stalled, full = all non-idle tasks stalled at once; avg10 is the last 10 seconds, in percent. Anything persistently above a few percent means the workload doesn't fit in memory. (systemd-oomd, enabled on Ubuntu desktops and optional on servers, acts on these numbers before the kernel's OOM killer has to.)

When the kernel runs out

If memory can't be reclaimed fast enough, the kernel picks a process and kills it with SIGKILL. You find out from the kernel log and from systemd:

bash
$ journalctl -k --grep -i 'killed process' -n 1 --no-pager
Jan 15 03:12:09 web1 kernel: Out of memory: Killed process 23110 (java) total-vm:6211304kB, anon-rss:2899116kB, file-rss:0kB, shmem-rss:0kB, UID:1002 pgtables:6248kB oom_score_adj:0
$ systemctl status reports.service | grep -E 'Active|Main PID'
     Active: failed (Result: oom-kill) since Thu 2026-01-15 03:12:09 UTC; 6h ago
   Main PID: 23110 (code=killed, signal=KILL)
$ journalctl -k -n 40 --no-pager | grep -A12 'invoked oom-killer' | head -3
Jan 15 03:12:09 web1 kernel: postgres invoked oom-killer: gfp_mask=0x140cca(GFP_HIGHUSER_MOVABLE|__GFP_COMP), order=0, oom_score_adj=-900
Jan 15 03:12:09 web1 kernel: CPU: 1 PID: 1840 Comm: postgres Not tainted 6.8.0-90-generic #91-Ubuntu
Jan 15 03:12:09 web1 kernel: Mem-Info:

Note who invoked the OOM killer (postgres, which needed a page) versus who was killed (java, the biggest target). The victim is not necessarily the culprit. The full report also lists every process with its memory, which tells you what filled the machine.

How the victim is chosen

Each process has an oom_score (see /proc/<pid>/oom_score): roughly its share of RAM plus swap in thousandths, plus its oom_score_adj (−1000 … +1000). The highest score dies; −1000 means "never". This model applies the rule to a typical small server:

python · try it yourself
TOTAL_KB = 4_000_000 + 2_000_000          # RAM + swap

procs = [  # name, resident + swapped kB, oom_score_adj
    ("postgres",  900_000, -900),
    ("java",     2_900_000,   0),
    ("nginx",       60_000,   0),
    ("node-api",   700_000,   0),
    ("backup",     500_000, 500),
    ("sshd",        10_000, -1000),
]

def score(rss_kb, adj):
    if adj == -1000:
        return 0                       # never killed
    return max(0, rss_kb * 1000 // TOTAL_KB + adj)

ranked = sorted(procs, key=lambda p: -score(p[1], p[2]))
for name, rss, adj in ranked:
    print(f"{name:<9} rss={rss / 1e6:4.2f} GB  adj={adj:>5}  oom_score={score(rss, adj):>4}")
print("victim:", ranked[0][0])
backup    rss=0.50 GB  adj=  500  oom_score= 583
java      rss=2.90 GB  adj=    0  oom_score= 483
node-api  rss=0.70 GB  adj=    0  oom_score= 116
nginx     rss=0.06 GB  adj=    0  oom_score=  10
postgres  rss=0.90 GB  adj= -900  oom_score=   0
sshd      rss=0.01 GB  adj=-1000  oom_score=   0
victim: backup

The backup job, marked +500 as expendable, goes first although Java uses far more memory; PostgreSQL at -900 and sshd at -1000 are out of reach. Without adjustments the biggest process dies, and on a database server that is usually the database, the worst possible choice. Distribution packages for databases and sshd ship such adjustments; for your own services set them in the unit file:

ini
[Service]
OOMScoreAdjust=-500        # protect this service (lower = less likely)
# or, for a batch job you'd rather lose first:
# OOMScoreAdjust=500
MemoryHigh=1500M           # throttle and reclaim above this
MemoryMax=2G               # hard cap: the OOM killer acts inside this service only

MemoryMax= is the stronger tool: it puts the service in its own memory budget (cgroups v2), so a leak kills only that service, never the database next to it.

A process may make itself more likely to be killed, but not less: lowering the score below what it started with needs root (CAP_SYS_RESOURCE). That holds for the sandbox's own processes too:

bash · try it yourself
sleep 60 & pid=$!
echo "start:           $(cat /proc/$pid/oom_score_adj)"
echo 500 > /proc/$pid/oom_score_adj && echo "raised to:       $(cat /proc/$pid/oom_score_adj)"
echo 100 > /proc/$pid/oom_score_adj && echo "lowered back to: $(cat /proc/$pid/oom_score_adj)"
echo -100 > /proc/$pid/oom_score_adj 2>/dev/null || echo "below the starting value (-100): permission denied"
kill $pid
start:           0
raised to:       500
lowered back to: 100
below the starting value (-100): permission denied

Practical rules

  • Size servers so that available memory stays above ~10–20% at peak, and alert on PSI or available memory, not on "free".
  • Give runtimes explicit limits: JVM -Xmx (or -XX:MaxRAMPercentage), Node's --max-old-space-size, PostgreSQL's shared_buffers and work_mem × connections. A runtime that doesn't know its limit grows until the kernel stops it.
  • Keep some swap (or zram) on small VMs: it smooths spikes and gives you time; vm.swappiness tunes how eagerly it is used.
  • After an OOM kill: find the victim and the context in journalctl -k, check Result: oom-kill in systemctl status, then decide between a limit (MemoryMax=), a fix (a leak, an unbounded cache, a query) or more RAM.
  • Don't disable the OOM killer or set vm.overcommit_memory=2 on general-purpose servers without understanding the consequences: allocation failures then hit random programs instead.

Test yourself

free -m shows 150 MB free and 1.8 GB available. Is the server short of memory?

  1. Yes, only 150 MB are free
  2. Not necessarily: 'available' includes page cache the kernel can reclaim immediately
  3. Yes, swap must be added
  4. It depends on the CPU

The kernel log says postgres invoked oom-killer and then Killed process 23110 (java). Which process caused the problem?

  1. postgres
  2. Not necessarily either: postgres just needed a page at that moment; java was the largest target. The report's process list shows what filled memory
  3. java, because it was killed
  4. The kernel

How do you make sure a memory leak in one service can't get the database killed?

  1. Add swap
  2. Give the leaking service a MemoryMax= limit (and the database a negative OOMScoreAdjust)
  3. Restart the server nightly
  4. Disable the OOM killer