Skip to content
Linux system performance · Chapter 9 of 21 Day 7: Memory II – pressure, swap, OOM killer and leaks

Day 7: Memory II – pressure, swap, OOM killer and leaks

Goal: recognize when memory is really short, measure swap and reclaim, set memory limits for services, understand and prove the OOM killer, trace a memory leak down to the line of code and resolve a swap storm · Duration: about 3.5 hours · Prerequisite: Day 0–6

Where we start

perf1 is quiet, no test service from Day 6 is running, and there is no swap yet. Three checks:

# on perf1
systemctl is-active sitzungsdienst

Expected:

inactive
# on perf1
swapon --show
  • swapon --show lists active swap areas.

Expected: no output, not even a header line – there is no swap.

# on perf1
free -m

Expected (excerpt – the line Swap:):

Swap:              0           0           0

Introduction

Yesterday you learned that little free memory is not a problem. Today is about the case in which it is one: programs need more than there is. Then the kernel has to decide what to push out of memory. First it sacrifices the page cache, then it swaps anonymous memory out to swap, and if that is not enough either, it ends a process – the OOM killer (out of memory).

Each of these steps has its price. Swapped-out memory has to be fetched back from disk on every access, and a program whose working set does not fit into memory does not become a little slower but slower by orders of magnitude. This is called thrashing or a swap storm, and you will measure it today: a program that suddenly runs several hundred times slower without the CPU being busy.

You also learn to give services memory limits – soft and hard –, to prove an OOM kill beyond doubt and to find out with memleak which line of code requests memory and does not give it back.

Today you learn:

  • to create a swap file, and what swappiness controls,
  • how the kernel reclaims memory (reclaim) and how you see it with sar -B and sar -W,
  • to interpret PSI for memory and I/O under memory pressure,
  • to set memory limits with memory.high and memory.max and read their event counters,
  • to prove an OOM kill in dmesg, in the journal and in systemd,
  • to trace memory leaks down to the calling function with memleak,
  • to recognize and resolve a swap storm.

Background

The picture for today: the desk and the basement

Stay in the reading room from Day 6, but sit down at your own desk. The desk is main memory, and below it there is a basement – the swap.

  • Books from the library (page cache) can be returned at any time and fetched again later. The kernel clears these first – cheap.
  • Your own notes (anonymous memory) exist nowhere else. To make room you have to carry them down to the basement. Without a basement you cannot put them away.
  • kswapd is the caretaker who tidies up at night before things get tight. If that is not enough, you have to tidy up yourself before you may keep writing (direct reclaim) – that costs your time.
  • Thrashing: Your desk is too small for what you are working on. For every second page you run down to the basement and carry another one down. You are no longer working, you are climbing stairs.
  • memory.high is a smaller desk: what does not fit has to go to the basement. memory.max is the house rule “whoever spreads out more gets thrown out” – the OOM killer.

The terms

Term Meaning in the picture
Reclaim win back pages when memory gets short tidying up
Swap area on disk for swapped-out anonymous memory basement
kswapd / direct reclaim background tidier / the process tidies up itself caretaker / tidy up yourself
Thrashing working set does not fit, constant swapping in and out climbing stairs
memory.high soft limit: throttles and swaps out smaller desk
memory.max hard limit: OOM killer in this cgroup thrown out
OOM killer ends a process with SIGKILL thrown out

Remember: Swap for forgotten things is healthy. Swap for the working set means climbing stairs – the program waits instead of computing.

Reclaim: making room

When free memory gets short, the kernel starts winning back pages (page reclaim). It sorts pages into lists by “active” and “inactive” (the fields from Day 6) and takes the inactive ones first:

  • Clean cache pages (file contents that lie unchanged on disk) it can simply discard – cheap.
  • Dirty cache pages it first has to write back.
  • Anonymous pages (heap, stack) exist nowhere else. To free them, it has to write them to swap – a swap partition or swap file. Without swap it cannot free anonymous memory.

In the background the kernel thread kswapd does this as soon as free memory falls below a mark. If that is not enough, a process that requests memory has to help itself (direct reclaim) – and waits while doing so. That is the first place where memory pressure creates latency.

swappiness

