GICT knowledge base
Understanding Swap Memory and When Linux Uses It
Published
Swap memory has confused Linux administrators for decades. Some swear by it, others disable it on every server they touch, and most people fall somewhere in the middle without really knowing why their system uses it the way it does. The truth is that swap is one of those topics where the conventional wisdom is half right and half outdated.
In this article, you will learn what swap actually does, why Linux sometimes swaps even when you have free RAM, how the swappiness value changes kernel behavior, and how to add or remove swap on a live server. You will also see when swap helps and when it makes things worse.
Prerequisites
Before you start, make sure you have:
- A Linux machine running Ubuntu 22.04, Debian 12, or a similar distribution.
- A user account with sudo access.
- Basic comfort with the terminal.
- At least 1 GB of free disk space if you plan to create a swap file.
What Swap Memory Actually Is
Swap is just disk space that the kernel pretends is RAM. When physical memory gets tight, Linux picks pages of memory that have not been used in a while and writes them to the swap area on disk. Later, if a process needs that data again, the kernel reads it back. The whole thing happens behind the scenes, and most applications never know it happened.
The catch is speed. RAM responds in nanoseconds. Disk responds in milliseconds. Even on fast Non-Volatile Memory Express (NVMe) drives, you are looking at a slowdown of roughly a thousand times. So swap is not a substitute for buying more RAM. It is more like a parachute. You hope you never need it, but you want it there.
Here is the part that trips people up. A server with zero swap usage is not automatically healthy, and a server using some swap is not automatically struggling. Linux uses swap proactively, even when RAM looks fine. It does this to keep more space available for the page cache, which speeds up file reads. So a small amount of swap usage often means the kernel is doing its job, not failing at it.
Swap Partition vs Swap File
There are two ways to give Linux swap space, and the choice matters less than it used to.
A swap partition is a chunk of the disk dedicated to swap. You set it up during installation, and it sits there as a separate partition. Older guides recommended this approach because partitions skipped the filesystem layer and ran slightly faster.
A swap file is just a regular file on the filesystem that you tell the kernel to use as swap. You can create it whenever you want, resize it later, or delete it entirely without messing with the partition table.
On modern kernels and modern hardware, the speed gap between the two is so small that most people will never notice it. Swap files win on flexibility, especially on cloud servers and virtual machines where repartitioning a live disk is the kind of task you avoid doing on a Friday afternoon. Unless you have a specific reason to use a partition, go with a file.
When Linux Decides to Swap
The kernel does not wait until RAM is full to start swapping. That alone surprises a lot of people. The decision involves a few moving parts.
When applications need more memory, the kernel has to free some up. It looks at what is currently in RAM and asks which pages are least useful. Pages that have not been touched in a while are good candidates. If those pages came from a file, the kernel can just drop them and read the file again later. If those pages are anonymous memory, meaning they belong to a running program’s heap or stack and have no file backing, the only way to free them is to write them to swap.
The kernel also weighs swap against the page cache. If swapping out a few unused pages frees up RAM that can cache frequently read files, the system gets faster overall. This is the proactive swapping behavior that catches administrators off guard. They see swap usage on a server with plenty of free memory and assume something is broken. Usually nothing is broken. The kernel just made a tradeoff.
Understanding Swappiness
Swappiness is the knob that controls how eagerly the kernel reaches for swap. It accepts values from 0 to 200, and most distributions ship with a default of 60.
Despite what some tutorials claim, swappiness is not a percentage of RAM. It is a relative weight in the kernel’s page reclaim algorithm. Higher numbers mean the kernel is more willing to swap. Lower numbers mean it tries harder to keep things in RAM and only swaps when it really has to.
Check the current swappiness value.
cat /proc/sys/vm/swappiness
A fresh Ubuntu or Debian install will almost always show 60. That number is fine for desktops and general workloads. For database servers, it is usually too high.
Change the value temporarily for testing.
sudo sysctl vm.swappiness=10
The change takes effect right away but goes back to the default after reboot.
Make the change stick across reboots.
sudo nano /etc/sysctl.conf
Add this line at the bottom of the file.
vm.swappiness=10
Apply the new setting without rebooting.
sudo sysctl -p
For database servers running MySQL or PostgreSQL, a swappiness of 1 or 10 usually performs better. For typical web servers, somewhere between 10 and 30 is a reasonable starting point. Desktops can leave it at 60 without issue.
[!NOTE] Setting swappiness to 0 does not turn swap off. It just tells the kernel to avoid swap unless an out-of-memory situation is about to happen.
Checking Current Swap Usage
Before making changes, see what your system is actually doing.
Check overall memory and swap status.
free -h
The output shows both RAM and swap with totals, used, and free columns. If the swap used number is zero, your kernel has not had a reason to swap yet.
List all active swap devices and files.
swapon --show
This is handy when you want a quick view of what swap exists and how much of it is in use.
Find which processes are using the most swap.
for file in /proc/*/status ; do awk '/VmSwap|Name/{printf $2 " " $3}END{ print ""}' $file; done | sort -k 2 -n -r | head
The command sorts processes by swap usage and shows the top consumers. Useful when something has filled up swap and you need to know what.
How to Add a Swap File
Adding swap to a running server takes about two minutes. The example below creates a 2 GB swap file.
Create the empty file.
sudo fallocate -l 2G /swapfile
If fallocate is not available on your distribution, fall back to dd.
sudo dd if=/dev/zero of=/swapfile bs=1M count=2048
Lock down the permissions.
sudo chmod 600 /swapfile
Only root should be able to read this file. A world-readable swap file is a real security problem because swap can hold sensitive data that was in memory.
Format the file as swap.
sudo mkswap /swapfile
Turn it on.
sudo swapon /swapfile
Confirm it is active.
swapon --show
Make it persistent across reboots by adding an entry to /etc/fstab.
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
[!WARNING] Never put swap files on network filesystems like Network File System (NFS). The kernel cannot reliably swap to a network location, and trying it can hang the entire system.
When You Should Skip Swap
Swap is not always a good idea. There are real cases where it makes things worse.
Database servers with enough RAM to hold their working set should usually avoid heavy swap usage. Once a query touches swapped memory, response time goes from microseconds to milliseconds, and that delay ripples through every application connected to the database. Many database administrators set swappiness to 1 or just keep swap off entirely on dedicated database hosts.
Real-time applications and latency-sensitive services have similar concerns. A single page fault that triggers a disk read can blow past the response time the application is supposed to guarantee.
Kubernetes is another case. For years, Kubernetes required swap to be disabled on every node. Newer versions support swap under specific conditions, but the default expectation is still that nodes run without it. Check your cluster requirements before flipping the switch.
How Much Swap You Actually Need
The old “swap should be twice your RAM” rule comes from a time when servers had 256 MB of memory. It does not apply anymore. Here is something more useful:
- Systems with 1 to 2 GB of RAM: Match swap to RAM. The kernel needs the headroom for memory spikes.
- Systems with 4 to 8 GB of RAM: Allocate 2 to 4 GB of swap. More than that rarely helps.
- Systems with 16 GB or more of RAM: Stick with 2 to 4 GB, or skip swap entirely if your workload is memory-bound and you have proper monitoring.
- Systems that hibernate: Match swap to RAM, since hibernation dumps the entire memory contents to swap.
These are starting points, not absolutes. Run free -h and vmstat over a few weeks of normal load and adjust based on what you actually see.
Conclusion
You now know what swap memory does, why Linux sometimes swaps even when free RAM is available, how swappiness shapes that behavior, and how to add or remove swap on a live system. You have also seen which workloads benefit from swap and which ones run better without it.
Swap is useful, but it is not a fix for an undersized server. The right approach is to size the machine for the workload, treat swap as a safety net, and tune swappiness based on what the application actually does. Watch swap usage over time, and if you see consistent heavy swapping, take it as a signal. Either the server needs more RAM or something has gone wrong inside a process.
Related guides
Plan a Safe Redis-to-Valkey Migration
Plan a Redis-to-Valkey migration: check version compatibility, rehearse recovery, stop writers for cutover and protect against lost writes during rollback.
Linux AdministrationHow to Restrict an SSH Key to One Command
Restrict an SSH key to one command with authorized_keys options. Protect the command and check that unwanted shell and forwarding access are denied.
Linux AdministrationHow to Schedule Tasks with systemd Timers
Schedule tasks with systemd timers. Verify service results separately from timer status, test missed-run handling and use an explicit UTC schedule.
Linux AdministrationHow to Restrict a Linux Service with systemd Security Settings
Restrict a Linux service with systemd drop-ins, a dedicated account, read-only paths, private temporary storage, and controlled writable directories.
