↓ Skip to main content
  1. Posts/

Swap, zram and the OOM killer on a small VPS

Table of Contents

A VPS with 1 or 2 GB of RAM runs fine right up until it doesn’t. A backup job, a burst of PHP workers or a badly written query pushes memory use over the edge, and one of two things happens. Either the machine goes unresponsive for a few minutes and then recovers with your database missing, or it simply stops answering and you reboot it from the provider panel.

Both outcomes are the kernel doing what it was designed to do. Once you know how it decides, you can tilt the decision in your favour.

What the kernel does when memory runs out
#

Linux doesn’t wait for RAM to hit zero before reacting. As free memory drops, it starts reclaiming: it drops page cache, writes dirty pages to disk and, if you have swap, moves anonymous memory (heap, stacks) out to it. Without swap, anonymous memory has nowhere to go, so the kernel keeps evicting the only thing it can, which is file-backed pages. That includes the code of running programs. They get read back from disk the next time they run, evicted again, read back again. This is the thrashing phase, where load goes through the roof, SSH takes a minute to give you a prompt and nothing seems to make progress.

When reclaim really can’t free enough, the kernel invokes the OOM killer. It picks one process, sends it SIGKILL and frees its memory. There’s no graceful shutdown and no chance for the process to flush anything.

How the victim is chosen
#

Every process has a badness score in /proc/<pid>/oom_score. The base score is roughly the share of allowed memory the process uses, scaled from 0 to 1000, counting RSS, swap and page tables. Then the value of /proc/<pid>/oom_score_adj is added, which can range from -1000 to +1000. The process with the highest result gets killed. A value of -1000 exempts a process completely.

On a small server that runs a web stack, the biggest process is usually the database, so MariaDB, MySQL or PostgreSQL is the most likely victim. That’s rarely what you want, because a PHP worker can be restarted for free while a killed database means errors for every request until something brings it back.

You can see the current ranking with a short loop:

for p in /proc/[0-9]*; do
  printf "%s %s %s\n" "$(cat $p/oom_score 2>/dev/null)" "${p#/proc/}" "$(cat $p/comm 2>/dev/null)"
done | sort -rn | head -15

The top of that list is what dies first if memory runs out right now.

Reading the logs after a kill
#

The kernel logs every OOM kill. Look in the kernel ring buffer or the journal:

dmesg -T | grep -i -E "out of memory|killed process"
journalctl -k -g "Out of memory" --since "2 days ago"

The key line looks something like this:

Out of memory: Killed process 812 (mariadbd) total-vm:1835012kB, anon-rss:402112kB, file-rss:0kB, shmem-rss:0kB, UID:106 pgtables:1156kB oom_score_adj:0

Just above it the kernel dumps a table of every process with its memory use and oom_score_adj, which is the useful part. It shows what else was using memory at that moment, and the process that got killed is often not the one that caused the problem. A runaway import script can push memory over the edge and the database still dies because it was bigger.

If the line says “Memory cgroup out of memory” instead, the kill came from a cgroup limit (for example a systemd MemoryMax=), not from the whole system running dry. systemd also records the result on the unit, so systemctl status mariadb will show the service failed with result oom-kill.

Add a swap file
#

Many VPS images ship with no swap at all. A modest swap file doesn’t make a small server faster, but it gives the kernel somewhere to put memory that’s allocated and rarely touched, and it turns a sudden kill into a slower degradation you can notice. Somewhere between half and the full size of RAM is a sensible starting point on a 1-4 GB machine.

fallocate -l 2G /swapfile
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile
echo '/swapfile none swap sw 0 0' >> /etc/fstab
swapon --show
free -h

On ext4 and XFS, fallocate works. On some filesystems a preallocated file counts as having holes and swapon rejects it. The portable way is to write the file out with dd:

dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress

Btrfs needs a file with copy-on-write disabled. Recent btrfs-progs can create one with btrfs filesystem mkswapfile --size 2G /swapfile.

zram: compressed swap in RAM
#

zram creates a block device in memory that compresses whatever is written to it. Used as swap, it lets the kernel squeeze cold pages instead of writing them to disk. Text-heavy memory like interpreter heaps tends to compress well, and swapping to RAM is much faster than swapping to a virtual disk shared with other tenants.

