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?
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
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) |
Frequently Asked Questions
What will I learn here?
This page covers the core concepts and techniques you need to understand the topic and progress confidently to the next lesson.
How should I use this page?
Start with the overview, then follow the section links to deepen your understanding. Use the table of contents on the right to jump to specific sections.
What should I read next?
Use the navigation below to continue to the next lesson or explore related topics.