vm.swappiness (0 to 200, default 60) weighs how willingly the kernel swaps out anonymous memory instead of discarding cache. Low values prefer discarding cache, high ones swapping out. 0 does not mean “never swap out” but “only when there is no other way”. The value is not a cure-all; Day 15 comes back to it.

Thrashing

Swap makes sense for memory that is not needed for a long time – parts of a program that only run at startup, a forgotten process. It becomes a problem when the working set (the memory a program needs constantly) does not fit into main memory. Then the kernel brings a page in, pushes out another one that is needed again right away, and so on. Every access becomes a disk access. A memory access costs about 100 nanoseconds, an access to an SSD-based virtual disk about 100 microseconds to a millisecond – a factor of more than a thousand.

Memory limits for cgroups

cgroups v2 has four controls for memory, which systemd sets as properties of a service:

File systemd property Effect
memory.min / memory.low MemoryMin= / MemoryLow= protection: this much stays (almost) guaranteed for the service
memory.high MemoryHigh= soft limit: above it the service is throttled and its memory reclaimed first
memory.max MemoryMax= hard limit: above it the OOM killer steps in within this cgroup
memory.swap.max MemorySwapMax= how much swap the service may use

memory.high is the brake, memory.max the wall. The file memory.events counts how often the service has hit which limit: high, max, oom, oom_kill.

The OOM killer

If there is no way out anymore – no cache to discard, no swap, or the hard limit of a cgroup has been reached –, the kernel picks a process and ends it with SIGKILL. The choice is based on a score (oom_score) that essentially depends on memory consumption and can be shifted with oom_score_adj (−1000 to 1000). With a cgroup limit it only picks processes within that cgroup. Every OOM kill leaves a detailed message in the kernel log.

Some systems additionally have an OOM daemon in user space (systemd-oomd) that steps in on sustained memory pressure according to PSI, before the kernel has to. Ubuntu Desktop turns it on, Ubuntu Server does not.

Finding memory leaks

A leak is memory that a program requests and never gives back. At system level you only see the growth (Day 6). To find the place in the code, memleak from the bcc tools can follow every malloc and free request of a process and, at the end, list the call chains whose memory has not been freed yet. That is noticeably expensive – every request is intercepted –, but acceptable for a measurement of a few seconds.

Drill 1: Setting up swap

Where you are: on perf1.

What you have afterwards: a 4 GiB swap file that is also active after a reboot.

Step 1 – create the file.

# on perf1
sudo fallocate -l 4G /swapfile
  • fallocate -l 4G creates a file of 4 GiB without writing zeros into it – the space is only reserved. That takes a fraction of a second.

Step 2 – root only.

# on perf1
sudo chmod 600 /swapfile
  • chmod 600 only allows root to read and write the file. Contents from the memory of all processes end up in swap, passwords too; swapon warns about more open permissions.

Step 3 – format as swap.

# on perf1
sudo mkswap /swapfile
  • mkswap writes the management structure of a swap area into the file.

Expected:

Setting up swapspace version 1, size = 4 GiB (4294963200 bytes)
no label, UUID=cc5c56cc-c1f5-4e4d-87f9-fa53f866ec59

Step 4 – switch it on.

# on perf1
sudo swapon /swapfile

Step 5 – make it permanent. So that the swap is still there after a reboot, you enter it in /etc/fstab – with nano as on Day 0:

# on perf1
sudo nano /etc/fstab

Leave the existing lines as they are and add this line at the end of the file:

/etc/fstab changes in green
/swapfile none swap sw 0 0

The line switches the swap on at every boot; none stands in place of a mount point, sw is the option for swap. Save with Ctrl+O and Enter, exit with Ctrl+X.

Step 6 – check.

# on perf1
swapon --show

Expected:

NAME      TYPE SIZE USED PRIO
/swapfile file   4G   0B   -2
# on perf1
free -m

Expected:

               total        used        free      shared  buff/cache   available
Mem:           11961         415       11647           1         104       11545
Swap:           4095           0        4095
# on perf1
cat /proc/sys/vm/swappiness

Expected:

60

