Learn / Linux / Processes & System
Lesson 27 of 74

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.

20 min read Report a problem Hands-on lab included 6-question quiz

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:

MeasureIn ps / topMeaning
virtual sizeVSZ / VIRTeverything the process has reserved or mapped. Can be huge and mostly unused
resident sizeRSS / RESpages 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

Program memory (RSS)heap, stacks, libraries
Page cachereclaimable
Free
programs keep growing
1 · Reclaim cachedrop clean file pages: cheap, invisible
still not enough
2 · Swapwrite idle program pages to disk: slow, but nothing dies
no swap left
3 · OOM killerSIGKILL the process with the highest oom_score
Try it · Task 1 of 4

Big or leaking?

Find the process whose memory keeps growing.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

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

bash
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.

text
               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-batch

Swap: 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

bash
sleep 10; ps -o pid,rss,comm --sort=-rss -C cache-warmer,order-sync,report-batch
text
    PID   RSS COMMAND
     25 132692 cache-warmer
     26 29708 order-sync
     27 10044 report-batch

cache-warmer hasn't changed by a single KB. order-sync grew by about 10 MB in 10 seconds.

3. Watch it grow

bash
for i in 1 2 3; do ps -o rss= -C order-sync; sleep 2; done

rss= 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).

text
29708
31764
33820

About 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.

2 · Your task

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.

text
echo order-sync > /root/leaker.txt

What each part does

  • You compared RSS (real memory) twice, a few seconds apart: order-sync grew each time, while cache-warmer stayed the same. Growth, not size, is the sign of a leak.
First start the lab machine in the terminal panel on the right.

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 swapHeavy, constant swapping
Idle memory (startup code, rarely used data) moves out of the way, leaving more RAM for cache and active workActive memory goes back and forth to disk ("thrashing"); the whole server crawls
Memory pressure becomes a slowdown you can see and fixThe 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.

bash
swapon --show        # active swap devices and files
free -h              # the Swap: line
vmstat 1             # si / so: pages swapped in / out per second

si 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:

ValueBehaviour
60default, balanced for desktops
10common for servers and databases: prefer dropping cache, swap only under real pressure
1swap almost only to avoid OOM
0swap as little as possible (not "off")
text
60
vm.swappiness=10

The current value from /proc/sys/vm/swappiness, and the permanent setting written to /etc/sysctl.d/99-swap.conf.

Creating a swap file

bash
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 boot
text
Setting 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.

Try it · Task 2 of 4

Create a swap file

Prepare a 128 MB swap file.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

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

bash
swapon --show
cat /proc/swaps
text
Filename				Type		Size		Used		Priority

swapon --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.

bash
fallocate -l 128M /var/swapfile
chmod 600 /var/swapfile
ls -lh /var/swapfile
CommandWhy
fallocate -l 128Mreserve 128 MB of disk instantly (real servers: often 1–4 GB)
chmod 600swap holds copies of any process's memory: passwords, keys. Only root may read it
text
-rw------- 1 root root 128M Nov 24 16:24 /var/swapfile

3. Format it as swap

bash
mkswap /var/swapfile
blkid /var/swapfile
text
Setting 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:

text
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:

text
swapon: /var/swapfile: swapon failed: Operation not permitted

That's expected: the file is ready, and the next step makes it permanent the same way you would on a VM.

2 · Your task

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
text
fallocate -l 128M /var/swapfile
chmod 600 /var/swapfile
mkswap /var/swapfile

What each part does

  • fallocate -l 128M /var/swapfile: reserve a 128 MB file on disk in one step (much faster than filling it with dd).
  • chmod 600: only root may read or write it. Swap can hold copies of any program's memory, including passwords, so mkswap warns 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 with swapon /var/swapfile, then check with swapon --show.
First start the lab machine in the terminal panel on the right.

Kernel settings: sysctl

vm.swappiness is one of hundreds of kernel settings (sysctls) exposed under /proc/sys:

bash
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 now

You'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.

Try it · Task 3 of 4

Make it permanent

Activate the swap file at every boot, and make the kernel swap only when it must.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

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

