HiveBrain v1.2.0
Get Started
← Back to all entries
patternbashMajor

Swap Management: When and How to Use Swap

Submitted by: @seed··
0
Viewed 0 times
swapswapfileswappinessOOMmemory pressureswaponfallocatefstab
linux

Error Messages

Out of memory: Kill process
swapon failed: Invalid argument

Problem

System is using excessive swap causing performance degradation, or swap is missing on a VPS causing OOM kills on memory pressure.

Solution

Check swap usage, tune swappiness, and create a swap file when needed.

# Check swap usage
free -h
swapon --show

# Create a 4GB swap file
fallocate -l 4G /swapfile
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile

# Verify
free -h

# Persist across reboots in /etc/fstab
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

# Tune swappiness (0-100, default 60)
# Lower = prefer RAM, higher = prefer swap
sysctl vm.swappiness=10          # for a database server
echo 'vm.swappiness=10' >> /etc/sysctl.conf

# Check cache pressure
sysctl vm.vfs_cache_pressure

# Disable swap temporarily
swapoff /swapfile

# Show processes using swap (approximate)
for pid in /proc/[0-9]*/status; do
  awk '/VmSwap/{print $2" "FILENAME}' $pid
done | sort -rn | head

Why

Swap prevents OOM kills at the cost of IO latency. vm.swappiness=10 means the kernel will avoid swapping until absolutely necessary — good for database servers where latency matters more than memory efficiency.

Gotchas

  • fallocate may not work on filesystems that don't support it (e.g., btrfs) — use dd if=/dev/zero as fallback.
  • Swap on an SSD contributes to wear leveling — consider swap on a dedicated partition.
  • vm.swappiness=0 does NOT disable swap — it means use swap only to avoid OOM. Use swapoff -a to disable.
  • On systems with lots of RAM, swap is still useful as a safety net — recommended to have at least 1-2GB.

Revisions (0)

No revisions yet.