The swap is on the system disk sda, not on /daten – that way your disk measurements on sdb on Day 8 and 9 stay undisturbed. PRIO -2 is the priority; with several swap areas the kernel uses the one with the highest priority first.

Remember: Swap in four steps: fallocate, chmod 600, mkswap, swapon – and one line in /etc/fstab so that it survives a reboot.

If it doesn’t work

  • swapon: /swapfile: insecure permissions 0644, 0600 suggested. (and a similar message from mkswap): you forgot chmod. The swap is switched on anyway; catch up on the step.

Save your progress? Sign up for free

Drill 2: A hard limit and the OOM killer

Where you are: on perf1.

What you have afterwards: a service that the OOM killer ended at its memory limit, and three pieces of evidence for it.

A small Python program requests 10 MiB every 50 milliseconds and never gives anything back. You start it as a service with a hard limit of 300 MiB and without swap:

# on perf1
sudo systemd-run --unit=fresser -p MemoryMax=300M -p MemorySwapMax=0 python3 -c "
import time
a = []
while True:
    a.append(bytearray(10 * 1024 * 1024))
    time.sleep(0.05)
"
  • -p MemoryMax=300M sets memory.max of the cgroup to 300 MiB.
  • -p MemorySwapMax=0 forbids swap for this service. Otherwise it would fill the swap first.
  • The program appends new 10 MiB blocks to the list a in an endless loop. The loop is in the service’s program – you type it once as part of the command, not as a shell loop.

Wait about eight seconds.

Evidence 1 – systemd.

# on perf1
systemctl status fresser --no-pager

Expected (excerpt – the first five lines):

× fresser.service - /usr/bin/python3 -c "\nimport time\na = []\nwhile True:\n    a.append(bytearray(10 * 1024 * 1024))\n    time.sleep(0.05)\n"
     Loaded: loaded (/run/systemd/transient/fresser.service; transient)
  Transient: yes
     Active: failed (Result: oom-kill) since Mon 2026-11-30 13:22:39 UTC; 5s ago
   Duration: 2.638s

Result: oom-kill – systemd knows why the service ended (fresser = “glutton”). After 2.6 seconds the limit was reached.

Evidence 2 – the service’s journal.

# on perf1
journalctl -u fresser --no-pager -o cat

journalctl -u shows the messages of a service, -o cat only the text without timestamps.

Expected (excerpt – the last four lines):

fresser.service: A process of this unit has been killed by the OOM killer.
fresser.service: Main process exited, code=killed, status=9/KILL
fresser.service: Failed with result 'oom-kill'.
fresser.service: Consumed 1.240s CPU time.

status=9/KILL: the process was ended with signal 9 (SIGKILL) – without a chance to clean up.

Evidence 3 – the kernel log.

# on perf1
sudo dmesg -T
  • dmesg shows the kernel log, -T with readable time.

Expected (excerpt – at the very bottom the lines with oom-kill and Killed process):

[Mon Nov 30 13:22:40 2026] oom-kill:constraint=CONSTRAINT_MEMCG,nodemask=(null),cpuset=fresser.service,mems_allowed=0,oom_memcg=/system.slice/fresser.service,task_memcg=/system.slice/fresser.service,task=python3,pid=2776,uid=0
[Mon Nov 30 13:22:40 2026] Memory cgroup out of memory: Killed process 2776 (python3) total-vm:325756kB, anon-rss:306432kB, file-rss:6656kB, shmem-rss:0kB, UID:0 pgtables:668kB oom_score_adj:0
  • constraint=CONSTRAINT_MEMCG – triggered by the limit of a cgroup, not because the whole machine was full. For a system-wide OOM this would say CONSTRAINT_NONE.
  • oom_memcg=/system.slice/fresser.service – which cgroup reached its limit.
  • Killed process 2776 (python3) with its consumption: anon-rss:306432kB – a good 300 MiB of anonymous memory, exactly the limit.

Above these lines the log contains a long table of all processes of the cgroup with their memory and oom_score_adj – the basis for the kernel’s decision.

Clear away the failed service:

# on perf1
sudo systemctl reset-failed fresser

Remember: You prove an OOM kill three times: Result: oom-kill in systemd, status=9/KILL in the journal, CONSTRAINT_MEMCG and Killed process in the kernel log.

