The Ultimate Guide to Linux Swap Memory
1. What is Swap Memory?
Swap memory is a technique that uses a portion of the hard drive (HDD/SSD) as if it were physical RAM when the actual RAM is full.
Here is a simple analogy:
- RAM: Your Desk (Very fast access, but limited workspace).
- HDD/SSD: The Bookshelf (Slow access, but huge storage).
- Swap: A Side Table used to temporarily hold books when your main desk is completely full.
2. Why is it Necessary?
Although RAM has become cheaper, Swap is still essential for server environments.
① OOM (Out Of Memory) Prevention (Most Important)
When RAM reaches 100% usage, the Linux kernel triggers the OOM Killer to terminate memory-intensive processes to keep the system alive.
- Without Swap: Web servers or databases may crash immediately without warning during traffic spikes.
- With Swap: The system may slow down, but it will stay alive, giving administrators time to react.
② Memory Efficiency
The OS moves inactive data (e.g., daemons used only during boot) to the swap area (Swap-out). This frees up high-speed physical RAM for active processes or file caching, improving overall performance.
3. How It Works
- Swap Out: Moves data that hasn't been used for a long time from RAM to the disk (Swap area).
- Swap In: Retrieves data from the swap area back to RAM when it is needed again.
Warning: Disk speeds are significantly slower than RAM. If the system relies too heavily on swap, it can cause "Thrashing", where the system becomes unresponsive due to constant data transfer.
4. Recommended Swap Size
In the past, the rule of thumb was "2x RAM," but for modern systems, the recommendations have changed.
| Physical RAM | Recommended Swap | Note |
|---|---|---|
| Less than 2GB | 2x RAM | For environments with critically low memory. |
| 2GB ~ 8GB | Equal to RAM | Standard web server setting. |
| 8GB ~ 64GB | 4GB ~ 8GB | Minimal safety net. |
| Over 64GB | 4GB+ | More may be needed if using Hibernation. |
5. Command Cheat Sheet
Check Status
# Display memory and swap usage in a human-readable format
free -h
# Show swap file/partition details
swapon --show