Swap Space

Managing virtual memory and swap space for system stability and handling memory overflow conditions

Swap space is virtual memory that extends RAM by using disk storage. When physical memory fills up, Linux moves inactive pages to swap, preventing out-of-memory crashes and maintaining system stability.

Key Concepts

  • Virtual Memory: Combination of RAM + swap space
  • Swap File: Regular file used as swap space
  • Swap Partition: Dedicated disk partition for swap
  • Swappiness: Kernel parameter controlling swap usage
  • Page: Fixed-size memory block moved to/from swap

Command Syntax

swapon [options] device/file swapoff [options] device/file

  • Enable/disable swap space
  • Device can be partition or file path

Common Options

-a - Enable/disable all swap in /etc/fstab -s - Display swap usage summary -p priority - Set swap priority (0-32767) -v - Verbose output --show - Display swap areas

Practical Examples

Example 1: Check current swap status

1
2
free -h
swapon --show

Shows memory usage and active swap areas

Example 2: Create swap file

1
2
3
4
sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

Creates and enables 2GB swap file

Example 3: Make swap permanent

1
2
echo '/swapfile none swap sw 0 0' | 
sudo tee -a /etc/fstab

Adds swap to fstab for automatic mounting

Example 4: Adjust swappiness

1
2
3
cat /proc/sys/vm/swappiness
echo 'vm.swappiness=10' | 
sudo tee -a /etc/sysctl.conf

Views and sets swap aggressiveness (0-100)

Example 5: Remove swap space

1
2
sudo swapoff /swapfile
sudo rm /swapfile

Disables and removes swap file

Use Cases

  • Low RAM systems: Extend available memory
  • Hibernation: Store RAM contents to disk
  • Memory spikes: Handle temporary high usage
  • Stability: Prevent OOM killer activation
  • Large applications: Support memory-intensive tasks

free - Display memory and swap usage vmstat - Virtual memory statistics mkswap - Set up swap area top/htop - Monitor swap usage by process cat /proc/swaps - Show swap areas

Tips & Troubleshooting

Performance Considerations

  • SSD vs HDD: SSDs provide faster swap access
  • Size: Typically 1-2x RAM, depends on use case
  • Priority: Higher priority swap used first
  • Multiple swap: Distribute across drives

Common Issues

  • High swap usage: Check for memory leaks
  • Swap thrashing: Reduce swappiness or add RAM
  • Permission errors: Ensure correct ownership/perms
  • Boot failures: Verify fstab entries

Best Practices

  • Monitor swap usage with sar -S
  • Keep swappiness low (10-20) for desktops
  • Use swap files for flexibility
  • Regular cleanup of unused swap areas
  • Consider zram for better performance

Security Notes

  • Swap may contain sensitive data
  • Encrypt swap on security-critical systems
  • Clear swap before system disposal