If it doesn’t work

  • The service keeps running and fills the swap: -p MemorySwapMax=0 is missing. Stop it with sudo systemctl stop fresser.
  • dmesg shows nothing: without sudo you may not read the kernel log on Ubuntu.

Save your progress? Sign up for free

Drill 3: Tracing a leak down to the function

Where you are: on perf1, in the directory ~/tag07.

What you have afterwards: the call chain from which a program requests memory and does not give it back.

Step 1 – a program with a leak.

# on perf1
mkdir -p ~/tag07
# on perf1
cd ~/tag07
# on perf1
nano leck.c

Content:

leck.c new file
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

/* Liest einen "Eintrag" und gibt eine Kopie zurück. */
static char *lade_eintrag(int n)
{
    char *kopie = malloc(4096);
    memset(kopie, n & 0xff, 4096);
    return kopie;
}

/* Verarbeitet einen Eintrag – und vergisst bei jedem zehnten das free(). */
static void verarbeite(int n)
{
    char *e = lade_eintrag(n);
    if (n % 10 != 0)
        free(e);
}

int main(void)
{
    for (int n = 0; ; n++) {
        verarbeite(n);
        usleep(100);
    }
}
# on perf1
gcc -O0 -g -fno-omit-frame-pointer -o leck leck.c
  • lade_eintrag (“load entry”) requests 4 KiB, fills them and returns them.
  • verarbeite (“process”) frees the memory again – except for every tenth number (n % 10 == 0). That is the leak, as it often hides in a rarely used error path in real programs.
  • usleep(100) waits 100 microseconds per iteration.
  • -O0 turns off optimizations so that the compiler does not build the small functions into main and the chain stays easy to read. -fno-omit-frame-pointer ensures complete chains (Day 5).

Step 2 – start the program.

# on perf1, terminal 1
./leck

It runs endlessly and prints nothing.

Step 3 – the PID.

# on perf1, terminal 2
pgrep -x leck

Expected:

76279

You will see a different number. Use it below instead of PID.

Step 4 – observe with memleak. Wait a few seconds after the start, then:

# on perf1, terminal 2
sudo memleak-bpfcc -p PID --top 3 10 1
Option Meaning
-p PID attach to this running process
--top 3 the three call chains with the most outstanding requests
10 1 print once after ten seconds

Expected:

Attaching to pid 76279, Ctrl+C to quit.
[23:14:24] Top 3 stacks with outstanding allocations:
    12947456 bytes in 3161 allocations from stack
        0x00005df92b9291c2  lade_eintrag+0x19 [leck]
        0x00005df92b9291fe  verarbeite+0x19 [leck]
        0x00005df92b92925c  main+0x1d [leck]
        0x0000770a1942a1ca  __libc_start_call_main+0x7a [libc.so.6]
        0x0000770a1942a28b  __libc_start_main_impl+0x8b [libc.so.6]
        0x00005df92b9290e5  _start+0x25 [leck]

In ten seconds 3,161 requests with a total of 13 MB have remained outstanding, all from the same chain: main → verarbeite → lade_eintrag → malloc. That narrows the search down to one place in the code. That lade_eintrag requests memory is correct – the bug is in the caller verarbeite, which does not always free it. memleak shows where the memory comes from; who should have freed it, the code tells you. Check the math: 3,161 outstanding blocks are a tenth of all iterations – so the program manages a good 3,100 iterations per second, and every tenth one loses 4 KiB.

Stop leck (“leak”) in terminal 1 with Ctrl+C.

Remember: memleak shows where unfreed memory comes from. Who should have freed it, only the caller’s code tells you.

If it doesn’t work

  • Only addresses instead of function names: the program was compiled without -g, or you built an optimized version without frame pointers.

Save your progress? Sign up for free

Diagnosis task

A report job that normally finishes in a few minutes has been “hanging” since the last deployment. According to its log it is hardly making progress. On the server the CPU is almost idle, and yet everything is sluggish.

Setup. The program keeps a working set in memory and accesses it constantly at random – like an application with a large index:

# on perf1
nano ~/tag07/arbeitsmenge.py

Content:

~/tag07/arbeitsmenge.py new file
import random, sys, time

