Skip to content

Tuning Linux swap and swappiness for servers

What vm.swappiness actually controls (reclaim preference, not a threshold), how to size and add a swap file safely, set swappiness persistently, and read memory pressure with vmstat, free, and PSI.

The single most common myth about Linux memory is that vm.swappiness=0 turns swap off. It does not. Swappiness is not a threshold, a percentage of RAM, or an on/off switch — it is the kernel’s relative preference for reclaiming anonymous pages (your programs’ heap and stack) versus dropping page cache (file data the kernel is holding in RAM). A low value tells the kernel “when you need to free memory, drop cache before you swap.” A value of 0 discourages swapping as strongly as the dial allows, but the kernel will still swap anonymous pages rather than invoke the OOM killer when it is genuinely out of memory. If you want swap truly off, you run swapoff, not swappiness=0. This guide covers what the dial really does, how to add a swap file the safe way, how to set the value so it survives a reboot, and how to read actual memory pressure instead of guessing.

What you’ll accomplish

  • Understand vm.swappiness as a reclaim preference on a 0–200 scale, not a percentage or a threshold.
  • Add a correctly sized, correctly permissioned swap file and register it in /etc/fstab.
  • Set vm.swappiness and vm.vfs_cache_pressure live and persist them across reboots.
  • Read real memory pressure with vmstat, free -h, and the PSI file /proc/pressure/memory.
  • Choose a sane swap policy for a database host versus a general-purpose server.

Prerequisites

  • A Linux server with root or sudo.
  • Kernel 4.20 or newer if you want Pressure Stall Information (/proc/pressure/memory); it is enabled by default on most current distributions.
  • On cgroup v2 systems, per-service PSI is also available under /sys/fs/cgroup/<slice>/memory.pressure.
  • Extra care on database hosts: changing swap behaviour under a live workload can move latency in ways you must be ready to observe and revert.

How it works

When the kernel runs low on free RAM it reclaims pages to make room. It has two broad sources. Page cache is file-backed: clean cached pages can simply be dropped and re-read from disk later, which is cheap. Anonymous pages — process heap, stack, malloc’d memory — have no file behind them, so to reclaim them the kernel must first write them to swap, which is comparatively expensive.

vm.swappiness is the dial that biases this choice. On modern kernels (5.8+) its range is 0 to 200; older kernels cap at 100. The default is usually 60. A higher value makes the kernel more willing to swap anonymous pages so it can keep more page cache; a lower value makes it prefer reclaiming cache and leave anonymous memory resident. Crucially, 0 does not mean “never swap” — it means “avoid swapping until doing so is the only way to avoid an out-of-memory situation.” The kernel still swaps under real pressure.

Decision flow showing the kernel weighing page cache reclaim against swapping anonymous pages, with vm.swappiness as the dial and a note that swappiness=0 does not disable swap

A companion knob, vm.vfs_cache_pressure, controls how aggressively the kernel reclaims the memory used for directory and inode caches (dentries and inodes). The default is 100. Lowering it makes the kernel keep filesystem metadata cached longer; raising it reclaims that metadata sooner. It is a separate lever from swappiness and is worth tuning only on workloads that walk large directory trees.

The number that tells you whether swapping is actually hurting you is not swap usage — a few used megabytes of long-idle pages is harmless. What matters is active swap traffic and stall time. vmstat exposes the si/so columns (swap-in/swap-out per second). PSI, in /proc/pressure/memory, reports the share of time tasks stalled waiting on memory. Non-zero si/so under load plus a rising PSI some avg10 is real pressure; idle swap with quiet columns is not.

