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:
- Reclaim the page cache — drop cleanly-readable pages of disk content from RAM. Fast and lossless.
- 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.
- OOM kill — when (1) and (2) cannot keep up, pick a victim process by score and
SIGKILLit. 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
-
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.
- Cloud VM under 4 GB RAM:
-
Allocate the file. Use
fallocateif the filesystem supports it (ext4, xfs do; ZFS does not — useddthere).sudo fallocate -l 2G /swapfile sudo chmod 0600 /swapfilechmod 0600is essential — a swap file readable by anyone leaks process memory.fallocateis fast because it pre-reserves blocks without writing them;dd if=/dev/zerois the slow alternative for filesystems that do not support fallocate. -
Format the file as swap and activate it.
sudo mkswap /swapfile sudo swapon /swapfile swapon --show free -hswapon --showshould now list/swapfilewith the configured size, priority-2(the default for files). -
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-reloadThe
pri=10sets 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 -
Tune
vm.swappinessandvm.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=10tells 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=50reduces how aggressively the kernel reclaims inode/dentry caches. For database hosts, this keeps directory traversals fast. -
For database hosts, lower swappiness further. Postgres and MySQL maintainers recommend
vm.swappiness=1or even0— 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 -
Optional: zswap or zram for compressed swap. On hosts with plenty of CPU but tight RAM,
zramcompresses anonymous pages in RAM instead of writing them to disk — orders of magnitude faster than disk swap. Ubuntu 22.04+ haszram-tools:sudo apt install -y zram-tools sudo systemctl status zramswapFor a VM with predictable memory pressure, this is often better than a swap file.
-
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
Swapstart 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:
/swapfilemust be0600. Anything looser leaks memory content to local users. fallocateon a filesystem that does not properly support it (older Btrfs, some ZFS configurations) creates a file thatmkswapwill refuse. Usedd if=/dev/zero of=/swapfile bs=1M count=2048as 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
-Xmxclose 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.