mib = int(sys.argv[1])
seite = 4096
daten = bytearray(mib * 1024 * 1024)       # die Arbeitsmenge
seiten = len(daten) // seite
runde = 0
t0 = time.time()
while True:
    for _ in range(20000):                 # 20 000 zufällige Seiten anfassen
        i = random.randrange(seiten) * seite
        daten[i] = (daten[i] + 1) % 256
    runde += 1
    if runde % 10 == 0:                    # alle 10 Runden: Tempo der letzten 10
        jetzt = time.time()
        print(f"Runde {runde}: {200000 / (jetzt - t0):.0f} Zugriffe/s", flush=True)
        t0 = jetzt
# on perf1
cd ~/tag07
# on perf1
timeout 15 python3 arbeitsmenge.py 1500
  • The program creates a working set of as many MiB as the first argument says and writes to 20,000 randomly chosen pages in every round.
  • Every ten rounds it prints how many accesses per second it managed in those ten rounds.
  • timeout 15 ends the test run after 15 seconds.

Expected (excerpt – the last two lines; this is how fast it is when there is enough memory):

Runde 260: 370478 Zugriffe/s
Runde 270: 403530 Zugriffe/s

Now the service as it has been running “since the deployment”:

# on perf1
sudo systemd-run --unit=berichtsjob -p User=ubuntu -p MemoryHigh=600M \
  python3 /home/ubuntu/tag07/arbeitsmenge.py 1500

Wait two minutes.

Task (20 minutes): Why is the job hardly making progress? Which resource is the bottleneck, and where exactly is the cause? Fix it and measure the success.

Solution path

Step 1 – is it making progress?

# on perf1
journalctl -u berichtsjob --no-pager -o short-precise

-o short-precise shows timestamps with microseconds.

Expected (excerpt – the last two lines, a good two minutes after the start):

Nov 30 23:14:54.808167 perf1 systemd[1]: Started berichtsjob.service - /usr/bin/python3 /home/ubuntu/tag07/arbeitsmenge.py 1500.
Nov 30 23:17:07.055941 perf1 python3[76376]: Runde 10: 1563 Zugriffe/s

For the first ten rounds the job needed 2 minutes 12 seconds – in the test run that was half a second. 1,563 accesses per second instead of about 400,000. (Lines before that come from earlier runs of the same service.)

Step 2 – the overview.

# on perf1
vmstat 1 4

Expected:

procs -----------memory---------- ---swap-- -----io---- -system-- -------cpu-------
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st gu
 1  1 1212572 11180600  16676 228256 1492 2320  4812  3290  955    1  3  2 83 11  1  0
 0  1 1212572 11180728  16676 228272  432    0   432     0  454  326  0  0 75 25  0  0
 0  1 1213340 11180728  16676 228272  344  768   344   768  340  247  0  0 75 24  0  0
 0  1 1213340 11180476  16676 228272  508    0   508     0  571  374  0  1 75 24  1  0
# on perf1
free -m

Expected:

               total        used        free      shared  buff/cache   available
Mem:           11961        1051       10918           1        239       10909
Swap:           4095        1184        2911

The picture is contradictory – and that is exactly the clue:

  • 11 GB free, and yet 1.2 GB are in swap (swpd, Swap used).
  • si (swap in) 340–500 KiB/s, so (swap out) at times: pages are constantly swapped out and in.
  • b = 1, wa = 24 %: one process is waiting for I/O all the time. Practically nothing is computed.

The machine has enough memory – but someone is not allowed to use it.

Step 3 – PSI. First the memory pressure:

# on perf1
cat /proc/pressure/memory

Expected:

some avg10=0.57 avg60=4.50 avg300=4.35 total=30280401
full avg10=0.57 avg60=4.49 avg300=4.34 total=30179922

Then the I/O pressure:

# on perf1
cat /proc/pressure/io

Expected:

some avg10=81.90 avg60=72.83 avg300=51.50 total=358481984
full avg10=81.58 avg60=72.70 avg300=51.40 total=355599221