Step-by-step

  1. Check what you have now. Read the current swappiness, memory layout, and any active swap devices.

    cat /proc/sys/vm/swappiness
    free -h
    swapon --show

    Expected: swappiness prints a number (often 60); free -h shows a Swap: row; swapon --show lists devices, or prints nothing if no swap is configured.

  2. Create a swap file. Prefer fallocate for speed; fall back to dd if your filesystem does not support it well (older ext4 on some kernels, or when you hit swapon: swapfile has holes). This example makes a 4 GiB file.

    sudo fallocate -l 4G /swapfile

    If swapon later complains about holes, recreate it with dd instead:

    sudo dd if=/dev/zero of=/swapfile bs=1M count=4096 status=progress

    Expected: a /swapfile of the requested size (ls -lh /swapfile shows 4.0G).

  3. Lock down permissions, then format it as swap. The file must be readable only by root, or swapon will refuse it.

    sudo chmod 0600 /swapfile
    sudo mkswap /swapfile

    Expected: mkswap prints Setting up swapspace version 1, size = 4 GiB and a UUID.

  4. Enable it and confirm.

    sudo swapon /swapfile
    swapon --show

    Expected: swapon --show now lists /swapfile with TYPE file and the correct SIZE.

  5. Make the swap file permanent. Add an /etc/fstab entry so it comes back after a reboot.

    echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

    Verify the fstab is parseable before you trust it:

    sudo swapoff /swapfile && sudo swapon -a && swapon --show

    Expected: swapon -a reads fstab and re-enables /swapfile with no error.

  6. Set swappiness live. For most servers a value of 10 is a reasonable starting point.

    sudo sysctl vm.swappiness=10

    Expected: the command echoes vm.swappiness = 10.

  7. Persist swappiness and cache pressure. Live sysctl changes are lost on reboot; write them to a drop-in file under /etc/sysctl.d/.

    printf 'vm.swappiness=10\nvm.vfs_cache_pressure=100\n' | sudo tee /etc/sysctl.d/99-swap.conf

    Then apply every drop-in:

    sudo sysctl --system

    Expected: sysctl --system prints the files it reads, including * Applying /etc/sysctl.d/99-swap.conf ..., followed by vm.swappiness = 10 and vm.vfs_cache_pressure = 100.

  8. Watch pressure under load. Run vmstat 1 and read the si (swap-in) and so (swap-out) columns while the workload runs. In a second terminal read the PSI file.

    vmstat 1
    cat /proc/pressure/memory

    Expected: si/so sit at or near 0 unless RAM is genuinely exhausted; PSI shows some avg10=0.00 (or a low number) when there is no memory stall.

Validate it works

  • swapon --show lists your swap device with the expected size and type.
  • sysctl vm.swappiness returns 10 (or whatever you set), and the value survives sudo reboot because it lives in /etc/sysctl.d/99-swap.conf.
  • Under representative load, vmstat 1 keeps si/so at or near zero. Sustained non-zero values mean the box is short on RAM, not that swappiness is wrong.
  • /proc/pressure/memory shows a low some avg10. A full avg10 above zero means tasks are stalling on memory and you should investigate RAM sizing, not just the dial.

Troubleshooting

  • swapon: /swapfile: insecure permissions 0644, 0600 suggested. The swap file is world-readable. Fix it with sudo chmod 0600 /swapfile, then sudo swapon /swapfile again. swapon refuses to attach a swap file that other users could read.
  • Swappiness reverts to 60 after reboot. The value was only set live, or it lives in a file that is not read. Confirm the drop-in exists and is applied: cat /etc/sysctl.d/99-swap.conf then sysctl vm.swappiness. A stray setting in /etc/sysctl.conf or a lexically later file in /etc/sysctl.d/ can also override yours — files are read in order, and the last one wins.
  • Swap is heavily used even though swappiness is low. Low swappiness discourages swapping; it cannot conjure RAM. Heavy swap use at low swappiness means the machine is genuinely out of memory. The fix is more RAM or less resident memory (fewer workers, smaller caches), not a lower dial. Confirm with free -h — if available is near zero, that is the real problem.
  • Database latency spikes that correlate with any swapping. For latency-sensitive engines (Postgres, MySQL, Redis) even a little swapping of hot pages shows up as tail-latency spikes. Set swappiness very low (1) and, more importantly, make sure the working set fits in RAM. Watch si/so during the spike window to confirm swap is the cause.
  • Consider zram instead of disk swap. On memory-constrained hosts, zram provides a compressed swap device in RAM, trading a little CPU for far lower swap latency than disk. It is not a substitute for enough RAM, but it softens spikes better than a disk swap file. It is configured separately (zramctl / a distro service), not through swappiness.
  • OOM killer fires with swap disabled. With no swap, the moment anonymous demand exceeds RAM the kernel invokes the OOM killer. If you see processes killed and swapon --show is empty, either add swap to give the kernel headroom or reduce memory demand. Check dmesg | grep -i oom for the victims.

When this is the wrong approach

Swap tuning manages the symptom of memory pressure; it rarely fixes the cause. If a server swaps regularly, the honest fix is usually right-sizing RAM, not enlarging swap and hoping the dial hides it. For latency-critical databases, the goal is to keep the working set resident: set swappiness very low, size RAM to the data, and monitor si/so and PSI — adding more swap is the wrong instinct there. And on containerized or Kubernetes hosts, swap is frequently disabled by the platform entirely (the kubelet historically required it off), so tuning swappiness inside a pod may do nothing; adjust node-level memory requests and limits instead. See also Too many open files: raising ulimits safely and Diagnose a disk I/O bottleneck with iostat for the neighbouring limits you will hit once memory is sorted. The kernel’s own reference for these knobs is the vm sysctl documentation.

If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.