"You have plenty of RAM, you do not need swap" is common advice and sounds reasonable. In practice it trades a slowdown for a killed process.
What happens without swap
When memory runs out the kernel does not slow down — it invokes the OOM killer, which picks a victim by heuristic and terminates it with KILL. The victim is usually the largest process, which is to say your database.
With swap the system has room to manoeuvre: rarely used pages move to disk and the application keeps running, slower. Slow is a state you notice and fix. A killed process is downtime.
How much
For an 8 GB server, 2–4 GB is sensible. The goal is not to double your memory but to give the kernel somewhere to go.
fallocate -l 4G /swapfile
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile
To bring it back after a reboot, add a line to /etc/fstab:
/swapfile none swap sw 0 0
Tune swappiness
The default of 60 pages out far too eagerly on an NVMe server. 10 is a better fit:
sysctl vm.swappiness=10
That means "use swap only when it is genuinely needed" — exactly the behaviour you want.