bash
echo '/var/swapfile none swap sw 0 0' >> /etc/fstab
tail -1 /etc/fstab
FieldValueMeaning
1/var/swapfilewhat (the device or file)
2nonewhere to mount (swap isn't mounted anywhere)
3swapfilesystem type
4swoptions
5, 60 0no dump backup, no fsck at boot
text
/var/swapfile none swap sw 0 0

Always 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

bash
cat /proc/sys/vm/swappiness
echo 'vm.swappiness=10' > /etc/sysctl.d/99-swap.conf
cat /etc/sysctl.d/99-swap.conf

Kernel settings ("sysctls") live under /proc/sys. Files in /etc/sysctl.d/ are applied at every boot.

text
60
vm.swappiness=10

On 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:

text
sysctl: setting key "vm.swappiness", ignoring: Read-only file system
vm.swappiness = 10
2 · Your task
  1. Add the swap file to /etc/fstab so it's activated at boot.
  2. Create /etc/sysctl.d/99-swap.conf setting vm.swappiness=10.

Expected result: grep swapfile /etc/fstab shows a swap line, and the sysctl file contains vm.swappiness=10.

Hint: the commands, explained
text
echo '/var/swapfile none swap sw 0 0' >> /etc/fstab
echo 'vm.swappiness=10' > /etc/sysctl.d/99-swap.conf

What each part does

  • The /etc/fstab line 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=10 in /etc/sysctl.d/: tell the kernel to swap only under real memory pressure (default is 60). The file is read at boot; sysctl --system applies it now.
First start the lab machine in the terminal panel on the right.

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):

bash
for p in $(pgrep -d' ' 'cache-warmer|order-sync|report-batch'); do
  echo "$(cat /proc/$p/oom_score) $(cat /proc/$p/comm)"
done | sort -rn
text
677 cache-warmer
669 order-sync
667 report-batch

Left alone, the kernel kills the biggest process, which may well be the one your customers need.

oom_score_adjEffect
1000always the first victim
0default
-500strongly protected
-1000never killed by the OOM killer
bash
echo 1000 > /proc/$(pgrep report-batch)/oom_score_adj   # volunteer a batch job
cat /proc/$(pgrep report-batch)/oom_score
text
1334

Raising 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:

text
dmesg -T | grep -i -A2 'out of memory'
journalctl -k --since yesterday | grep -i oom

You'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).

Try it · Task 4 of 4

Contain the damage

Stop the leak, and make the report job the OOM killer's first choice.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

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

bash
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?

bash
for p in $(pgrep -d' ' 'cache-warmer|order-sync|report-batch'); do
  echo "$(cat /proc/$p/oom_score) $(cat /proc/$p/comm)"
done | sort -rn

For each PID, print its OOM score and name; sort highest first.

text
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

bash
echo 1000 > /proc/$(pgrep report-batch)/oom_score_adj
cat /proc/$(pgrep report-batch)/oom_score
text
1334

The 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.

2 · Your task
  1. Stop the leaking process.
  2. Set oom_score_adj of 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
text
kill $(pgrep order-sync)
echo 1000 > /proc/$(pgrep report-batch)/oom_score_adj

What each part does

  • pgrep order-sync prints the process's PID; $( ) puts that number into the command, so it becomes kill 26. Plain kill sends 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.
First start the lab machine in the terminal panel on the right.

Memory leaks

A leak is memory that's allocated and never released. The biggest process isn't necessarily leaking; the growing one is:

text
    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-batch

The 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=1G in 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:

WhereSetting
systemd unitMemoryHigh=800M (throttle and reclaim above this), MemoryMax=1G (hard limit: OOM-kill inside the service)
Dockerdocker run --memory=1g
Kubernetesresources.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. Watch si/so.
  • vm.swappiness (servers ~10) via /etc/sysctl.d/; sysctl -w / --system to apply.
  • oom_score_adj / OOMScoreAdjust= choose victims; dmesg -T, journalctl -k show kills; exit 137 = SIGKILL.
  • Leaks grow over time; cap services with MemoryMax= or container limits.
Check your understanding

Quick quiz

Feedback