Skip to content

Adding a swap file on Linux — sizing, swappiness, and when to skip it

Swap is not the villain memes make it out to be — for sub-4 GB cloud instances it is the difference between an OOM kill and a slowdown. Here is how we size, mount, and tune it.

Cloud images ship without swap. The reasoning is “swap on a network-attached volume is slow,” which is correct but incomplete: no swap at all means the kernel’s OOM killer is the only memory-pressure release valve. For sub-4 GB hosts running anything memory-bursty, the choice between “swap thrash for 30 seconds during peak” and “lose your application process” is not even close. This article documents the swap file pattern we put on every small host.

How to verify

Check what is in place.

free -h
swapon --show
cat /proc/swaps
grep -E '^[^#]*swap' /etc/fstab
sysctl vm.swappiness vm.vfs_cache_pressure

If swapon --show returns nothing, there is no active swap. free -h will show Swap: 0B 0B 0B. That is the state we are about to change.

What’s happening

Linux memory management has three pressure-release mechanisms:

  1. Reclaim the page cache — drop cleanly-readable pages of disk content from RAM. Fast and lossless.
  2. Swap out anonymous pages — write process memory (heap, stack) to a swap area and reclaim the RAM. Slower; the page faults back in when next accessed.
  3. OOM kill — when (1) and (2) cannot keep up, pick a victim process by score and SIGKILL it. Brutal and lossy.

Without a swap area, only (1) and (3) are available. Step (1) only helps for workloads dominated by file I/O. Anything with a heap (Java, Node, Python, Ruby, Go) cannot be reclaimed by step (1). The OOM killer is reached at the first hard memory pressure event. With swap, step (2) exists as a buffer — the host slows down but does not lose work. On NVMe-backed cloud volumes (the modern default), the slowdown is real but measured in tens to hundreds of milliseconds per fault, not seconds.

The right size depends on workload. For a host with 2 GB RAM running a small web service, 1–2 GB of swap is enough to absorb a brief spike. For a host with 16 GB RAM running a JVM with -Xmx14g, swap is almost useless because the JVM will not page out heap. The general rule: small hosts benefit, large hosts running large heaps do not. Database hosts running Postgres or MySQL want vm.swappiness=10 to keep the page cache resident and only swap anonymous memory under genuine pressure.

The procedure

  1. Decide the size. Practical defaults:

    • Cloud VM under 4 GB RAM: swap = RAM (1G for 1G, 2G for 2G).
    • Cloud VM 4–8 GB: 2 GB swap.
    • Cloud VM over 8 GB: skip unless the workload is known to spike.
    • Bare metal with spinning disk: do not put swap on the spinning disk; the latency is too high to be useful.
  2. Allocate the file. Use fallocate if the filesystem supports it (ext4, xfs do; ZFS does not — use dd there).

    sudo fallocate -l 2G /swapfile
    sudo chmod 0600 /swapfile

    chmod 0600 is essential — a swap file readable by anyone leaks process memory. fallocate is fast because it pre-reserves blocks without writing them; dd if=/dev/zero is the slow alternative for filesystems that do not support fallocate.

  3. Format the file as swap and activate it.

    sudo mkswap /swapfile
    sudo swapon /swapfile
    swapon --show
    free -h

    swapon --show should now list /swapfile with the configured size, priority -2 (the default for files).

  4. Make it persistent across reboots. Add to /etc/fstab:

    echo '/swapfile none swap sw,pri=10 0 0' | sudo tee -a /etc/fstab
    sudo systemctl daemon-reload

    The pri=10 sets a higher priority than the default — useful if you ever add multiple swap areas. Verify the entry by simulating mount:

    sudo swapoff /swapfile && sudo swapon -a && swapon --show
  5. Tune vm.swappiness and vm.vfs_cache_pressure. The kernel defaults are tuned for desktop workloads.

    sudo tee /etc/sysctl.d/99-swap-tuning.conf > /dev/null <<'EOF'
    vm.swappiness = 10
    vm.vfs_cache_pressure = 50
    EOF
    sudo sysctl --system | grep -E 'swappiness|vfs_cache'

    vm.swappiness=10 tells the kernel to prefer reclaiming the page cache over swapping anonymous memory. Sensible for servers (default is 60, which is desktop-friendly). vm.vfs_cache_pressure=50 reduces how aggressively the kernel reclaims inode/dentry caches. For database hosts, this keeps directory traversals fast.

  6. For database hosts, lower swappiness further. Postgres and MySQL maintainers recommend vm.swappiness=1 or even 0 — only swap as the last resort. The trade-off: when the OS does decide to swap, it has waited too long and the result is worse.

    echo 'vm.swappiness = 1' | sudo tee /etc/sysctl.d/99-db-swap.conf
    sudo sysctl --system
  7. Optional: zswap or zram for compressed swap. On hosts with plenty of CPU but tight RAM, zram compresses anonymous pages in RAM instead of writing them to disk — orders of magnitude faster than disk swap. Ubuntu 22.04+ has zram-tools:

    sudo apt install -y zram-tools
    sudo systemctl status zramswap

    For a VM with predictable memory pressure, this is often better than a swap file.

  8. Verify the host can handle a memory spike. Generate enough memory pressure to see swap kick in.

    stress-ng --vm 1 --vm-bytes 80% --timeout 30s
    # in another shell:
    watch -n 1 'free -h; swapon --show'

    You should see Swap start filling and the host stay responsive. If it does not — if the OOM killer fires before swap is used — something is wrong with the swap activation.

Common pitfalls

  • File permissions: /swapfile must be 0600. Anything looser leaks memory content to local users.
  • fallocate on a filesystem that does not properly support it (older Btrfs, some ZFS configurations) creates a file that mkswap will refuse. Use dd if=/dev/zero of=/swapfile bs=1M count=2048 as the fallback.
  • Forgetting to add to /etc/fstab — the swap works until the next reboot, then silently disappears.
  • Adding swap on a host where the application reserves all RAM intentionally (a JVM with -Xmx close to the box’s RAM) and then being surprised that swap fills up under GC pressure. Swap is a buffer, not a solution to undersized hosts.
  • Putting a 4 GB swap file on a 30 GB cloud volume during a disk-space crunch — the file consumes its full allocated size.

In the engagements we run, swap is on by default for small instances and tuned for the workload (web vs. database) automatically as part of the provisioning role. If you inherit a fleet of small hosts that have all hit OOM kills at some point, sweeping in a sensible swap baseline is usually the easiest first-week win — and it is part of the Managed Operations tuning pass.