It needs the zram kernel module. Some virtualised or container-based VPS kernels don’t provide it, and in an OpenVZ or LXC container you can’t load modules at all. Check before installing anything:

modprobe zram && ls /sys/block | grep zram

If that fails, stick with a swap file.

On Debian and Ubuntu there are two common ways to set it up. The simple one is zram-tools:

apt install zram-tools
# /etc/default/zramswap
ALGO=zstd
PERCENT=50
PRIORITY=100
systemctl restart zramswap

The other is systemd-zram-generator, which Fedora uses by default:

apt install systemd-zram-generator
# /etc/systemd/zram-generator.conf
[zram0]
zram-size = ram / 2
compression-algorithm = zstd
systemctl daemon-reload
systemctl start systemd-zram-setup@zram0.service
zramctl

zramctl shows how much data went in and how much RAM it actually occupies after compression. Both tools give zram a swap priority of 100, higher than a disk swap file, so you can keep both: the kernel fills zram first and only touches the disk when zram is full.

vm.swappiness
#

vm.swappiness tells the kernel how willing it is to swap anonymous memory compared to dropping page cache. It accepts 0 to 200, and the default is 60. The kernel documentation suggests going above 100 for in-memory swap like zram, because swapping there is cheaper than rereading files from disk. With a disk swap file only, the default or something lower is reasonable.

# /etc/sysctl.d/99-swappiness.conf
vm.swappiness = 100
sysctl --system

There’s no universal right value. Change it, watch vmstat 5 under normal load for a while, and look at the si and so columns. Constant swapping in and out means the machine needs less work or more RAM, and no tuning will fix that.

Tell systemd what matters
#

Most services on a modern Debian or Ubuntu box run under systemd, which can set the OOM score and enforce memory limits per unit. Use a drop-in with systemctl edit so package upgrades don’t overwrite it.

To make the database a less attractive victim:

# systemctl edit mariadb
[Service]
OOMScoreAdjust=-500

Avoid -1000 on everything you care about. If nothing is killable, the kernel has no good way out, and you end up back at the frozen server.

The opposite move is often better: cap the things that are allowed to misbehave. MemoryHigh= is a soft limit where the kernel throttles the unit and reclaims its memory hard. MemoryMax= is the hard limit, and crossing it triggers an OOM kill inside that unit’s cgroup only.

# systemctl edit php8.2-fpm
[Service]
MemoryHigh=600M
MemoryMax=800M
OOMScoreAdjust=300

Now a leaky PHP pool slows down and then gets killed on its own, while the database and SSH keep running. The same goes for queue workers, cron jobs and anything a user can trigger with a large upload. These limits need cgroup v2, which is the default on current Debian and Ubuntu releases. Check with stat -fc %T /sys/fs/cgroup, which prints cgroup2fs.

Userspace OOM killers
#

The kernel OOM killer acts late, often after the thrashing has already gone on for a while. Two userspace daemons try to act earlier.

earlyoom is small and simple. It checks available memory and free swap, and kills the biggest process when both drop below a threshold. You can steer it with regular expressions:

apt install earlyoom
# /etc/default/earlyoom
EARLYOOM_ARGS="-m 5 -s 10 -r 3600 --avoid '(^|/)(sshd|mariadbd|postgres)$' --prefer '(^|/)(php-fpm.*|node)$'"

systemd-oomd works on cgroups instead of single processes and uses pressure stall information (PSI), which measures how much time tasks spend waiting for memory. It only acts on units that opt in:

apt install systemd-oomd
# /etc/systemd/system/system.slice.d/oomd.conf
[Slice]
ManagedOOMMemoryPressure=kill
ManagedOOMMemoryPressureLimit=60%

When pressure in system.slice stays above the limit, systemd-oomd kills the whole cgroup of the service under the most pressure. It also expects swap to be present, so pair it with a swap file or zram. Pick one of the two daemons, not both, because they’ll compete for the same decisions.

On a 1-4 GB server, a reasonable default is a swap file or zram, a MemoryMax= on whatever runs user code, and a negative OOMScoreAdjust= on the database. After the next OOM event, check that the process in the kill line is the one you meant to sacrifice.

Related