The I/O pressure is at 82 %, the memory pressure is low now. That is surprising at first. PSI counts waiting for a page that is read back from swap as I/O waiting. Memory pressure is measured mainly during reclaim – and that was strong at the beginning: in the first minute of the job, memory some avg10 was at 22 %. After that an equilibrium set in in which almost only swapping in happens.

Step 4 – who? The processes by RSS, with state:

# on perf1
ps -eo pid,stat,rss,comm --sort=-rss | head -3
  • --sort=-rss by RSS in descending order, head -3 the header line and the largest.

Expected (excerpt – header line and first process):

    PID STAT   RSS COMMAND
  76376 Ds   611296 python3

A Python process in state D (waiting for I/O) with just under 600 MB RSS.

Step 5 – how much of it is in the basement? Every process shows its swap share in /proc/PID/status, in the line VmSwap:

# on perf1
grep VmSwap /proc/76376/status

Use the PID from your ps output instead of 76376.

Expected:

VmSwap:   935256 kB

935,256 kB, that is 913 MiB. Working set 1.5 GB, in memory 600 MB – the rest has to come from swap on every access.

Step 6 – why only 600 MB? The service’s cgroup. The soft limit:

# on perf1
cat /sys/fs/cgroup/system.slice/berichtsjob.service/memory.high

Expected:

629145600

The current consumption:

# on perf1
cat /sys/fs/cgroup/system.slice/berichtsjob.service/memory.current

Expected:

628752384

What is in swap:

# on perf1
cat /sys/fs/cgroup/system.slice/berichtsjob.service/memory.swap.current

Expected:

1283235840

How often the limits were reached:

# on perf1
cat /sys/fs/cgroup/system.slice/berichtsjob.service/memory.events

Expected (excerpt – the lines high, max, oom, oom_kill):

high 3612
max 0
oom 0
oom_kill 0

And the I/O pressure of the service itself:

# on perf1
cat /sys/fs/cgroup/system.slice/berichtsjob.service/io.pressure

Expected:

some avg10=90.76 avg60=81.42 avg300=39.41 total=156174766
full avg10=90.76 avg60=81.42 avg300=39.41 total=156174766
  • memory.high = 629,145,600 bytes = 600 MiB, and memory.current sticks just below it.
  • memory.swap.current = 1.2 GB in swap.
  • memory.events: hit the soft limit high 3,612 times, never max, no OOM.
  • The service itself has 91 % I/O pressure.

That is the cause: during the deployment the soft limit was set to 600 MiB, but the job’s working set is 1.5 GB. The kernel keeps the limit by pushing the rest into swap – and the job fetches it back on every second access. The disk holding the swap is quite busy meanwhile; iostat -sxz 1 2 showed more than 1,200 requests per second and 81 % utilization for sda at the beginning, sar -W about 1,100 pages swapped in and out per second.

Step 7 – fix. Raise the limit while running:

# on perf1
sudo systemctl set-property --runtime berichtsjob MemoryHigh=2G

systemctl set-property changes properties of a running service; --runtime only applies until the next restart, without creating files under /etc.

# on perf1
cat /sys/fs/cgroup/system.slice/berichtsjob.service/memory.high

Expected:

2147483648

But that alone only helps slowly: the kernel only brings swapped-out pages back when they are touched, one after the other. With 1.2 GB in swap and random accesses, that takes up to half an hour. It is faster to switch swap off briefly – then the kernel has to bring everything back at once, and it reads it sequentially from disk:

# on perf1
time sudo swapoff /swapfile

Expected:

real    0m56.554s
user    0m0.015s
sys 0m15.003s

Then switch swap back on:

# on perf1
sudo swapon /swapfile

swapoff only works if there is enough free memory for everything in swap – here more than enough.

Step 8 – check.

# on perf1
journalctl -u berichtsjob --no-pager -o short-precise

Expected (excerpt – the lines of this run):

