9.5. Managing Memory and Swap
Memory is the resource most often misread, because Linux spends almost all of it on cache on purpose and takes it back on demand. This section covers reading the numbers correctly, providing swap, and what actually happens - at the kernel level and in userspace - when a workload exceeds what it was given.
9.5.1. Interpreting Available Memory, Cache, and Swap Activity
Start with the one-line summary:
$ free -h
total used free shared buff/cache available
Mem: 1.4Gi 222Mi 1.2Gi 2.0Mi 152Mi 1.2Gi
Swap: 0B 0B 0B
The free column (1.2 GiB) is nearly meaningless on its own, and the
available column (also 1.2 GiB here) is the one to watch: it estimates how
much memory programs can allocate before the kernel must reclaim page cache
or swap something out. buff/cache is file content held in memory to speed
up the next read - the kernel will sacrifice it the moment a process needs
the RAM, so "used" being low and "free" being high is not the goal. The
detailed source of all these figures is /proc/meminfo:
# grep -E "^(MemTotal|MemAvailable|Cached|SwapTotal|Dirty|Writeback):" /proc/meminfo
MemTotal: 1504864 kB
MemAvailable: 1275976 kB
Cached: 125036 kB
SwapTotal: 0 kB
Dirty: 1460 kB
Writeback: 0 kB
MemTotal is 1504864 kB (the 1.4 GiB the machine has); MemAvailable
counts free pages plus reclaimable cache. Dirty and Writeback are the
page-cache states from Section 9.4.7. SwapTotal: 0 is the next
subsection's subject. Where free summarizes a moment, vmstat samples
continuously - one line per second, forever if you let it; stop it with
Ctrl+C:
$ vmstat 1 3
procs -----------memory---------- ---swap-- -----io---- -system-- -------cpu-------
r b swpd free buff cache si so bi bo in cs us sy id wa st gu
2 2 0 1259556 18084 138052 0 0 161 5267 209 1 5 1 82 11 0 0
0 2 0 1259508 18084 138068 0 0 0 0 86 47 0 0 50 50 0 0
0 2 0 1259508 18084 138068 0 0 0 0 71 42 0 0 50 50 0 0
vmstat 1 3 prints one line per second for three seconds, with the first
line showing averages since boot. The columns that matter for memory work:
r (tasks runnable right now) and b (tasks blocked in uninterruptible
sleep - Section 9.7.1 returns to both), si/so (swap in/out, kilobytes
per second - nonzero values mean the machine is actively swapping), and
bi/bo (blocks in/out to storage). In this capture si and so are
zero everywhere because the machine has no swap; the b column shows two
blocked tasks and wa 50% - chapter I/O still in flight on the example
machine at that moment. On an idle desktop, r, b, si, and so all sit
near zero. Sustained so with falling available is the signature of memory
starvation; occasional si alone is harmless.
One modern diagnostic belongs in every administrator's kit: the kernel's
pressure stall information, readable by any user from /proc/pressure/.
Each file reports, for its resource, how much of the recent wall time tasks
spent waiting for it:
$ cat /proc/pressure/cpu /proc/pressure/memory /proc/pressure/io
some avg10=0.20 avg60=0.08 avg300=1.03 total=39494820
full avg10=0.00 avg60=0.00 avg300=0.00 total=0
some avg10=0.00 avg60=0.21 avg300=2.14 total=49394252
full avg10=0.00 avg60=0.21 avg300=2.13 total=49276011
some avg10=1.56 avg60=1.42 avg300=7.86 total=259204326
full avg10=1.56 avg60=1.39 avg300=7.63 total=251925187
The three groups are CPU, memory, and I/O. The some line is the share of
time at least one task was stalled on that resource; full is the share
of time all non-idle tasks were stalled at once - the machine making no
progress. The avg10/avg60/avg300 figures are percentages over the
last 10, 60, and 300 seconds, and total is cumulative microseconds since
boot, which is why it is large here despite low current pressure: the
example machine had run the chapter's exercises. Pressure fractions turn
"the machine feels slow" into a number you can alert on; systemd-oomd
(Section 9.5.3) acts on exactly these numbers.
A note on the one famous sysctl: vm.swappiness (default 60) weighs how
eagerly the kernel prefers swapping out cold anonymous memory versus
dropping page cache. Values range from 0 (avoid swap except to avoid OOM)
to 100; it is a dial for cache-heavy workloads, not a fix for insufficient
RAM - and as with everything in /proc/sys, a permanent change belongs in
/etc/sysctl.d (Chapter 7).
9.5.2. Creating and Managing Swap Space
Swap gives the kernel a place to put pages it does not need right now, and - just as important - a second stage of overflow before the OOM killer. The example machine starts without any:
# swapon --show
Empty output means exactly that: no swap is active. The quickest remedy on a running system is a swap file on an existing filesystem. In the root shell, four steps - create the file, lock down its permissions, write a swap signature, activate it:
# fallocate -l 256M /swapfile
# chmod 600 /swapfile
# mkswap /swapfile
Setting up swapspace version 1, size = 256 MiB (268431360 bytes)
no label, UUID=2ad05e5c-5f11-4a41-80b7-f276a6c72d97
The first two commands are silent. fallocate reserves 256 MiB instantly
(without writing it full, the way dd would), and chmod 600 matters
because a swap file is raw pages - anyone who could read it could read
memory contents. mkswap writes the swap signature and reports the size it
found and the UUID it assigned. Activate and verify:
# swapon /swapfile
Silent - swapon says nothing on success:
# swapon --show
NAME TYPE SIZE USED PRIO
/swapfile file 256M 0B -2
# free -h
total used free shared buff/cache available
Mem: 1.4Gi 224Mi 1.2Gi 1.9Mi 153Mi 1.2Gi
Swap: 255Mi 0B 255Mi
The swap line now counts 255 MiB (a little of the file's 256 MiB is
overhead), unused so far. PRIO -2 is the default priority given to a swap
area activated without -p; with several areas the kernel fills the
highest-priority one first, which is how you would prefer a fast SSD swap
over a slower disk. To make the swap file survive reboots, add one line to
/etc/fstab:
/swapfile none swap sw 0 0
With that entry in place, the boot process activates the swap file
automatically (test any fstab edit before rebooting with swapon -a,
which activates everything listed). One caveat on the file itself: the
kernel refuses swap files with holes, and fallocate on ext4 as used here
produced a hole-free file. If swapon ever rejects a swap file with a
message about holes or unwritten extents, recreate it by writing real zeros
with dd if=/dev/zero of=/swapfile bs=1M count=256. A swap partition -
created during installation (Chapter 2) or with the
partitioning tools of Chapter 11 - avoids the
question entirely, and the zram-tools package offers a third option:
compressed swap held in RAM itself, useful on small-memory machines where
trading CPU for memory is a good bargain.
Removing swap is the reverse, with one caution: swapoff must page
everything still stored there back into RAM first, so it needs free memory
at least equal to the used swap, and it can take a while:
# swapoff /swapfile
# rm /swapfile
# swapon --show
All three commands print nothing; the final swapon --show confirming
empty output is the verification that the swap is gone. If you added the
/etc/fstab entry, remove that line as well, or the next boot's swapon -a
will complain about the missing file.
9.5.3. Out-of-Memory Events and systemd-oomd
When memory runs out, two different killers may act. The kernel OOM killer fires per cgroup or system-wide and kills one process - the biggest offender, chosen by a scoring heuristic. systemd-oomd is a userspace daemon that watches the pressure counters of Section 9.5.1 and kills whole cgroups - a user session or a service - before the kernel's last-ditch stage. Debian 13 ships it enabled:
# systemctl status systemd-oomd --no-pager | head -n 10
● systemd-oomd.service - Userspace Out-Of-Memory (OOM) Killer
Loaded: loaded (/usr/lib/systemd/system/systemd-oomd.service; enabled; preset: enabled)
Active: active (running) since Thu 2026-11-19 19:20:13 UTC; 24min ago
Invocation: 52556e05897e417b98d7f9c9a8785232
TriggeredBy: ● systemd-oomd.socket
Docs: man:systemd-oomd.service(8)
man:org.freedesktop.oom1(5)
Main PID: 315 (systemd-oomd)
Status: "Processing requests..."
Tasks: 1 (limit: 1711)
The service is enabled and preset-enabled on this installation; if yours
shows otherwise, the systemd-oomd package provides it, and
systemctl enable --now systemd-oomd starts it. What oomd watches is
opt-in per unit: an administrator (or the distribution) marks a unit with
ManagedOOMMemoryPressure=kill or ManagedOOMSwap=kill, and oomd kills
that whole unit when its pressure crosses the configured limit. Debian
opts user session services in by default - this is a shipped drop-in, not
local configuration:
# cat /usr/lib/systemd/system/user@.service.d/10-oomd-user-service-defaults.conf
[Service]
ManagedOOMMemoryPressure=kill
ManagedOOMMemoryPressureLimit=50%
Read it as: any service under a user session may be killed by oomd when
that service's memory pressure passes 50%. The result on a stressed
desktop is that one misbehaving application's session cgroup is killed
while the system stays healthy. oomctl shows the daemon's current state
- the memory and swap resources it tracks and the cgroups that are
candidates for killing - and journalctl -u systemd-oomd shows its
decisions.
The kernel-side mechanism is worth seeing end to end, and a small memory
hog makes it visible without endangering the machine. Save this as
memory_hog.py in the workspace:
#!/usr/bin/env python3
"""Allocate and touch memory in chunks until killed."""
import sys
import time
chunk = int(sys.argv[1]) if len(sys.argv) > 1 else 4 * 1024 * 1024
held = []
while True:
block = bytearray(chunk)
for offset in range(0, chunk, 4096):
block[offset] = 1
held.append(block)
print(f"allocated={len(held) * chunk // (1024 * 1024)}MiB", flush=True)
time.sleep(0.05)
It allocates 4 MiB blocks, touches every page so the kernel cannot lazily skip them, and reports its total until something stops it. Run it under a hard 64 MiB cgroup limit - in the root shell:
# systemd-run --unit=handbook-oom --slice=handbook.slice -p MemoryMax=64M /home/john/debian-handbook/processes/memory_hog.py
Running as unit: handbook-oom.service; invocation ID: 345cefef53824f1a90f30334fb9a84df
The unit starts; the hog begins filling its 64 MiB. Two seconds later, the verdict is on the unit:
# systemctl show handbook-oom -p Result -p MemoryMax -p MemoryPeak
Result=oom-kill
MemoryPeak=67108864
MemoryMax=67108864
Result=oom-kill is systemd's record of what happened; MemoryPeak
confirms the cgroup reached exactly its 64 MiB ceiling (67108864 bytes)
before the kill. The kernel's own account is in the journal - journalctl
-k filters to kernel messages, grep selects the OOM line, tail -n 1
keeps the most recent:
# journalctl -k --no-pager | grep -i "Memory cgroup out of memory" | tail -n 1
Nov 19 19:44:47 proc kernel: Memory cgroup out of memory: Killed process 9991 (python3) total-vm:80020kB, anon-rss:65208kB, file-rss:5728kB, shmem-rss:0kB, UID:0 pgtables:192kB oom_score_adj:0
The message identifies the killed process (PID 9991, python3 - the hog),
its memory at death (anon-rss 65 MiB of anonymous pages), and UID:0
because the transient unit runs as root by default. Two details make this
line worth reading slowly. First, this was a cgroup OOM - the phrase
Memory cgroup out of memory means the kernel killed the hog because its
cgroup hit memory.max, not because the machine was out of memory. A
system-wide OOM prints Out of memory: instead and is a different
emergency. Second, oom_score_adj:0 is the per-process OOM bias - the
same setting an administrator can lower to protect a critical daemon: a
drop-in for ssh.service containing OOMScoreAdjust=-1000 makes the SSH
server effectively unkillable by the OOM killer, which is worth doing on
any remote machine whose console access is inconvenient.
The distinction between the two killers, and what each produces:
| Kernel OOM (cgroup or global) | systemd-oomd | |
|---|---|---|
| Runs in | The kernel. | Userspace, systemd's daemon. |
| Trigger | Hard limit reached; no reclaim left. | Memory pressure or swap use above a configured limit. |
| Victim | One process, chosen by score. | The whole marked cgroup - a service or session. |
| Evidence | Result=oom-kill, Memory cgroup out of memory in the kernel log. |
oomctl, journalctl -u systemd-oomd. |
After a cgroup OOM like this one, recovery is a decision, not an
emergency: either the limit was wrong for the workload - raise
MemoryMax - or the program is broken - fix it. Nothing restarts
automatically here because the transient unit has no restart policy
(Chapter 8 covers service restart configuration).
The handbook-oom.service unit remains in the failed state until it is
cleaned up with systemctl reset-failed.