Platform Engineering · Lesson 18

Swap and Virtual Memory Tuning

When a server runs short of memory, Linux has three moves: drop file cache, push idle pages to swap, or kill a process with the OOM killer. Which one happens, and to which process, is decided by settings an administrator controls: how much swap there is, vm.swappiness, overcommit, oom_score_adj, and cgroup memory limits. This lesson follows one memory spike on a database server and tunes it so the spike is absorbed, not fatal and not a slow-motion outage.

Difficulty: Advanced · Know this first: Lesson 09, Lesson 12

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar adds up minutes of degraded service during one memory spike. It is a worked example, not a measurement. The swap and pressure hops are where the settings decide between a kill and a crawl.

Try it: absorb, kill, or thrash?

Set how far the spike exceeds available memory, how much swap there is, and how much of the spilled memory is actively used (hot) rather than idle.

2 GBswapped out
lowswap traffic
absorbedoutcome

Absorbed: idle pages went to swap and stay there

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Memory tuning grows in four levels: reading memory, configuring swap, controlling who pays for a shortage, and fleet-wide policy.

Basic — Read memory correctly

At the basic level you can tell a healthy box from a short one.

  • free -h (available), vmstat 1 (si, so), top sorted by RES.
  • Page cache is reclaimable; anonymous memory needs swap or must stay.
  • journalctl -k | grep -i oom to find past kills.

Where it breaks: adding RAM because MemFree is low, when MemAvailable was fine all along.

Try it: Basic

Which number best tells you whether a server can start a 2 GB process without swapping?

Now do it: Run free -h on three servers and compare free with available.

Intermediate — Configure swap and swappiness

At the intermediate level you set swap up deliberately.

  • A swap file: fallocate -l 4G /swapfile; chmod 600 /swapfile; mkswap /swapfile; swapon /swapfile, plus /swapfile none swap sw 0 0 in fstab.
  • vm.swappiness in /etc/sysctl.d/99-memory.conf.
  • zram (zram-generator or zram-tools) for small machines and laptops.

Try it: Intermediate

You set vm.swappiness=0 expecting swap to be disabled, yet swap is still used under pressure. Why?

Now do it: Add a 1 GB swap file in a VM and watch swapon --show.

Advanced — Who pays for a shortage

At the advanced level shortages land on the right process.

  • cgroup v2: MemoryHigh= throttles, MemoryMax= kills inside the group, MemorySwapMax= caps swap.
  • OOMScoreAdjust= in units; systemd-oomd acting on PSI.
  • Overcommit: vm.overcommit_memory=2 with a ratio makes allocations fail up front, for workloads that handle it.

Try it: Advanced

A server freezes for 30 minutes under memory pressure but nothing is killed. What helps it fail fast instead?

Now do it: Check whether systemd-oomd is enabled: systemctl status systemd-oomd.

Master — Memory policy for a fleet

At the master level memory behaviour is a standard, not a surprise.

  • One swap and swappiness policy per workload class, applied by configuration management.
  • Alerts on PSI, swap traffic, and OOM kills; dashboards of MemAvailable over time.
  • Kubernetes nodes: kubelet memory reservations and eviction thresholds; swap support only where configured.

Trade-off: no swap gives predictable latency and abrupt kills; some swap absorbs spikes and risks slow degradation. Pick per workload, and limit batch jobs either way.

Try it: Master

Which alert best predicts a memory incident on a fleet?

Now do it: Graph /proc/pressure/memory for a busy server for a day.

Go deeper

Commands to inspect memory, add a swap file safely, and run a job inside a memory limit. Try them in a VM.

Inspect

free -h
grep -E "MemTotal|MemAvailable|SwapTotal|SwapFree|Committed_AS|CommitLimit" /proc/meminfo
vmstat 1 5                     # si/so: pages swapped in and out per second
cat /proc/pressure/memory      # time stalled waiting for memory
sysctl vm.swappiness vm.overcommit_memory
journalctl -k | grep -i "out of memory" | tail

