Swap Management & Tuning
Swap partitions vs swapfiles, swappiness tuning, zswap, and why swap matters even with large RAM on modern Linux systems.
Overview
Swap is disk space used as an overflow for RAM. Linux uses swap not only when RAM is exhausted but also proactively to free RAM for file cache — controlled by the swappiness kernel parameter.
Types of Swap
- Swap partition — dedicated partition, kernel writes directly (slightly faster)
- Swap file — regular file on any filesystem (on ext4/XFS; btrfs has restrictions). Flexible, resizable without partition tools.
- zswap — a compressed in-RAM cache for swap pages. Compresses pages before writing to disk, reducing I/O. Transparent to applications.
Key Parameters
vm.swappiness (0-200, default 60)
- 60 (default) — kernel proactively reclaims anonymous pages to swap when under memory pressure
- 0 — avoid swap unless absolutely necessary (OOM risk increases)
- 1 — minimal swap, use mostly for OOM prevention
- 100 — swap anonymous memory as aggressively as page cache reclaim
- > 100 — cgroup v2 only: allows swapping anonymous pages before page cache reclaim
vm.vfs_cache_pressure (default 100)
Controls how aggressively the kernel reclaims dentry/inode cache vs anonymous memory. Higher = more aggressive inode cache reclaim (good for systems with millions of files).
Key concepts
- swappiness
- Sysctl parameter (vm.swappiness, 0-200). Controls the trade-off between swapping anonymous memory and reclaiming page cache. Default 60. Set to 1-10 for latency-sensitive workloads.
- Anonymous memory
- Process heap, stack, and mmap(MAP_ANONYMOUS) allocations — not backed by a file. Can only be saved to swap. Unlike file-backed pages, cannot be simply dropped from RAM.
- zswap
- In-kernel compressed cache for swap pages. Compresses pages in RAM before writing to disk. Reduces swap I/O at the cost of CPU. Dramatically reduces latency compared to raw disk swap.
- Swap priority
- Multiple swap devices can be active with different priorities. Higher priority swap is used first. Set with swapon -p . Use SSD swap at higher priority than HDD.
When to use it
- Explaining why swap is still needed on systems with large RAM (OOM prevention, memory overcommit)
- Tuning swappiness for database workloads where swap latency is unacceptable
- Designing a cloud VM disk layout that includes swap without a dedicated partition
Interview questions
- Why should you have swap enabled even on a server with 256GB of RAM, and how do you tune it to minimize latency impact?
Sign up free to read the full topic
More Linux topics
Start free on Cariara · Coding problems · System design studio