How Swap Works
Swap gets a bad reputation — "my system is swapping, it's slow." But swap is a nuanced tool. Understanding when Linux uses it, why it makes certain choices, and how to tune it can turn a crashing server into a stable one.
What is Swap?
What is swap space?
Swap is disk space that Linux can use as overflow memory. When physical RAM fills up, the kernel moves less-recently-used memory pages to the swap partition or swap file. This frees RAM for active processes. Later, if that swapped-out page is needed again, the kernel reads it back from disk.
# Check swap usage
free -h
# total used free shared buff/cache available
# Mem: 32G 12G 8G 500M 12G 19G
# Swap: 8G 512M 7G
# See swap details
cat /proc/swaps
# /dev/sda2 partition 8388604 524288 -2
# Create a swap file (if you don't have a partition)
sudo fallocate -l 4G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
Which Pages Get Swapped — LRU
The kernel doesn't randomly choose pages to swap. It uses an LRU (Least Recently Used) algorithm: pages that haven't been accessed recently are candidates for eviction. Linux maintains two lists per memory zone:
- Active list: Recently accessed pages — stay in RAM
- Inactive list: Not recently accessed — candidates for swap or reclaim
Pages move from active → inactive when not accessed for a while. Inactive file-backed pages (from /tmp, logs) are dropped (re-read from disk if needed). Inactive anonymous pages (heap, stack) go to swap.
Swappiness — Tuning the Aggressiveness
What is vm.swappiness?
A kernel tunable (0-200, default 60) that controls how aggressively Linux swaps anonymous pages vs evicting file cache. Lower value = prefer to keep pages in RAM, only swap when necessary. Higher value = swap more aggressively, keep file cache.
# Check current swappiness
cat /proc/sys/vm/swappiness # typically 60
# Desktop: reduce swappiness (prioritize responsiveness)
sudo sysctl vm.swappiness=10
# Server with plenty of RAM: reduce further
sudo sysctl vm.swappiness=1
# Persistent:
echo "vm.swappiness=10" | sudo tee -a /etc/sysctl.conf
zswap and zram — Compressed Memory
Modern alternatives that avoid slow disk I/O:
| Feature | zswap | zram |
|---|---|---|
| What it is | Compressed swap cache in RAM | Compressed block device in RAM as swap |
| How it helps | Compresses pages before writing to disk swap. Fewer disk writes. | Swap to RAM (compressed) instead of disk. Much faster. |
| Typical compression | 2-3x | 2-4x |
| Best for | Systems with slow disk swap | Systems with no swap, low RAM (RPi, laptops) |
# Enable zram (creates a compressed RAM swap device)
sudo modprobe zram
echo lz4 > /sys/block/zram0/comp_algorithm
echo 4G > /sys/block/zram0/disksize
sudo mkswap /dev/zram0
sudo swapon -p 100 /dev/zram0 # -p 100 = higher priority than disk swap