Add Swap to a VPS: A Safety Net for Low Memory
When a server runs out of RAM, Linux starts killing processes — often the very database or app you care about. A swap file gives it somewhere to put idle memory instead. It's a safety net, not extra speed.
Check what you have
free -h
swapon --show
If the Swap line shows 0, there's none.
Add a 2 GB swap file
fallocate -l 2G /swapfile
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile
echo '/swapfile none swap sw 0 0' >> /etc/fstab
The last line makes it survive reboots.
Tell Linux to use it sparingly
By default Linux swaps quite eagerly. On a server you usually want it only as a last resort:
sysctl vm.swappiness=10
echo 'vm.swappiness=10' > /etc/sysctl.d/99-swap.conf
How big?
- 1–2 GB RAM: a swap file the same size as RAM.
- 4 GB and up: 2 GB is usually enough as a buffer.
When swap isn't the answer
Swap lives on disk, which is far slower than RAM. If free -h shows swap constantly in use and the server feels sluggish, you don't need more swap — you need a bigger plan.
Typical signs:
- builds or package installs that crawl
- a database that slows down as the day goes on
- Out of memory: Killed process in the logs (check with dmesg -T | grep -i kill)
Rule of thumb
Swap is great for rare spikes — a one-off build, a nightly job. For a steady workload that needs more memory, move from Atom to Spark or from Spark to Core.
Deploy a server and give it a safety net from the start.