Linux Swap Management — Swap Files, Partitions & Tuning Guide
In this tutorial, you'll learn about Linux Swap Management. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
Swap is disk space used as an overflow for RAM — when physical memory fills up, the kernel moves inactive pages to swap, freeing RAM for active processes and preventing out-of-memory crashes.
What You'll Learn
How to create and remove swap files and partitions, tune swappiness and cache pressure, use zswap and zram for compressed in-memory swap, monitor swap usage, and configure swap for different workload types.
Why Swap Matters
A server without swap is one memory spike away from an OOM kill. Swap provides a safety net: the kernel can page out cold memory to disk, keeping the system responsive under pressure. Properly configured swap also enables hibernation (suspend-to-disk). Durga Antivirus Pro's scan servers use zram-backed swap to absorb memory spikes during signature updates without thrashing SSDs.
Learning Path
flowchart LR A[Filesystems Compared] --> B[Swap Management
You are here] B --> C[Performance Tuning] B --> D[System Rescue] style B fill:#f90,color:#fff
Swap Files vs Swap Partitions
| Feature | Swap File | Swap Partition |
|---|---|---|
| Resizing | Easy — grow/shrink at any time | Requires partition resize tools |
| Performance | Slightly slower (filesystem overhead) | Direct block device access |
| Flexibility | Create on any filesystem | Requires free partition space |
| Hibernation | Supported on most distros | Required for traditional suspend-to-disk |
| Snapshot-friendly | Yes (file inside snapshot) | Can complicate snapshots |
Modern Linux supports both equally well. Swap files are preferred for flexibility.
Creating a Swap File
# Create a 4GB swap file
sudo dd if=/dev/zero of=/swapfile bs=1M count=4096 status=progress
# Set correct permissions (must be 600)
sudo chmod 600 /swapfile
# Format as swap
sudo mkswap /swapfile
# Enable it
sudo swapon /swapfile
# Make permanent
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
Expected output:
$ sudo swapon --show
NAME TYPE SIZE USED PRIO
/swapfile file 4G 0B -2
Creating a Swap Partition
# Create a swap partition (using parted as example)
sudo parted /dev/sdb mklabel gpt
sudo parted /dev/sdb mkpart primary linux-swap 1MiB 100%
# Format as swap
sudo mkswap /dev/sdb1
# Get UUID
sudo blkid /dev/sdb1
# Enable
sudo swapon /dev/sdb1
# Make permanent (using UUID)
echo 'UUID=abc123-... none swap sw 0 0' | sudo tee -a /etc/fstab
Managing Multiple Swap Areas
You can have multiple swap areas with different priorities. The kernel uses higher-priority swap first:
# Add swap with priority
sudo swapon -p 10 /swapfile # Higher priority (used first)
sudo swapon -p 5 /dev/sdb1 # Lower priority (used when higher fills)
# Check priority and usage
swapon --show
# Remove a swap area
sudo swapoff /swapfile
sudo swapoff /dev/sdb1
Expected output:
$ swapon --show
NAME TYPE SIZE USED PRIO
/swapfile file 4G 1.2G 10
/dev/sdb1 partition 8G 0.5G 5
Swap Monitoring
# Overall swap usage
free -h
# Per-process swap usage
for file in /proc/*/status; do
awk '/VmSwap|Name/{printf $2 " " $3}END{ print ""}' $file 2>/dev/null
done | sort -k2 -n -r | head -10
# Using smem
sudo smem -t -s swap
# Check swap activity with vmstat
vmstat 1 10
# With sar
sar -S 1 3
Expected free output:
$ free -h
total used free shared buff/cache available
Mem: 15G 12G 891M 245M 2.0G 2.3G
Swap: 11G 1.7G 9.3G
Swappiness Tuning
Swappiness (0–100) controls how aggressively the kernel swaps. Lower values keep data in RAM longer.
# Check current swappiness
cat /proc/sys/vm/swappiness
# Default: 60
# Set swappiness temporarily
sudo sysctl vm.swappiness=10
# Set permanently
echo 'vm.swappiness=10' | sudo tee /etc/sysctl.d/99-swap.conf
Swappiness Recommendations
| Workload | Swappiness | Rationale |
|---|---|---|
| Desktops | 10–20 | Faster app switching, willing to use swap for file cache |
| Database servers | 1–10 | Keep database memory in RAM, avoid swap at all costs |
| Web servers | 10–30 | Balance between RAM for app and cache |
| Containers | 10–20 | Avoid swapping container processes |
| Batch processing | 60+ | Accept swap to leave RAM for file cache |
VFS Cache Pressure
# Default: 100
cat /proc/sys/vm/vfs_cache_pressure
# Reduce cache reclaim frequency
sudo sysctl vm.vfs_cache_pressure=50
# Make permanent
echo 'vm.vfs_cache_pressure=50' | sudo tee -a /etc/sysctl.d/99-swap.conf
Lower values (50) keep dentry and inode caches longer at the expense of other memory uses. Higher values (200) reclaim cache more aggressively.
zswap — Compressed In-Memory Swap
zswap intercepts pages being swapped out, compresses them, and stores them in a RAM pool. If the pool fills, pages are written to disk swap.
# Enable zswap (at boot)
echo 'zswap.enabled=1 zswap.compressor=zstd zswap.max_pool_percent=20' | \
sudo tee /etc/default/grub.d/zswap.cfg
# Update grub and reboot
sudo update-grub
sudo reboot
# Check zswap stats
cat /sys/kernel/debug/zswap/
zram — Compressed RAM Block Device
zram creates a compressed block device in RAM that acts as swap entirely in memory — no disk involved. Ideal for systems with limited RAM (VMs, Raspberry Pi).
# Install
sudo apt install zram-tools
# Configure
echo 'ALGO=zstd' | sudo tee -a /etc/default/zramswap
echo 'PERCENT=50' | sudo tee -a /etc/default/zramswap
# Enable
sudo systemctl enable --now zramswap
# Check
zramctl
Expected output:
$ zramctl
NAME ALGORITHM DISKSIZE DATA COMPR TOTAL STREAMS MOUNTPOINT
/dev/zram0 zstd 7.5G 2.3G 987M 1001M 4 [SWAP]
The compression ratio here is 2.3G of data compressed to ~1001M — nearly 2.3x savings.
Swap and Hibernation
Hibernation (suspend-to-disk) saves RAM contents to swap. The swap area must be large enough to hold all of RAM.
# Check if the system can hibernate
sudo systemctl hibernate
# Configure resume kernel parameter
sudo sed -i 's/GRUB_CMDLINE_LINUX="/GRUB_CMDLINE_LINUX="resume=UUID=SWAP_UUID/' /etc/default/grub
sudo update-grub
# Resume offset for swap files (not partitions)
sudo btrfs inspect-internal map-swapfile -r /swapfile # If on Btrfs
Common Errors
1. swapon Failed: "Invalid argument"
The swap file has wrong permissions or is on a filesystem that does not support swap (e.g., Btrfs without specific configuration). Fix: sudo chmod 600 /swapfile and ensure the filesystem supports swap files.
2. Out of Memory (OOM) With Swap Available
The OOM killer activates when memory pressure is extreme. Swap may exist but the system is thrashing — spending all CPU swapping pages in and out. Add more RAM or reduce workload.
3. Swap File on Btrfs
Btrfs supports swap files only with specific limitations: no compression, no copy-on-write, and no snapshots on the file. Create the file with chattr +C beforehand to disable CoW.
4. Swappiness=0 Does Not Disable Swap
Swappiness=0 means the kernel avoids swapping unless memory pressure is extreme. It does not disable swap entirely. To truly disable swap, remove or turn off all swap areas.
5. SSD Wear From Excessive Swapping
Frequent swapping wears SSDs. Mitigate with: (1) increase RAM, (2) use zswap/zram to keep swapped pages compressed in RAM, (3) set swappiness to 1 on SSD-only systems.
6. Hibernation Fails Because Swap Is Too Small
The swap area must be at least as large as the total installed RAM. Use a dedicated swap partition for hibernation instead of a swap file.
7. High Swap Usage Despite Available RAM
This usually indicates misconfigured swappiness or an application leaking memory. Use smem to find the culprit Process. Check vmstat 1 for si (swap in) and so (swap out) columns.
Practice Questions
1. What is the difference between swap and zram? Swap writes pages to disk. zram compresses pages in RAM and uses them as swap — no disk I/O. zram is faster but uses RAM for compressed storage.
2. What swappiness value is recommended for database servers? 1–10. Databases benefit from keeping their working set in RAM and avoiding swap latency.
3. How do you check which processes are using swap?
Read /proc/*/status and grep for VmSwap, or use sudo smem -t -s swap.
4. What is the advantage of a swap file over a swap partition? Swap files can be created, resized, and removed without repartitioning. They work on most modern filesystems and support snapshots of the containing volume.
5. How does zswap differ from zram? zswap intercepts swapped pages, compresses them, and stores them in a RAM cache. If the cache fills, pages spill to disk swap. zram creates a compressed RAM block device used directly as swap, never touching disk.
Challenge: Set up a system with 2GB of zram swap (priority 100), an 8GB swap file on SSD (priority 50), and a 4GB swap partition on HDD (priority 10). Generate memory pressure with stress --vm 4 --vm-bytes 10G --timeout 60. Monitor swap-in/swap-out rates with vmstat 1, compression ratios with zramctl, and verify the priority order. Then tune swappiness to minimize SSD writes.
What's Next
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. Updated 2026-06-24.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro