Complete Guide to Linux Swap Space Management
You don’t add swap to make a slow machine fast. You add it so a busy machine doesn’t faceplant. Swap is disk space the kernel can borrow when RAM is tight. It’s far slower than memory, but it’s better than the OOM killer taking down your app in the middle of a deploy.
If you want answers fast, start with the decision tree below. If you’d rather understand what’s going on under the hood—and make choices you won’t regret—read on.
Rule of thumb: Start with a 4 GB swap file, set
vm.swappiness=10, watch it for a week, and adjust.
Quick Decision Tree
Hibernation? On Btrfs? Database box? Make the call in under a minute:
Do you need hibernation?
├─ YES → Size swap ≥ RAM.
│ Swap file? add resume_offset.
│ Swap partition? add resume=UUID.
│
├─ On Btrfs/XFS (reflink)?
│ → Create a nocow, non-sparse file with dd (see Btrfs notes).
│
├─ Database server?
│ → 2–4 GB swap, swappiness=1, alert if swap is touched.
│
├─ Container host?
│ → 4–8 GB swap, swappiness=5–10, consider cgroup swap limits.
│
├─ < 4 GB RAM?
│ → Prefer zram to protect storage and reduce thrash.
│
└─ Everyone else
→ 4 GB swap file on SSD/NVMe, swappiness=10.
Takeaway: Most people want the last line. If you’re not sure, that’s your answer.
Understanding Swap (what it is, why you care)
When memory pressure rises, the kernel looks for pages that haven’t been touched lately and pushes them out to disk. That frees RAM for the things you’re actively doing. When those swapped-out pages are needed again, the kernel faults them back in. It works—until you’re swapping constantly. Then the machine spends more time shuttling pages than doing work. That’s thrashing, and it’s why your terminal types like molasses.
Think in orders of magnitude: RAM is measured in nanoseconds; SSD swap lives in microseconds to milliseconds; HDD swap drifts into multiple milliseconds. That gap is the difference between “fine” and “time to file a support ticket.”
Sanity check right now:
free -h # Quick overview
swapon --show # What swap is active
vmstat 1 # Watch si/so: swap-in/swap-out rates
Watch those si and so columns in vmstat. If they’re bouncing around above 1000 KB/s consistently, you’re thrashing. If they’re near zero, you’re fine.
Takeaway: Swap is a seatbelt, not a turbocharger. It keeps you alive under stress; it doesn’t make you faster.
Official docs: Linux Memory Management
Swap Files vs Swap Partitions
On modern Linux, a swap file is the right answer most of the time. It lives on your filesystem, you can grow or shrink it without touching partitions, and performance is effectively identical on ext4 and XFS-noreflink. The only time a swap partition still earns its keep is when you know your requirements upfront (fresh installs, long-lived servers), or you’re on filesystems that complicate swap files (Btrfs, XFS with reflink).
Hibernation works with both, but a swap file needs one extra setting: the resume_offset. We’ll cover that later.
If you’re on Btrfs, you’ll need to disable CoW and compression for the file and create it with dd so it isn’t sparse. On newer XFS with reflink enabled, either mount without reflink for the swap file, place it on an ext4 slice, or use a partition instead. These filesystems are picky about how data is laid out, and swap needs contiguous, predictable blocks.
What I recommend: Default to a swap file on SSD or NVMe. Only deviate if your filesystem argues with you or you already know you want a fixed partition.
Create a safe swap file on ext4/XFS-noreflink (most people):
sudo dd if=/dev/zero of=/swapfile bs=1M count=4096 status=progress
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
That’s 4 GB. Adjust the count= value to change size. The chmod 600 is critical—swap can contain passwords and keys, so lock it down to root-only.
Takeaway: Use a file unless your filesystem argues with you—or you already know you want a fixed partition.
How Much Swap Do You Need?
The old “2× RAM” rule came from the 256 MB era. Today, size for your failure mode, not for superstition.
Here’s the pragmatic breakdown: Desktops and laptops usually do fine with 4 GB if you don’t hibernate. If you do hibernate, you need swap at least as large as your RAM. Databases need tiny swap (2–4 GB) as an escape hatch, with vm.swappiness=1 to make sure they almost never use it. General servers? 4–8 GB is usually enough to ride out memory bursts. If you’re on a device with limited RAM or flash storage (embedded systems, SD cards), prefer zram to save the flash from wear.
Quick sizing table:
| RAM | No Hibernation | With Hibernation |
|---|---|---|
| 2 GB | 2 GB | 4 GB |
| 4 GB | 2 GB | 6 GB |
| 8 GB | 2–4 GB | 10 GB |
| 16 GB | 2–4 GB | 18 GB |
| 32 GB | 2–4 GB | 34 GB |
| 64 GB+ | 4 GB | RAM + 2 GB |
Reality check your choice
# Run your normal workload for a few days, then:
free -h
sar -S # historical swap usage (needs sysstat package)
If ‘used’ never budges, you can dial swap down. If it climbs and stays high, tune swappiness or add RAM.
Takeaway: Size for safety, then verify with real usage. You can always adjust.
Creating Swap Space
Here’s where the rubber meets the road. You’ve got three main paths: swap files (easiest), swap partitions (traditional), or LVM volumes (flexible). We’ll focus on files first since that’s what most people want.
The Standard Way: Swap Files
Pick a fast disk with free space. Ideally NVMe or SSD, definitely not a network mount. Your root filesystem is usually fine. Here’s the process.
Step 1: Check your filesystem
df -Th # What filesystem type?
df -h # Enough free space?
If you see btrfs or xfs, you’ll need special handling (covered below). For ext4, you’re golden with the standard approach.
Step 2: Create the file
Use dd for maximum compatibility. It’s slower than fallocate but works everywhere and guarantees contiguous blocks (important for hibernation).
# 4 GB swap file
sudo dd if=/dev/zero of=/swapfile bs=1M count=4096 status=progress
# 8 GB swap file
sudo dd if=/dev/zero of=/swapfile bs=1M count=8192 status=progress
# 2 GB swap file
sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress
The status=progress flag shows you it’s working. Grab coffee—this takes a minute.
Step 3: Lock down permissions
This is critical. Swap can contain anything that was in RAM: passwords, keys, personal data. You want root-only access.
sudo chmod 600 /swapfile
sudo chown root:root /swapfile
# Verify it worked
ls -l /swapfile
# Should show: -rw------- 1 root root
If you skip this, mkswap will yell at you (and rightly so).
Step 4: Format and enable
sudo mkswap /swapfile
sudo swapon /swapfile
You should see: Setting up swapspace version 1, size = X GiB. That’s your confirmation.
Step 5: Verify it’s working
swapon --show
free -h
You should see your swap file listed and the total swap increased.
Step 6: Make it permanent
Right now your swap will vanish on reboot. Fix that:
# Backup fstab first (good hygiene)
sudo cp /etc/fstab /etc/fstab.backup
# Add swap to fstab
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
# Verify the entry
tail -1 /etc/fstab
Reboot and check swapon --show again to confirm it persists.
Takeaway: Six steps, five minutes, done. This works for most systems running ext4 or XFS without reflink.
Special Case: Btrfs (Needs CoW Disabled)
Btrfs is copy-on-write by default, and swap hates that. You need to create a directory with CoW disabled, turn off compression, and use dd to avoid sparse files.
# Create dedicated directory for swap
sudo mkdir -p /swap.d
sudo chattr +C /swap.d # Disable CoW BEFORE creating file
sudo btrfs property set /swap.d compression none
# Create the swap file
sudo dd if=/dev/zero of=/swap.d/swapfile bs=1G count=4 status=progress
# Permissions
sudo chmod 600 /swap.d/swapfile
# Format and enable
sudo mkswap /swap.d/swapfile
sudo swapon /swap.d/swapfile
# Make permanent
echo '/swap.d/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
If you try the standard method on Btrfs without these steps, you’ll get swapon: swapfile has holes errors. The kernel won’t use it.
Official Btrfs docs: Btrfs Swap File Support
Gotcha: On Btrfs, CoW must be disabled before you create the file. Can’t fix it after the fact.
Special Case: XFS with Reflink
Newer XFS defaults to reflink (like Btrfs’s CoW). Swap files don’t work on reflinked filesystems without extra steps.
Your options:
- Mount XFS without reflink (add
noreflinkto fstab mount options) - Create swap on a different filesystem (like a small ext4 partition)
- Use a swap partition instead
I recommend option 3 (partition) if you’re on XFS with reflink and need hibernation. Otherwise option 1 or 2 work fine.
Alternative: Swap Partitions
Sometimes you want a partition. Fresh install with known requirements? Long-lived server with fixed specs? This is your path.
During installation: Most installers (Ubuntu, Fedora, Debian) create swap partitions automatically. You can customize the size during partitioning.
Post-installation: You’ll need to either shrink an existing partition to make space, or have unallocated space ready. This is destructive, so back up first.
Using fdisk (quick example):
sudo fdisk /dev/sda
# Inside fdisk:
n # New partition
p # Primary
[Enter] # Accept defaults for partition number and start
+4G # Make it 4 GB
t # Change type
[number] # Your new partition number
82 # Linux swap
w # Write and exit
Format and enable:
# Replace /dev/sda3 with your actual partition
sudo mkswap /dev/sda3
sudo swapon /dev/sda3
# Get the UUID (better than device names)
sudo blkid /dev/sda3
# Add to fstab with UUID
UUID=xxxx-xxxx-xxxx none swap sw 0 0
UUIDs are better than device names because device names can change if you add or remove disks. UUIDs are permanent.
Takeaway: Partitions are fixed size but slightly cleaner. Use them if you know your requirements won’t change.
LVM Option (For the Enterprise Crowd)
LVM logical volumes give you the best of both worlds: partition-like cleanliness with file-like resizing.
# Create a 4 GB logical volume
sudo lvcreate -L 4G -n swap_lv vg_name
# Format and enable
sudo mkswap /dev/vg_name/swap_lv
sudo swapon /dev/vg_name/swap_lv
# Add to fstab
/dev/vg_name/swap_lv none swap sw 0 0
Resize later:
sudo swapoff /dev/vg_name/swap_lv
sudo lvextend -L +2G /dev/vg_name/swap_lv
sudo mkswap /dev/vg_name/swap_lv
sudo swapon /dev/vg_name/swap_lv
This is overkill for most desktops but perfect for servers where requirements evolve.
Hibernation Setup (Resume from Swap)
Hibernation writes your RAM to swap and powers off. On boot, the kernel reads that RAM back and resumes where you left off. For this to work, you need swap at least as large as your RAM, and you need to tell the kernel where to find it.
For swap partitions: Add resume=UUID to your kernel command line.
For swap files: Add both resume=UUID and resume_offset (the physical location of the file on disk).
Automated setup for swap files:
# Get the device UUID
SWAPDEV=$(findmnt -no SOURCE -T /swapfile)
UUID=$(blkid -s UUID -o value "$SWAPDEV")
# Get the physical offset
OFFSET=$(sudo filefrag -v /swapfile | awk '$1=="0:"{print $4}' | sed 's/\.\.//;s/:$//')
# Update GRUB config
sudo sed -i "s/^GRUB_CMDLINE_LINUX_DEFAULT=.*/GRUB_CMDLINE_LINUX_DEFAULT=\"quiet splash resume=UUID=$UUID resume_offset=$OFFSET\"/" /etc/default/grub
# Apply changes
sudo update-grub
sudo update-initramfs -u
After rebooting, test hibernation with systemctl hibernate. If it works, your system powers off and resumes with all your apps intact.
Official docs: Suspend and Hibernation
Gotcha: Forget the resume_offset with a swap file and hibernation will fail silently. The kernel needs that offset to find your saved RAM state.
Managing Existing Swap
Sometimes you need to resize, add, or remove swap. Here’s how.
Check What You Have
free -h # Quick overview
swapon --show # Detailed swap info
cat /proc/swaps # Same info, different format
Add More Swap (Multiple Swap Spaces)
You can have multiple swap areas running simultaneously. The kernel uses them based on priority.
# Create a second swap file
sudo dd if=/dev/zero of=/swapfile2 bs=1M count=2048 status=progress
sudo chmod 600 /swapfile2
sudo mkswap /swapfile2
sudo swapon /swapfile2
# Make it permanent
echo '/swapfile2 none swap sw 0 0' | sudo tee -a /etc/fstab
Priority system: Higher priority = used first. Set priorities in fstab:
/swap_fast none swap sw,pri=10 0 0 # Fast NVMe, used first
/swap_slow none swap sw,pri=5 0 0 # Slower disk, emergency
Same priority means the kernel stripes across them for better throughput.
Resize Swap
For files: Disable, delete, recreate larger.
sudo swapoff /swapfile
sudo rm /swapfile
sudo dd if=/dev/zero of=/swapfile bs=1M count=8192 status=progress
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
For partitions: Requires booting from live media, resizing with GParted or parted, then reformatting.
For LVM: Easiest option (see LVM section above).
Remove Swap
sudo swapoff /swapfile
sudo rm /swapfile
# Remove from fstab
sudo nano /etc/fstab
# Delete the swap line
Temporarily Disable/Enable
sudo swapoff -a # Turn off all swap
sudo swapon -a # Turn on all swap from fstab
Useful for testing how your apps behave without swap, or forcing the system to reclaim memory.
Takeaway: Swap is not set in stone. Adjust it as your needs change.
Performance Tuning: Swappiness
Swappiness controls how eager the kernel is to swap. It’s a value from 0 to 100. Higher values mean “swap more aggressively to keep RAM free for cache.” Lower values mean “avoid swapping until you really have to.”
The default is 60, which works fine for desktops with plenty of RAM. For servers or systems where swapping is bad (databases), you want it much lower. Setting it to 1 is better than 0—there are edge cases where 0 behaves weirdly, and 1 still lets the kernel swap in emergencies without the quirks.
Check current swappiness:
cat /proc/sys/vm/swappiness
Change it temporarily (until reboot):
sudo sysctl vm.swappiness=10
Change it permanently:
echo "vm.swappiness=10" | sudo tee /etc/sysctl.d/99-swappiness.conf
sudo sysctl -p /etc/sysctl.d/99-swappiness.conf
What value should you use?
- Desktops: 60 (default) or 30-40 if you have modest RAM
- Servers: 10 (general purpose) or 1 (databases)
- Systems with fast NVMe: 20-30 (swap penalty is lower)
Official docs: sysctl/vm.txt
Rule of thumb: Database servers get swappiness=1. Everything else starts at 10 and adjusts based on monitoring.
Monitoring: Know When You’re Swapping
Healthy systems barely swap. If you’re swapping constantly, you either need more RAM or you need to fix a memory leak. Here’s how to tell the difference.
Real-time monitoring:
vmstat 1
Focus on the si and so columns (swap in / swap out). They show KB/s. Near zero is good. Occasional small values are fine. Sustained values over 1000 KB/s mean you’re thrashing.
Which processes are using swap:
# Quick and dirty
for dir in /proc/[0-9]*; do
pid=$(basename $dir)
name=$(cat $dir/status 2>/dev/null | grep "^Name:" | awk '{print $2}')
swap=$(cat $dir/status 2>/dev/null | grep "^VmSwap:" | awk '{print $2}')
if [ ! -z "$swap" ] && [ "$swap" -gt 0 ]; then
echo "$name (PID $pid): ${swap} kB"
fi
done | sort -t: -k2 -n -r | head -20
Better: Use smem (accounts for shared memory correctly):
sudo apt install smem
sudo smem -s swap -r # Sort by swap usage
# Handy alias to add to your .bashrc
alias topswap='sudo smem -rs swap | head -n 20'
Historical analysis:
sudo apt install sysstat
sudo systemctl enable --now sysstat
sar -S # Swap usage history
sar -W # Swap activity (paging)
Set up alerts (Prometheus example):
- alert: HighSwapUsage
expr: (1 - (node_memory_SwapFree_bytes / node_memory_SwapTotal_bytes)) > 0.8
for: 5m
- alert: SwapThrashing
expr: rate(node_vmstat_pswpin[1m]) > 1000 or rate(node_vmstat_pswpout[1m]) > 1000
for: 2m
Official Prometheus docs: Node Exporter
Takeaway: Watch vmstat. If si/so are quiet, you’re good. If they’re screaming, you’re in trouble.
Common Problems and Fixes
Problem: System Is Crawling (Thrashing)
Symptoms: Everything is slow, disk light is solid, vmstat shows high si/so values.
Diagnosis:
vmstat 1
# si/so columns > 1000 consistently = thrashing
top
# Press Shift+M to sort by memory
# Identify the memory hogs
Fixes:
- Kill the worst offenders (temporary relief)
- Reduce swappiness:
sudo sysctl vm.swappiness=10 - Add more RAM (permanent solution)
- Fix memory leaks in your apps
- Use zram if you can’t add RAM
Problem: OOM Killer Despite Available Swap
Symptoms: Processes getting killed even though free -h shows swap available.
Diagnosis:
swapon --show # Is swap actually enabled?
cat /proc/sys/vm/swappiness # Set too low?
dmesg | grep -i oom # Check OOM killer logs
Fixes:
# Enable swap if it's off
sudo swapon -a
# Increase swappiness if it's too low
sudo sysctl vm.swappiness=60
# Check fstab to ensure swap activates on boot
cat /etc/fstab | grep swap
Problem: Swap File Permission Errors
Symptoms: swapon fails with “permission denied” or security warnings.
Fix:
sudo chmod 600 /swapfile
sudo chown root:root /swapfile
sudo swapon /swapfile
Problem: Hibernation Doesn’t Work
Symptoms: System reboots instead of resuming from hibernation.
Diagnosis:
# Check swap size (must be ≥ RAM)
free -h
# Check resume parameters
cat /proc/cmdline | grep resume
# For swap files, check if resume_offset is set
cat /proc/cmdline | grep resume_offset
Fix: Follow the hibernation setup in the earlier section. Don’t forget the resume_offset for swap files.
Problem: “File Has Holes” Error
Symptoms: mkswap or swapon complains about holes in the swap file.
Cause: You used fallocate on Btrfs or XFS-reflink, or CoW is still enabled.
Fix:
# Delete and recreate with dd
sudo swapoff /swapfile
sudo rm /swapfile
sudo dd if=/dev/zero of=/swapfile bs=1M count=4096 status=progress
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
On Btrfs, also verify CoW is disabled (see Btrfs section).
Takeaway: Most problems are either thrashing (need more RAM) or configuration issues (permissions, fstab, resume params).
Advanced Topics
Zswap: Compressed Cache in RAM
Zswap sits between RAM and disk swap. When the kernel wants to swap something out, zswap compresses it first and keeps it in RAM. Only if that compressed cache fills up does it write to disk. This can double or triple your effective RAM for things that compress well.
Enable zswap at boot:
# Edit /etc/default/grub
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash zswap.enabled=1 zswap.compressor=lz4 zswap.zpool=z3fold"
sudo update-grub
sudo reboot
Most zswap parameters are read-only after boot, so set them via kernel command line.
Official docs: Zswap
Zram: Compressed Swap in RAM (No Disk)
Zram creates a compressed block device entirely in RAM. It’s perfect for systems where you want to avoid disk I/O completely (embedded systems, SD cards) or where you have limited RAM and want to squeeze more out of it.
Install and configure (Ubuntu/Debian):
sudo apt install zram-tools
# Edit /etc/default/zramswap
sudo nano /etc/default/zramswap
# Set:
ALGO=lz4
PERCENT=25 # Use 25% of RAM for zram
sudo systemctl restart zramswap
Verify it’s working:
zramctl
swapon --show
Official docs: Zram
Use case: Zram is brilliant for Raspberry Pis, embedded devices, and containers where disk swap would be too slow.
Encrypted Swap
Swap can contain passwords, keys, and personal data. If you’re on a laptop or handling sensitive data, encrypt it.
Simple approach (random key per boot):
# Add to /etc/crypttab
cryptswap /dev/sda3 /dev/urandom swap,cipher=aes-xts-plain64,size=256
# Add to /etc/fstab
/dev/mapper/cryptswap none swap sw 0 0
Data doesn’t persist across reboots (new random key each time), but that’s usually fine for swap.
Official docs: dm-crypt
Cgroup v2 Memory Limits
Modern systems use cgroup v2 to limit memory and swap per process or container.
Limit memory and swap for a cgroup:
echo "2G" > /sys/fs/cgroup/myapp/memory.max
echo "1G" > /sys/fs/cgroup/myapp/memory.swap.max
Docker:
# Total memory (RAM + swap) = 3GB
docker run -it --memory 2g --memory-swap 3g ubuntu
# No swap (memory-swap = memory)
docker run -it --memory 2g --memory-swap 2g ubuntu
Kubernetes: Recent versions (1.22+) support swap with failSwapOn: false in kubelet config, but it’s still generally discouraged for production clusters.
Official docs:
Swap Priority and Striping
When you have multiple swap areas, priority determines order of use. Same priority means the kernel stripes across them (parallel I/O).
# In /etc/fstab
/swap_nvme none swap sw,pri=10 0 0 # Fast, used first
/swap_ssd none swap sw,pri=10 0 0 # Same priority = striped
/swap_hdd none swap sw,pri=1 0 0 # Slow, emergency only
This lets you layer fast and slow storage intelligently.
Best Practices by Use Case
Desktop/Laptop (The Default Case)
RAM: 8-16 GB
Swap: 4 GB file on SSD
Swappiness: 10-20
Hibernation: If yes, swap = RAM + 2GB
Desktops can tolerate occasional swapping. 4 GB is usually enough. If you hibernate, size swap to fit your RAM.
Database Server (PostgreSQL, MySQL, Redis)
RAM: 64 GB+
Swap: 2-4 GB file
Swappiness: 1 (not 0!)
Page-cluster: 0
Critical config:
sudo sysctl vm.swappiness=1
sudo sysctl vm.page-cluster=0
# Disable transparent huge pages
echo never | sudo tee /sys/kernel/mm/transparent_hugepage/enabled
echo never | sudo tee /sys/kernel/mm/transparent_hugepage/defrag
Database servers should almost never swap. If they do, performance tanks. Monitor closely and alert if swap is touched.
Official DB docs: PostgreSQL Resource Consumption | MySQL Performance
Web/Application Server
RAM: 16-32 GB
Swap: 4-8 GB
Swappiness: 10
Web servers can handle light swapping, but you want to avoid it under load. Tune your app servers (PHP-FPM, Node, etc.) to limit memory per process.
Container Host (Docker/Kubernetes)
RAM: 32-128 GB
Swap: 4-8 GB (host only)
Swappiness: 5-10
Let containers manage their own memory limits. The host swap is for system processes, not containers. Most production k8s clusters disable swap entirely.
Official docs: Docker Resource Constraints
Development Workstation
RAM: 16 GB
Swap: 4 GB
Swappiness: 10
Location: NVMe
IDEs and build tools are memory hungry. A bit of swap on fast storage saves you from OOM kills during big compiles.
Quick Reference
Create Standard Swap File (Copy-Paste)
sudo dd if=/dev/zero of=/swapfile bs=1M count=4096 status=progress
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
Create Btrfs-Safe Swap File
sudo mkdir -p /swap.d && sudo chattr +C /swap.d
sudo btrfs property set /swap.d compression none
sudo dd if=/dev/zero of=/swap.d/swapfile bs=1G count=4 status=progress
sudo chmod 600 /swap.d/swapfile
sudo mkswap /swap.d/swapfile && sudo swapon /swap.d/swapfile
echo '/swap.d/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
Set Up Hibernation (Swap File)
SWAPDEV=$(findmnt -no SOURCE -T /swapfile)
UUID=$(blkid -s UUID -o value "$SWAPDEV")
OFFSET=$(sudo filefrag -v /swapfile | awk '$1=="0:"{print $4}' | sed 's/\.\.//;s/:$//')
sudo sed -i "s/^GRUB_CMDLINE_LINUX_DEFAULT=.*/GRUB_CMDLINE_LINUX_DEFAULT=\"quiet splash resume=UUID=$UUID resume_offset=$OFFSET\"/" /etc/default/grub
sudo update-grub && sudo update-initramfs -u
Install Zram (Ubuntu/Debian)
sudo apt install zram-tools
sudo sed -i 's/^#*ALGO=.*/ALGO=lz4/' /etc/default/zramswap
sudo sed -i 's/^#*PERCENT=.*/PERCENT=25/' /etc/default/zramswap
sudo systemctl restart zramswap
Essential Monitoring Commands
free -h # Quick overview
swapon --show # What's active
vmstat 1 # Real-time swap activity (watch si/so)
sudo smem -s swap -r # Which processes are swapped
sar -S # Historical swap usage
Troubleshooting Checklist
1. Is swap enabled? → swapon --show
2. Is it being used? → free -h
3. Swappiness too low? → cat /proc/sys/vm/swappiness
4. Thrashing? → vmstat 1 (check si/so columns)
5. What's using it? → sudo smem -s swap -r
6. Disk healthy? → sudo smartctl -a /dev/sda
7. Permissions correct? → ls -l /swapfile (should be 600)
8. Fstab entry correct? → cat /etc/fstab | grep swap
Official Documentation
Core Linux Docs
Filesystems
Distributions
Containers & Databases
Security
Monitoring
Wrapping Up
Swap isn’t sexy, but it’s essential. Done right, it’s invisible—your system handles memory pressure gracefully, apps don’t crash, and you never think about it. Done wrong, you get thrashing, OOM kills, and late-night pages.
Start simple: 4 GB swap file, swappiness=10, monitor with vmstat. Adjust based on what you see. If you’re never swapping, you can dial it down. If you’re thrashing, add RAM or fix memory leaks. If you’re on a database server, set swappiness=1 and alert if swap is ever touched.
And remember: swap is a seatbelt, not a turbocharger.
For more details, check the official kernel docs at kernel.org/doc.