Nov 30 23:14:54.808167 perf1 systemd[1]: Started berichtsjob.service - /usr/bin/python3 /home/ubuntu/tag07/arbeitsmenge.py 1500.
Nov 30 23:17:07.055941 perf1 python3[76376]: Runde 10: 1563 Zugriffe/s
Nov 30 23:19:11.121607 perf1 python3[76376]: Runde 20: 1612 Zugriffe/s
Nov 30 23:19:13.822924 perf1 python3[76376]: Runde 30: 74007 Zugriffe/s
Nov 30 23:19:15.022064 perf1 python3[76376]: Runde 40: 166802 Zugriffe/s
Nov 30 23:19:15.967562 perf1 python3[76376]: Runde 50: 211560 Zugriffe/s
Nov 30 23:19:16.674351 perf1 python3[76376]: Runde 60: 282908 Zugriffe/s
Nov 30 23:19:17.330900 perf1 python3[76376]: Runde 70: 304638 Zugriffe/s

And a quarter of a minute later (excerpt – the last two lines):

Nov 30 23:19:31.995873 perf1 python3[76376]: Runde 380: 404420 Zugriffe/s
Nov 30 23:19:32.439770 perf1 python3[76376]: Runde 390: 450488 Zugriffe/s
# on perf1
vmstat 1 2

Expected (excerpt – the last line):

 1  0      0 10137344  13728 332772    0    0     0    12 1197  119 25  0 75  0  0  0

The story in these lines: the first twenty rounds took about two minutes each – a good 1,500 accesses per second. Round 20 ended while swapoff was running; after that the rate rises from round to round until it is at 400,000 to 450,000 per second – almost 300 times as fast. vmstat shows no more swap, no waiting, one CPU fully busy (us = 25 of four CPUs). This is what a program looks like that computes instead of waiting.

Step 9 – clean up.

# on perf1
sudo systemctl stop berichtsjob
# on perf1
sudo systemctl reset-failed berichtsjob

If the second one reports not loaded, the service is already forgotten – not an error.

In real operations the correction belongs in the service definition: MemoryHigh matching the working set – measured, not estimated.

If it doesn’t work

  • swapoff: /swapfile: swapoff failed: Cannot allocate memory: there is not enough free memory for the contents of the swap. Raise the limit first or stop the service.
  • The job runs fast even with the limit: your VM has too little memory for the assumptions, or MemoryHigh was not set. Check cat /sys/fs/cgroup/system.slice/berichtsjob.service/memory.high.

Challenge

Start the report job again with MemoryHigh=600M and MemorySwapMax=0. What happens now, and why might that even be better in this case?

Solution path:

# on perf1
sudo systemd-run --unit=berichtsjob -p User=ubuntu -p MemoryHigh=600M -p MemorySwapMax=0 \
  python3 /home/ubuntu/tag07/arbeitsmenge.py 1500

Wait a minute. Then the consumption:

# on perf1
cat /sys/fs/cgroup/system.slice/berichtsjob.service/memory.current

Expected:

693243904
# on perf1
cat /sys/fs/cgroup/system.slice/berichtsjob.service/memory.swap.current

Expected:

0
# on perf1
cat /sys/fs/cgroup/system.slice/berichtsjob.service/memory.events

Expected (excerpt):

high 3755
max 0
oom 0
oom_kill 0
oom_group_kill 0
# on perf1
cat /sys/fs/cgroup/system.slice/berichtsjob.service/memory.pressure

Expected:

some avg10=82.54 avg60=53.51 avg300=15.76 total=55048524
full avg10=82.54 avg60=53.51 avg300=15.76 total=55048524

Without swap the kernel cannot swap out the anonymous memory above the soft limit anywhere. It therefore lets the cgroup grow beyond 600 MiB (693 MB after one minute) – but only very slowly: every request above memory.high is artificially delayed so that the service does not spread without limit. The service’s memory pressure is now at 83 %, no longer the I/O pressure, and after one minute no progress line has appeared in the journal yet. So it does not get faster – only slow in a different way. memory.high is a brake, not a recommendation. Only a limit that matches the working set helps; whoever prefers failing loudly over creeping quietly additionally sets a hard limit (MemoryMax) so that the OOM killer produces a clear error. Stop the service afterwards:

# on perf1
sudo systemctl stop berichtsjob
# on perf1
sudo systemctl reset-failed berichtsjob

Save your progress? Sign up for free

Checkpoint

# on perf1
swapon --show --noheadings

Expected: /swapfile file 4G 0B -2 (the USED column may show a few KiB).

