28.3. Diagnosing Memory Problems

Memory pressure is not the same as low free memory. Linux uses otherwise idle memory for page cache, and it reclaims clean pages without touching swap. The questions that matter are whether a workload's working set fits, whether reclaim is causing stalls, whether swap is active, and whether a cgroup limit or an address-space limit is the actual constraint.

28.3.1. Working Sets, Page Cache, Reclaim, and Swap Activity

The key fields in /proc/meminfo are the total, the free pages, the estimate of memory available to new work, the page cache, and the dirty pages that still need writeback:

$ grep -E '^(MemTotal|MemFree|MemAvailable|Cached|SwapTotal|SwapFree|Dirty)' /proc/meminfo
MemTotal:        2020956 kB
MemFree:         1262088 kB
MemAvailable:    1686092 kB
Cached:           527824 kB
SwapTotal:             0 kB
SwapFree:              0 kB
Dirty:              2492 kB

Cached is mostly file-backed page cache; it is reclaimable, which is why MemAvailable is higher than MemFree. A file that has just been written is in the cache even though the writer has closed it:

$ dd if=/dev/zero of=cache-test.img bs=1M count=128 status=none

The command is silent because status=none suppresses the transfer summary. fincore reports how many pages of the file are resident:

$ fincore cache-test.img
  RES PAGES  SIZE FILE
 128M 32768  128M cache-test.img

All 128 MiB are cached. Reading the file again would be served from memory, so a storage benchmark that reads the same file twice is measuring the page cache, not the disk. fincore is the quick check: if the resident size is already the file size before the read, the cache is warm. To force a real read, use O_DIRECT, a different file, or a working set larger than available memory. Do not drop the system-wide cache to make a benchmark look better; that penalizes every other workload and still does not control the host cache.

Swap is a separate layer. This guest starts with none; create a 512 MiB swap file in john's workspace for the exercise, using absolute paths because root's tilde is not john's home:

$ sudo fallocate -l 512M /home/john/debian-handbook/performance/swapfile

The command produces no output on success. Restrict the file's permissions, also silently:

$ sudo chmod 600 /home/john/debian-handbook/performance/swapfile

Initialize the swap area:

$ sudo mkswap /home/john/debian-handbook/performance/swapfile
Setting up swapspace version 1, size = 512 MiB (536866816 bytes)
no label, UUID=98175c47-aa0b-40f5-b0ca-d557f5816f04

Activate the file; swapon produces no output. Confirm the size:

$ sudo swapon /home/john/debian-handbook/performance/swapfile
$ sudo swapon --show
NAME                                            TYPE SIZE USED PRIO
/home/john/debian-handbook/performance/swapfile file 512M   0B   -2

Produce the pressure with the memory-hog.py program listed in Section 28.3.2, started as a transient unit with a 1650 MiB request:

$ sudo systemd-run --unit=mem-hog --uid=john --collect python3 /home/john/debian-handbook/performance/memory-hog.py 1650
Running as unit: mem-hog.service; invocation ID: 5b36b674e56a48feb79c2c07b1d17549

The program touches every page it allocates, writes one allocated= line to the unit's journal, and then sleeps, so the 1.65 GiB working set stays resident while the samples are taken. On this 2 GiB guest that forces the kernel to reclaim cache and then swap. vmstat shows the swap counters and the blocked-process count:

$ vmstat 1 4
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 473008  85164   4616 211028   18  198 13854  3712  749    5  7  2 73 17  0  0
 0  0 473008  78360   4616 217556    0    0  5908     0  354  571  1  1 85 13  0  0
 0  1 473008  78360   4624 217556    0    0     0   564  147  150  0  0 82 18  0  0
 0  0 473008  78360   4632 217688  120    0   252    20  976 1951  3  3 80 15  0  0

swpd is used swap, si and so are swap-in and swap-out rates, and b is the number of blocked tasks. This interval has both swap-in and swap-out activity and a blocked task, so the system was under real memory pressure. free confirms it:

$ free -h
               total        used        free      shared  buff/cache   available
Mem:           1.9Gi       1.8Gi        81Mi       1.6Mi       217Mi       156Mi
Swap:          511Mi       461Mi        50Mi

Only 156 MiB is available; most of the cache has been reclaimed and 461 MiB is in swap. The pressure counter rises at the same time:

$ cat /proc/pressure/memory
some avg10=16.29 avg60=7.92 avg300=1.97 total=44002157
full avg10=15.85 avg60=7.76 avg300=1.93 total=42981012

A some and full value above zero means some or all tasks were stalled on memory reclaim. The program behind the load sleeps for thirty seconds and then exits; stop it before removing the swap area, so its pages are freed first:

$ sudo systemctl stop mem-hog

The stop command produces no output. Reclaim the workspace and disable swap:

$ sudo swapoff /home/john/debian-handbook/performance/swapfile
$ sudo rm /home/john/debian-handbook/performance/swapfile

Both commands are silent. Keeping a swap file only for an experiment is fine; on a production system, swap should be sized and monitored deliberately.

28.3.2. Finding Growing Processes and Cgroup Memory Pressure

A process that grows without bound is easiest to catch by sampling its resident set. The memory-hog.py example allocates a requested number of MiB, touches each page, prints its PID, and sleeps:

