Memory and Swap
How Linux uses RAM: virtual vs resident memory, the page cache, what happens when memory runs out, swap and swappiness, the OOM killer and oom_score_adj, spotting memory leaks, creating a swap file, making swap and sysctl settings permanent, and capping a service's memory with cgroups.
How Linux uses memory
Every process sees its own private virtual address space, as if it had the machine to itself. The kernel maps the parts it actually uses onto real RAM, page by page (a page is usually 4 KB). That's why there are two memory numbers for every process:
| Measure | In ps / top | Meaning |
|---|---|---|
| virtual size | VSZ / VIRT | everything the process has reserved or mapped. Can be huge and mostly unused |
| resident size | RSS / RES | pages actually in RAM right now. The number that matters |
Programs often reserve far more than they use (Java heaps, thread stacks, memory-mapped files), so a big VSZ alone means nothing.
The rest of RAM isn't wasted: the kernel fills it with the page cache, copies of files read from or written to disk. That's what buff/cache means in free, and it's given back the moment programs need memory.
Where memory goes, and what happens when it runs out
Big or leaking?
Find the process whose memory keeps growing.
A memory leak is a program that keeps allocating memory and never gives it back. It's not necessarily the biggest process right now, it's the one that keeps growing. A big but stable process (a cache with a fixed size, a database's buffer pool) is working as designed. To tell them apart, measure twice.
1. A snapshot
free -h
ps -o pid,rss,comm --sort=-rss -C cache-warmer,order-sync,report-batch-C name,name selects processes by name; rss is resident memory in KB.
total used free shared buff/cache available
Mem: 7.8Gi 798Mi 6.3Gi 12Mi 1.0Gi 7.1Gi
Swap: 0B 0B 0B
PID RSS COMMAND
25 132692 cache-warmer
26 19424 order-sync
27 10044 report-batchSwap: 0B: there's no swap at all. And cache-warmer is by far the biggest, at about 130 MB. Is it the problem?
2. Measure again
sleep 10; ps -o pid,rss,comm --sort=-rss -C cache-warmer,order-sync,report-batch PID RSS COMMAND
25 132692 cache-warmer
26 29708 order-sync
27 10044 report-batchcache-warmer hasn't changed by a single KB. order-sync grew by about 10 MB in 10 seconds.
3. Watch it grow
for i in 1 2 3; do ps -o rss= -C order-sync; sleep 2; donerss= prints the value without a header. watch -n 2 'ps -o pid,rss,comm -C order-sync' does the same in a refreshing screen (Ctrl+C to quit).
29708
31764
33820About 1 MB per second, every second. At that rate it fills this lab's 512 MB in minutes, and a real server's RAM within hours or days. That's the leak.
Save the name of the process that's leaking memory to /root/leaker.txt.
Expected result: /root/leaker.txt names the process whose RSS keeps growing.
Hint: the commands, explained
Compare RSS values a few seconds apart. The biggest process isn't the one growing.
echo order-sync > /root/leaker.txtWhat each part does
- You compared RSS (real memory) twice, a few seconds apart:
order-syncgrew each time, whilecache-warmerstayed the same. Growth, not size, is the sign of a leak.
Swap
Swap is disk space used as overflow for memory. When RAM is tight, the kernel writes pages that haven't been touched in a while to swap and reuses their RAM. If a process later touches a swapped-out page, it has to be read back from disk: a "major page fault", thousands of times slower than RAM.
So swap is a trade:
| A little swap | Heavy, constant swapping |
|---|---|
| Idle memory (startup code, rarely used data) moves out of the way, leaving more RAM for cache and active work | Active memory goes back and forth to disk ("thrashing"); the whole server crawls |
| Memory pressure becomes a slowdown you can see and fix | The real fix is more RAM or less usage |
Many cloud images ship with no swap, so memory exhaustion goes straight to the OOM killer. Whether to add swap is a judgement call: Kubernetes nodes traditionally run without it, while most general-purpose servers benefit from a small swap file as a cushion.
swapon --show # active swap devices and files
free -h # the Swap: line
vmstat 1 # si / so: pages swapped in / out per secondsi and so are the real signal: swap being used (swpd) is fine; swap being actively moved (sustained si/so) means you're short of RAM right now.
Swappiness
vm.swappiness (0–100, default 60) sets how eagerly the kernel swaps program memory versus dropping file cache:
| Value | Behaviour |
|---|---|
60 | default, balanced for desktops |
10 | common for servers and databases: prefer dropping cache, swap only under real pressure |
1 | swap almost only to avoid OOM |
0 | swap as little as possible (not "off") |
60
vm.swappiness=10The current value from /proc/sys/vm/swappiness, and the permanent setting written to /etc/sysctl.d/99-swap.conf.
Creating a swap file
fallocate -l 2G /swapfile # reserve the space (the lab uses 128M)
chmod 600 /swapfile # only root: swap holds copies of process memory
mkswap /swapfile # write the swap header
swapon /swapfile # activate now
echo '/swapfile none swap sw 0 0' >> /etc/fstab # activate at every bootSetting up swapspace version 1, size = 128 MiB (134213632 bytes)
no label, UUID=62fb528a-708b-4a9d-8bcd-6e7a275b2ed9
/swapfile: UUID="62fb528a-708b-4a9d-8bcd-6e7a275b2ed9" TYPE="swap"mkswap on the 128 MB lab file, then blkid confirming it's swap. On the lab machine swapon itself is refused (Operation not permitted) because containers can't change the host kernel's swap; on a VM it activates immediately.
How much? A common rule of thumb for servers today: 1–4 GB, or around half of RAM on small machines. Hibernation-sized swap (equal to RAM) is a desktop concern.
To remove swap: swapoff /swapfile, delete the fstab line, then rm /swapfile.
Create a swap file
Prepare a 128 MB swap file.
Swap is disk space the kernel can move rarely used memory pages to. It isn't a substitute for enough RAM, but a little swap gives the kernel room to push out memory that's allocated but idle, and turns a sudden OOM kill into a gradual slowdown you can notice and fix. A swap file is the easiest way to add swap: no repartitioning needed.
1. Check current swap
swapon --show
cat /proc/swapsFilename Type Size Used Priorityswapon --show prints nothing and /proc/swaps only its header: no swap.
2. Create the file
Many servers (and cloud images) already have a swap file called /swapfile, so this lab uses /var/swapfile. The name doesn't matter to the kernel.
fallocate -l 128M /var/swapfile
chmod 600 /var/swapfile
ls -lh /var/swapfile| Command | Why |
|---|---|
fallocate -l 128M | reserve 128 MB of disk instantly (real servers: often 1–4 GB) |
chmod 600 | swap holds copies of any process's memory: passwords, keys. Only root may read it |
-rw------- 1 root root 128M Nov 24 16:24 /var/swapfile3. Format it as swap
mkswap /var/swapfile
blkid /var/swapfileSetting up swapspace version 1, size = 128 MiB (134213632 bytes)
no label, UUID=62fb528a-708b-4a9d-8bcd-6e7a275b2ed9
/var/swapfile: UUID="62fb528a-708b-4a9d-8bcd-6e7a275b2ed9" TYPE="swap"mkswap writes a swap header; blkid confirms the file is now TYPE="swap".
4. Turning it on
On a real server the next command is:
swapon /var/swapfile
swapon --show → /var/swapfile file 128M 0B -2
free -h → Swap: 128Mi ...This lab machine is a container, which isn't allowed to change the host kernel's swap, so here it fails:
swapon: /var/swapfile: swapon failed: Operation not permittedThat's expected: the file is ready, and the next step makes it permanent the same way you would on a VM.
Create a 128 MB swap file at /var/swapfile with mode 600, formatted with mkswap.
Expected result: ls -lh /var/swapfile shows 128M and -rw-------, and blkid /var/swapfile shows TYPE="swap".
Hint: the commands, explained
fallocate -l 128M /var/swapfile
chmod 600 /var/swapfile
mkswap /var/swapfileWhat each part does
fallocate -l 128M /var/swapfile: reserve a 128 MB file on disk in one step (much faster than filling it withdd).chmod 600: only root may read or write it. Swap can hold copies of any program's memory, including passwords, somkswapwarns if others can read it.mkswap /var/swapfile: write a swap signature into the file so the kernel can use it. It prints the size and a UUID. Turn it on withswapon /var/swapfile, then check withswapon --show.
Kernel settings: sysctl
vm.swappiness is one of hundreds of kernel settings (sysctls) exposed under /proc/sys:
sysctl vm.swappiness # read (same as cat /proc/sys/vm/swappiness)
sysctl -w vm.swappiness=10 # change now (lost at reboot)
echo 'vm.swappiness=10' > /etc/sysctl.d/99-swap.conf # permanent
sysctl --system # reload all files in /etc/sysctl.d nowYou'll meet others in the Networking module (net.ipv4.ip_forward, connection backlog sizes). The pattern is always the same: a file in /etc/sysctl.d/ for permanence, sysctl -w or sysctl --system to apply now. Inside containers most sysctls are read-only, because the kernel is shared with the host.
Make it permanent
Activate the swap file at every boot, and make the kernel swap only when it must.
swapon only lasts until the next reboot. To activate swap at every boot, add it to /etc/fstab, the file that lists what to mount at startup. And the kernel setting vm.swappiness (0–100, default 60) controls how eagerly the kernel swaps. Servers usually set it low (10), so swap is a safety net rather than something used all the time.
1. Add it to /etc/fstab
echo '/var/swapfile none swap sw 0 0' >> /etc/fstab
tail -1 /etc/fstab| Field | Value | Meaning |
|---|---|---|
| 1 | /var/swapfile | what (the device or file) |
| 2 | none | where to mount (swap isn't mounted anywhere) |
| 3 | swap | filesystem type |
| 4 | sw | options |
| 5, 6 | 0 0 | no dump backup, no fsck at boot |
/var/swapfile none swap sw 0 0Always use >> (append). A single > would replace the whole fstab, and the server might not boot. On a real VM, test with swapon -a, which activates everything listed in fstab.
2. Set swappiness permanently
cat /proc/sys/vm/swappiness
echo 'vm.swappiness=10' > /etc/sysctl.d/99-swap.conf
cat /etc/sysctl.d/99-swap.confKernel settings ("sysctls") live under /proc/sys. Files in /etc/sysctl.d/ are applied at every boot.
60
vm.swappiness=10On a VM you'd apply it immediately with sysctl -p /etc/sysctl.d/99-swap.conf or sysctl -w vm.swappiness=10. Containers share the host's kernel, so here that's refused:
sysctl: setting key "vm.swappiness", ignoring: Read-only file system
vm.swappiness = 10- Add the swap file to
/etc/fstabso it's activated at boot. - Create
/etc/sysctl.d/99-swap.confsettingvm.swappiness=10.
Expected result: grep swapfile /etc/fstab shows a swap line, and the sysctl file contains vm.swappiness=10.
Hint: the commands, explained
echo '/var/swapfile none swap sw 0 0' >> /etc/fstab
echo 'vm.swappiness=10' > /etc/sysctl.d/99-swap.confWhat each part does
- The
/etc/fstabline has 6 fields: what (/var/swapfile), where (none, because swap isn't mounted on a folder), type (swap), options (sw), and two zeros (no dump, no fsck). It turns the swap on at every boot. vm.swappiness=10in/etc/sysctl.d/: tell the kernel to swap only under real memory pressure (default is 60). The file is read at boot;sysctl --systemapplies it now.
The OOM killer
When there's no cache left to drop and no swap left to use, the kernel must free memory or lock up. It picks a victim and kills it with SIGKILL: no warning, no cleanup.
The choice is based on each process's oom_score (roughly its share of memory, 0–1000), shifted by oom_score_adj (-1000 to +1000):
for p in $(pgrep -d' ' 'cache-warmer|order-sync|report-batch'); do
echo "$(cat /proc/$p/oom_score) $(cat /proc/$p/comm)"
done | sort -rn677 cache-warmer
669 order-sync
667 report-batchLeft alone, the kernel kills the biggest process, which may well be the one your customers need.
| oom_score_adj | Effect |
|---|---|
1000 | always the first victim |
0 | default |
-500 | strongly protected |
-1000 | never killed by the OOM killer |
echo 1000 > /proc/$(pgrep report-batch)/oom_score_adj # volunteer a batch job
cat /proc/$(pgrep report-batch)/oom_score1334Raising a score is always allowed; lowering it needs privileges (CAP_SYS_RESOURCE). Make it permanent per service in systemd: OOMScoreAdjust=-500 for the database, OOMScoreAdjust=1000 for batch jobs. sshd typically runs with -1000 so you can still log in to a struggling server.
Finding OOM kills
An OOM kill looks like "the app just disappeared". The evidence is in the kernel log:
dmesg -T | grep -i -A2 'out of memory'
journalctl -k --since yesterday | grep -i oomYou'll see a line like Out of memory: Killed process 1234 (java) total-vm:... anon-rss:..., followed by the memory state at the time. In Kubernetes the same event shows up as a container status of OOMKilled (exit code 137 = 128 + 9, SIGKILL).
Contain the damage
Stop the leak, and make the report job the OOM killer's first choice.
When memory runs out completely, the kernel's OOM killer picks a victim using each process's oom_score (0–1000+): mostly how much memory it uses, adjusted by oom_score_adj (-1000 to 1000). A higher score means "kill me first". -1000 means "never kill this one".
You can't fix the leaking program's code right now, but you can stop it, and decide in advance what the kernel should sacrifice next time.
1. Stop the leak
kill $(pgrep order-sync)Its memory is returned to the system immediately. (On a real server you'd restart it under systemd with a memory cap, MemoryMax=, until the bug is fixed.)
2. Who would the OOM killer pick?
for p in $(pgrep -d' ' 'cache-warmer|order-sync|report-batch'); do
echo "$(cat /proc/$p/oom_score) $(cat /proc/$p/comm)"
done | sort -rnFor each PID, print its OOM score and name; sort highest first.
677 cache-warmer
669 order-sync
667 report-batch(Measured before stopping order-sync.) The scores are close, and the biggest process wins. Bad luck if that's the one your customers depend on.
3. Volunteer the batch job
echo 1000 > /proc/$(pgrep report-batch)/oom_score_adj
cat /proc/$(pgrep report-batch)/oom_score1334The report job now has by far the highest score: if memory runs out, it dies first, and it can simply run again later.
Anyone may make a process more likely to be killed. Making one less likely (a negative value) needs extra privileges: in this lab even root is refused (echo: write error: Permission denied). On servers, set it in the systemd unit: OOMScoreAdjust=-500 for the database, OOMScoreAdjust=1000 for batch work. And when a process vanished overnight, look for Out of memory: Killed process in dmesg -T or journalctl -k.
- Stop the leaking process.
- Set
oom_score_adjof report-batch to 1000, so it's the OOM killer's first choice.
Expected result: pgrep order-sync finds nothing, and cat /proc/$(pgrep report-batch)/oom_score_adj prints 1000.
Hint: the commands, explained
kill $(pgrep order-sync)
echo 1000 > /proc/$(pgrep report-batch)/oom_score_adjWhat each part does
pgrep order-syncprints the process's PID;$( )puts that number into the command, so it becomeskill 26. Plainkillsends SIGTERM, the polite stop.echo 1000 > /proc/PID/oom_score_adj: set the OOM adjustment to the maximum, so the kernel kills this process first if memory runs out.
Memory leaks
A leak is memory that's allocated and never released. The biggest process isn't necessarily leaking; the growing one is:
PID RSS COMMAND
25 132692 cache-warmer
26 19424 order-sync
27 10044 report-batch
PID RSS COMMAND
25 132692 cache-warmer
26 29708 order-sync
27 10044 report-batchThe same ps command ten seconds apart. cache-warmer is big and perfectly flat; order-sync grew by 10 MB.
In practice, the monitoring graph of a leaking service looks like a saw: memory climbs steadily, the process is OOM-killed or restarted, memory drops, and it climbs again. Short-term fixes, while developers find the bug:
- restart the service on a schedule (crude but common),
- cap it with a cgroup so it's killed before it hurts others:
MemoryMax=1Gin its systemd unit, or a container memory limit, - protect everything else with
oom_score_adj.
Capping memory with cgroups
nice and ulimit don't limit memory well. cgroups do, for a whole service or container:
| Where | Setting |
|---|---|
| systemd unit | MemoryHigh=800M (throttle and reclaim above this), MemoryMax=1G (hard limit: OOM-kill inside the service) |
| Docker | docker run --memory=1g |
| Kubernetes | resources.limits.memory: 1Gi |
When a cgroup hits its limit, the OOM killer acts only inside that cgroup: the leaking service dies, the rest of the server is untouched. That's the main reason containers have memory limits.
Judging memory by VSZ. It includes reservations never used. Use RSS/RES.
Blaming the biggest process. Measure over time; the leak is the one that grows.
> instead of >> on /etc/fstab. You replace the whole file and the server may not boot. Back it up first: cp /etc/fstab /etc/fstab.bak.
World-readable swap. Anyone could read other processes' memory from it. Always chmod 600.
Treating swap as extra RAM. Constant swapping (si/so in vmstat) means the server needs more memory or less load.
"What's the difference between VSZ and RSS?" VSZ is all virtual memory a process has mapped; RSS is what's actually resident in RAM.
"What is swap and when is it bad?" Disk used as overflow for memory. A little is a useful cushion; sustained swap-in/out (thrashing) makes everything slow.
"What is the OOM killer and how do you influence it?" The kernel's last resort when memory is exhausted: it kills the process with the highest oom_score. Adjust with oom_score_adj or OOMScoreAdjust= in systemd; check kills with dmesg or journalctl -k.
"How do you add swap to a server?" fallocate a file, chmod 600, mkswap, swapon, and add it to /etc/fstab.
"A container keeps restarting with exit code 137. Why?" 137 = killed by SIGKILL, usually OOMKilled: it hit its memory limit. Check the limit and the app's memory use.
Summary
- VSZ is reserved, RSS is real. Spare RAM becomes page cache, given back on demand.
- Out of memory: reclaim cache → swap → OOM killer (SIGKILL by
oom_score). - Swap file:
fallocate,chmod 600,mkswap,swapon, fstab line. Watchsi/so. vm.swappiness(servers ~10) via/etc/sysctl.d/;sysctl -w/--systemto apply.oom_score_adj/OOMScoreAdjust=choose victims;dmesg -T,journalctl -kshow kills; exit 137 = SIGKILL.- Leaks grow over time; cap services with
MemoryMax=or container limits.
Quick quiz
You've practised everything in this lesson
Every task was checked on your own machine. You can end the lab, or keep experimenting in the terminal.