# on perf1
systemctl is-active berichtsjob fresser

Expected: inactive twice.

# on perf1
grep -c swapfile /etc/fstab

Expected: 1.

Test yourself

  1. In which order does the kernel reclaim memory, and why does it need swap for anonymous memory?
  2. What is the difference between memory.high and memory.max?
  3. With which three pieces of evidence do you prove an OOM kill, and how do you recognize that a cgroup limit triggered it?
  4. A server has 11 GB free, 1.2 GB in swap, wa 24 % and almost no CPU load. What do you suspect?
  5. Why did the swap storm show mainly I/O pressure in PSI and hardly any memory pressure?

Answers:

  1. First discard clean cache pages, then write back dirty ones, then swap out anonymous pages. Anonymous memory has no copy on disk – without swap there is no place for it.
  2. memory.high throttles and swaps out (smaller desk), memory.max triggers the OOM killer in this cgroup (thrown out).
  3. systemctl status (Result: oom-kill), journal (status=9/KILL), dmesg (Killed process); constraint=CONSTRAINT_MEMCG shows the cgroup limit.
  4. A memory limit that is too small for a service whose working set does not fit – thrashing; check with memory.high, memory.events and memory.swap.current of the cgroup.
  5. PSI counts waiting for pages that are read from swap as I/O waiting; memory pressure is measured mainly during reclaim.

Interview Note

“A server is swapping. Is that bad?” – Not necessarily: swap for rarely used memory is healthy. What is bad is constant swapping in and out (si/so in vmstat permanently above zero, major faults, I/O pressure), that is thrashing. Whoever also names cgroup limits – memory.high throttles, memory.max kills –, can tell an OOM kill with CONSTRAINT_MEMCG in dmesg from a system-wide one and knows that a swap storm often appears as I/O pressure in PSI, impresses.

Enterprise Note

In container platforms memory limits are everywhere, and their wrong size is one of the most common causes of creeping slow or constantly restarting services. Kubernetes sets a container’s limit as memory.max; with the optional feature Memory QoS additionally memory.high. Good practice: derive limits from consumption measured under load, monitor and alert on memory.events (high, oom_kill), and have a clear policy for swap – some platforms forbid it entirely to get predictable latency. OOM kills belong in central log monitoring: a service that was ended by the OOM killer three times at night and restarted by systemd otherwise goes unnoticed.

Summary

  • Reclaim: first clean cache, then dirty cache, then anonymous memory into swap. kswapd in the background, direct reclaim slows down the requesting process.
  • Set up swap: fallocate, chmod 600, mkswap, swapon, /etc/fstab. swappiness weighs swapping out against discarding cache.
  • Thrashing: working set larger than the allowed memory – measured almost 300 times slower, with an idle CPU.
  • cgroup limits: memory.high throttles and swaps out, memory.max triggers the OOM killer; memory.events counts both.
  • Prove an OOM kill: systemctl status (Result: oom-kill), journal (status=9/KILL), dmesg (CONSTRAINT_MEMCG, Killed process).
  • memleak shows the call chains of outstanding requests.
  • A swap storm appears in PSI mainly as I/O pressure; swapoff/swapon brings swapped-out pages back all at once.

Commands at a glance

Command What it does Parameters
fallocate -l 4G /swapfile create a file of fixed size -l length
mkswap /swapfile / swapon / swapoff create swap / switch on / off –
sudo nano /etc/fstab enter swap permanently file
swapon --show [--noheadings] active swap areas –
systemd-run -p MemoryMax=… -p MemoryHigh=… -p MemorySwapMax=… service with memory limits see Background
systemctl set-property --runtime DIENST MemoryHigh=2G change a limit while running (DIENST = service) --runtime only until restart
cat …/memory.high, memory.events, memory.swap.current limits and events of a cgroup –
journalctl -u DIENST -o cat / -o short-precise messages of a service -o format
sudo dmesg -T kernel log with time, OOM kills at the very bottom -T readable time
memleak-bpfcc -p PID --top 3 10 1 outstanding memory requests by call chain --top count, interval, count
sar -B 1 / sar -W 1 paging or swapping per second –
grep VmSwap /proc/PID/status swap share of a process –

Contents

More