Add a 2 GB swap file and tune swappiness

sudo fallocate -l 2G /swapfile && sudo chmod 600 /swapfile
sudo mkswap /swapfile && sudo swapon /swapfile
echo "/swapfile none swap sw 0 0" | sudo tee -a /etc/fstab
echo "vm.swappiness=10" | sudo tee /etc/sysctl.d/99-memory.conf && sudo sysctl --system >/dev/null
swapon --show

Run a job inside a memory limit

# the job is killed inside its own cgroup at 200 MB, and nothing else is touched
sudo systemd-run --scope -p MemoryMax=200M -p MemorySwapMax=0 \
  python3 -c "x = bytearray(500 * 1024 * 1024); print('never printed')"
echo "exit code: $?"
journalctl -k --since "-1 min" | grep -i "memory cgroup out of memory"

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. A month-end report took down a database twice.

Timeline

  • Month 1A report job on the database host loads a full year of orders. The host has no swap; the OOM killer picks PostgreSQL, the largest process. 25 minutes to recover.
  • Month 2The "fix" is 64 GB of swap and swappiness 100. The next report sends the database's working set to swap; queries take seconds for 40 minutes and nothing fails over because nothing died.
  • Month 3Swap is cut to 4 GB, swappiness set to 10, the report runs in a cgroup with MemoryMax=, and the database gets OOMScoreAdjust=-900. The report is killed once and rewritten to stream; nothing else is affected.

What changed after

Memory PSI and swap-in alerts page on-call, batch jobs run under memory limits by default, and the database host runs no ad-hoc jobs at all.

Try it yourself, from scratch

Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.

Before you start: A Linux VM or a spare machine where you have sudo (a cloud VM, Multipass, or VirtualBox). Some commands change the system; do not run them on a shared server.

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. Read memory the right way: available, swap, and pressure.

    free -h; grep -E "MemAvailable|SwapTotal|SwapFree|Committed_AS|CommitLimit" /proc/meminfo; cat /proc/pressure/memory
  2. Swap traffic (si and so) is what matters, not swap used.

    vmstat 1 5
  3. Add a 512 MB swap file, check it, and remove it again.

    sudo fallocate -l 512M /lab.swap && sudo chmod 600 /lab.swap && sudo mkswap /lab.swap >/dev/null && sudo swapon /lab.swap
    swapon --show; sysctl vm.swappiness
    sudo swapoff /lab.swap && sudo rm /lab.swap
  4. Run a greedy process inside a memory limit: only it is killed.

    sudo systemd-run --scope -p MemoryMax=100M -p MemorySwapMax=0 python3 -c "x = bytearray(300 * 1024 * 1024)"; echo "exit code: $?"
    journalctl -k --since "-2 min" --no-pager | grep -i "memory cgroup out of memory" | tail -1

2. Python: oom_score.py

This program models how the kernel chooses an OOM victim from memory use and oom_score_adj, and shows how protecting the database and penalising batch jobs changes the choice. Save it as oom_score.py, then run it.

# oom_score.py
TOTAL_MB = 16_384
procs = {  # name: (resident MB, oom_score_adj)
    "postgres": (6_200, 0), "report-job": (5_800, 0), "api": (1_400, 0), "sshd": (12, -1000)}

def victim(procs):
    scores = {}
    for name, (rss, adj) in procs.items():
        if adj == -1000:
            continue                      # never killed
        scores[name] = max(0, round(rss / TOTAL_MB * 1000) + adj)
    return max(scores, key=scores.get), dict(sorted(scores.items(), key=lambda kv: -kv[1]))

name, scores = victim(procs)
print("default settings:", scores, "-> kills", name)
procs["postgres"] = (6_200, -900)         # OOMScoreAdjust=-900 in the unit
procs["report-job"] = (5_800, 500)        # batch jobs volunteer to die first
name, scores = victim(procs)
print("tuned settings:  ", scores, "-> kills", name)

Run it, and you should see this output:

