Optimizing Ubuntu Swap for SSD: Key Steps and Best Practices
Using an SSD for Swap is the most impactful optimization—its faster read/write speeds (especially NVMe SSDs) drastically reduce swap latency compared to HDDs. This is ideal for systems with limited RAM, as it minimizes performance degradation when swapping occurs. Ensure your SSD has sufficient endurance (e.g., consumer-grade NVMe SSDs handle frequent writes well for typical desktop use).
Swappiness (0–100) controls how aggressively the kernel moves memory pages to Swap. A lower value reduces unnecessary disk I/O (extending SSD lifespan) while relying more on physical RAM.
cat /proc/sys/vm/swappiness (default: 60).sudo sysctl vm.swappiness=10 (applies until reboot).vm.swappiness=10 to /etc/sysctl.conf (recommended for SSDs; values between 10–30 strike a balance between RAM usage and swap responsiveness).Zswap (available in Linux kernel 4.0+) compresses memory pages before writing them to Swap, reducing the volume of data written to the SSD. This cuts I/O by up to 50% for compressible data (e.g., text, code) and delays swap usage until compression is no longer feasible.
/etc/default/grub, add zswap.enabled=1 zswap.compressor=lz4 to GRUB_CMDLINE_LINUX, then run:sudo update-grub
sudo reboot
LZ4 is the fastest compressor; alternatives include zstd (better compression but slower).Add the noatime option to your SSD’s filesystem mount entry in /etc/fstab. This disables updating the “last accessed” timestamp for files, reducing unnecessary write operations (critical for SSD longevity).
/dev/sda1 / ext4 defaults 0 1 to:/dev/sda1 / ext4 noatime,discard,defaults 0 1sudo mount -oremount / to activate noatime without rebooting.Use tools to track Swap activity and ensure optimizations are effective:
free -h: View total Swap usage and available RAM.swapon --show: Check active Swap devices/files and their sizes.vmstat 1: Monitor si (Swap In) and so (Swap Out) values—frequent swaps indicate high usage.Adjust the Swap file size based on your RAM and workload:
sudo fallocate -l 8G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
/etc/fstab: Replace the old entry with /swapfile none swap sw 0 0 to retain changes after reboot.sudo swapoff /old_swapfile
sudo rm /old_swapfile
For SSDs, a Swap file size equal to or slightly larger than your RAM (e.g., 8GB RAM → 8GB Swap) is sufficient for most users.By following these steps, you can configure Ubuntu’s Swap to work efficiently with SSDs, balancing performance, longevity, and system stability.