SELFHOST.COMPUTER

Swap & Swappiness Calculator

Many VPS images ship with no swap, so one memory spike can get your database killed. Tell the tool how much RAM and free disk you have and what the server mostly does, and it suggests a swap file size, a vm.swappiness value and the commands. The numbers are rules of thumb, not measurements. Everything runs in your browser.

Check free disk with df -h / and RAM with free -h. The pre-filled numbers are placeholders.

Commands


How it's calculated

  • Size. About twice the RAM on tiny servers (up to 1 GB), 2 GB for 1 to 2 GB of RAM, half the RAM up to 8 GB, and 4 GB above that. Databases cap at 2 GB; bursty workloads get 1.5 times the base, up to 8 GB. It rounds up to the nearest half gigabyte.
  • Disk. Swap never takes more than 10% of your free disk. If that would leave less than 0.5 GB, the tool recommends no swap file.
  • Swappiness. The kernel default is 60. This tool suggests 10 for ordinary web and container workloads, 1 for databases (swap only as a last resort) and 20 for bursty jobs. Lower values keep application memory in RAM longer; they don't switch swap off.

What swap is, and isn't

Swap isn't extra RAM. It's slow disk space that holds memory pages nobody is using, and a buffer that turns a sudden crash into a slowdown. If a server is swapping all the time (check the si and so columns of vmstat 5), swap is hiding a real shortage. Fix that with memory limits, SQLite instead of another Postgres, or a bigger plan. The small VPS RAM budget post walks through all of it, and the commands above come from it.

Caveats

  • Container-based virtualization (LXC, OpenVZ) often doesn't let you create swap yourself. On a normal KVM virtual machine it works.
  • Btrfs needs a different method: sudo btrfs filesystem mkswapfile --size 2G /swapfile on recent btrfs-progs. Other filesystems with copy-on-write have similar rules. fallocate is fine on ext4.
  • Resizing: run sudo swapoff /swapfile, delete the file, create a new one with the commands, and remove the old /etc/fstab line first so you don't end up with two.
  • Check before running twice. The echo ... | tee -a /etc/fstab line appends every time it runs.

Related

Work out how much RAM you need in the first place with the VPS size calculator, cap each container with the Compose generator (it sets mem_limit), and keep the server safe with the first 15 minutes.