$ python3 oom_score.py
default settings: {'postgres': 378, 'report-job': 354, 'api': 85} -> kills postgres
tuned settings:   {'report-job': 854, 'api': 85, 'postgres': 0} -> kills report-job

3. What to notice

4. Advanced: every step as one Bash script

The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/swap-and-virtual-memory-tuning && cd ~/labs/swap-and-virtual-memory-tuning) and save this as lab.sh.

#!/usr/bin/env bash
# The Linux steps of "Swap and Virtual Memory Tuning", as one script (save it as lab.sh).
#
#   ./lab.sh          run every step, in order
#   ./lab.sh 2 4      run only steps 2 and 4
#   ./lab.sh --list   list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.

STEPS=(
  'Read memory the right way: available, swap, and pressure.'
  'Swap traffic (si and so) is what matters, not swap used.'
  'Add a 512 MB swap file, check it, and remove it again.'
  'Run a greedy process inside a memory limit: only it is killed.'
)

step_1() {
free -h; grep -E "MemAvailable|SwapTotal|SwapFree|Committed_AS|CommitLimit" /proc/meminfo; cat /proc/pressure/memory
}

step_2() {
vmstat 1 5
}

step_3() {
sudo fallocate -l 512M /lab.swap && sudo chmod 600 /lab.swap && sudo mkswap /lab.swap >/dev/null && sudo swapon /lab.swap
swapon --show; sysctl vm.swappiness
sudo swapoff /lab.swap && sudo rm /lab.swap
}

step_4() {
sudo systemd-run --scope -p MemoryMax=100M -p MemorySwapMax=0 python3 -c "x = bytearray(300 * 1024 * 1024)"; echo "exit code: $?"
journalctl -k --since "-2 min" --no-pager | grep -i "memory cgroup out of memory" | tail -1
}

# print a step that has to be run by hand, instead of running it
by_hand() {
  echo "  (run this one yourself: $1)"
  sed 's/^/    /'
}

RESULTS=()
run_step() {
  local n=$1 start=$SECONDS code
  printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
  "step_$n"
  code=$?
  RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}

summary() {
  echo
  echo "== summary"
  local r
  for r in "${RESULTS[@]}"; do echo "  $r"; done
}

case "${1:-}" in
  -h|--help) sed -n '2,6p' "$0"; exit 0 ;;
  --list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac

[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
  if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
    echo "there is no step '$n'; try --list" >&2
    exit 2
  fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done

Then make it executable and run it:

chmod +x lab.sh
./lab.sh --list     # the steps
./lab.sh            # every step, then a summary of exit codes and times
./lab.sh 2 3        # only steps 2 and 3

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

Set the memory policy for three server types: a PostgreSQL host, a Java API host, and a CI runner that builds containers.

Clarifying questions to ask

How much swap for each, and what swappiness? Which process should die first on each host? Where do limits go? What do you alert on?

Rough sizing

Say 64 GB database hosts with a 48 GB buffer pool, 16 GB API hosts with a 10 GB heap, and 32 GB CI runners with jobs that sometimes use 40 GB.

Shape of the answer

Database: 4 GB swap, swappiness 1 to 10, OOMScoreAdjust=-900, no ad-hoc jobs. API: 2 GB swap, a fixed heap below the cgroup limit, systemd-oomd on. CI runner: each job in a cgroup with MemoryMax=24G and MemorySwapMax=0, so a greedy build fails fast. Alerts on PSI, swap-in, and OOM kills everywhere.

Trade-offs to name

Swap smooths spikes and can hide a leak until it is a crawl; no swap fails abruptly but predictably. Tight cgroup limits fail jobs that would have finished; loose ones let one job hurt the host.

Saved on this device, in this browser.
Next in this series · Lesson 19
Package Management: apt, dnf, Repositories, and Updates

Almost everything on a Linux server arrived as a package: a signed archive with files, dependencies, and scripts, from a repository the system trusts.

Go to Lesson 19 →

Or browse the full course from the Lessons index.