#!/usr/bin/env python3
import os
import sys
import time

megabytes = int(sys.argv[1]) if len(sys.argv) > 1 else 1024
chunks = []
for index in range(megabytes):
    chunk = bytearray(1024 * 1024)
    for page in range(0, len(chunk), 4096):
        chunk[page] = index & 0xFF
    chunks.append(chunk)
print(f"allocated={megabytes}MiB pid={os.getpid()}", flush=True)
time.sleep(30)

Start a 700 MiB instance as john:

$ sudo systemd-run --unit=mem-hog --uid=john --collect python3 /home/john/debian-handbook/performance/memory-hog.py 700
Running as unit: mem-hog.service; invocation ID: 17a97b7bded247d6b3bb6423453ead0e

The process identity is visible with its full command line, which also distinguishes this instance from other python3 processes:

$ sudo ps -o pid,vsz,rss,args -p $(pgrep -f 'memory-hog.py 700' | head -1)
    PID    VSZ   RSS COMMAND
  34255 734040 728224 /usr/bin/python3 /home/john/debian-handbook/performance/memory-hog.py 700

VSZ is virtual size and RSS is resident set size, both reported by ps in KiB; the 700 MiB request appears as 728224 KiB - about 711 MiB - once the interpreter and page granularity are included. Sampling RSS over time answers "is it growing?"; comparing VSZ with RSS answers "is the address space large but sparsely resident?" A process with a huge VSZ and a small RSS is not necessarily consuming physical memory.

Cgroups add a hard ceiling. Run the same program with MemoryMax=128M and no swap allowance:

$ sudo systemd-run --unit=mem-limit --property=MemoryMax=128M --property=MemorySwapMax=0 --uid=john python3 /home/john/debian-handbook/performance/memory-hog.py 400
Running as unit: mem-limit.service; invocation ID: cd6f589833904d789808774ed88b779e

The unit exceeds the limit almost immediately and the kernel OOM killer ends it. Selected output is shown; the Invocation: line, the leading Started journal line, and the trailing CPU/memory summary line are omitted:

$ sudo systemctl status mem-limit --no-pager
× mem-limit.service - [systemd-run] /usr/bin/python3 /home/john/debian-handbook/performance/memory-hog.py 400
     Loaded: loaded (/run/systemd/transient/mem-limit.service; transient)
  Transient: yes
     Active: failed (Result: oom-kill) since Tue 2026-11-24 00:34:56 UTC; 5s ago
   Duration: 199ms
    Process: 34517 ExecStart=/usr/bin/python3 /home/john/debian-handbook/performance/memory-hog.py 400 (code=killed, signal=KILL)
    Main PID: 34517 (code=killed, signal=KILL)
    Mem peak: 128M
        CPU: 140ms

Nov 24 00:34:56 perf1 systemd[1]: mem-limit.service: A process of this unit has been killed by the OOM killer.
Nov 24 00:34:56 perf1 systemd[1]: mem-limit.service: Main process exited, code=killed, status=9/KILL
Nov 24 00:34:56 perf1 systemd[1]: mem-limit.service: Failed with result 'oom-kill'.

This is a cgroup shortage, not a host shortage: the machine still had free memory, but this unit was not allowed to use it. MemoryMax is enforced by the memory controller; MemoryHigh would throttle and reclaim before reaching a hard limit, and MemorySwapMax bounds the swap the unit may use. Reset the failed unit before reusing its name:

$ sudo systemctl reset-failed mem-limit

The command produces no output when it succeeds; the failed state is cleared and the unit name can be reused.

28.3.3. Distinguishing Memory Shortage from Address Space Limits

Allocation can fail even when the host has plenty of memory if the process's address-space limit is too low. The relevant limit commands are:

Command Description
prlimit --as=BYTES -- command Apply an address-space limit to one command.
ulimit -v KB Set the virtual-memory limit for the current shell and its children.
/proc/PID/limits Show the limits inherited by a running process.

prlimit applies a limit to one command without changing the shell:

$ prlimit --as=200000000 -- python3 memory-hog.py 300
Traceback (most recent call last):
  File "/home/john/debian-handbook/performance/memory-hog.py", line 9, in <module>
MemoryError

The limit is 200,000,000 bytes of virtual address space, and the 300 MiB allocation cannot fit. The same program with a small request succeeds:

$ python3 memory-hog.py 10
allocated=10MiB pid=19350

So the failure was the limit, not a system-wide memory shortage. The shell equivalent is ulimit -v 200000, which takes the limit in KiB and applies to the current shell and its children; prlimit --as takes bytes and is convenient for a single test. A process that reports MemoryError, Cannot allocate memory, or a failed mmap should be checked for both limits and actual pressure:

Symptom Likely cause Next measurement
MemoryError immediately, low RSS address-space or data limit prlimit --pid PID --as, ulimit -a, /proc/PID/limits
RSS grows until killed, oom-kill cgroup or system shortage memory.events, memory.current, PSI memory
High si/so, long stalls reclaim and swap vmstat, sar -W, per-process RSS
Low MemAvailable, high cache page cache, not necessarily a leak fincore, workload working set

The table is a decision aid, not a substitute for the counters. In particular, a low MemFree value with a large Cached value is normal and should not trigger an alert by itself.