Tune Linux vm.swappiness for Server Performance

Why vm.swappiness matters on Linux servers

On Linux servers, vm.swappiness controls the kernels tendency to move memory pages to swap vs keeping them in RAM. Tuning vm.swappiness impacts latency, throughput, and the overall responsiveness of services, especially under memory pressure. For sysadmins, developers, and SREs, understanding and measuring vm.swappiness is a practical way to reduce I/O spikes and avoid unexpected out of memory events.

This guide focuses on hands on measurement, safe adjustments, enabling zswap and zram, making persistent sysctl changes, and offering workload specific recommendations for databases, virtual machines, and containers. Commands and monitoring checks are included so you can reproduce tests and roll back changes if needed.

Measure real swap activity

Before changing vm.swappiness, baseline swap usage and page faults. Use tools that report real time activity and historical counters, for example vmstat, sar, free, and /proc/vmstat. Look for swapin and swapout rates, page faults, and the amount of swapped memory to decide if swap is active or simply reserved.

Useful commands to run while the workload is active include:

  • vmstat 1 30 to capture short term stats
  • cat /proc/vmstat | egrep "pswpin|pswpout|pgmajfault|pgfault" for counters
  • free -m to view total swap and usage

Benchmark latency and throughput changes

Measure application latency and I/O throughput before and after adjustments. Use fio for disk performance, and tools like ab, wrk, or your applications native load generator for latency profiles. Collect metrics from iostat, sar, and your APM so you can correlate spikes with swap activity.

See also  Linux Backup Checklist for Reliable Recovery

When benchmarking, run controlled workloads, and capture system metrics in parallel. Sample workflow:

  • Start monitoring: vmstat, iostat -x, and application metrics
  • Run the workload for a fixed duration
  • Compare percentiles, IOPS, and latency histograms between runs

Adjust vm.swappiness safely

Change vm.swappiness conservatively, test, then iterate. The default value is often 60 on many distributions, which favors swapping sooner. Lowering the value keeps pages in RAM longer, reducing I/O at the cost of higher memory pressure. Raising it increases swapping, which may help on systems with heavy caching needs but slow memory allocations.

Apply a temporary change with sysctl during tests, for example sysctl -w vm.swappiness=10. Recommended starting values for common roles:

  • Databases: 1 to 10 (favor RAM over swap)
  • Virtual machine hosts: 10 to 30 (balanced)
  • Containers and general purpose servers: 10 to 60 depending on memory overcommit

Enable and tune zswap

zswap provides an in memory compressed cache for swapped pages, reducing physical I/O. It can be a low risk win on systems with spare CPU and limited swap devices. Enable at boot via kernel parameters or at runtime via sysfs. Example to enable at runtime:

echo 1 > /sys/module/zswap/parameters/enabled

Tune zswap with parameters such as max_pool_percent and compressor. Monitor compression ratios and pool usage with cat /sys/module/zswap/parameters/*. If compression reduces disk writes and latency, make the change persistent in your boot config.

vm.swappiness

Use zram for swap and compressed RAM

zram creates compressed block devices in RAM for swap, giving faster swap than disk backed devices. It is useful on memory constrained VMs or systems without fast swap devices. Configure zram size conservatively, for example 25 to 50 percent of RAM depending on workload and CPU cost of compression.

See also  Linux Systemd Troubleshooting: Fix Failed Units Fast

Common steps are installing the zram service or configuring via udev or systemd, then enabling a zram device as swap. Monitor with swapon --show and observe how zram affects page reclaim and overall latency. If CPU becomes the bottleneck, dial back zram size or switch to zswap.

Make sysctl changes persistent and rollback

To persist vm.swappiness across reboots, add the setting to /etc/sysctl.d/99-custom.conf or /etc/sysctl.conf, for example vm.swappiness=10, then apply with sysctl --system. Document changes in your configuration management system so they are auditable and repeatable.

Rollback steps are simple, and should be tested as part of change management. To revert temporarily, run sysctl -w vm.swappiness=60 or remove the line from sysctl configuration files and reload. Keep a short playbook that lists commands, expected metrics, and a time window for safe rollback.

Workload specific recommendations

Different services have different tolerance for swap. Databases and latency sensitive services must avoid swapping under normal load, while batch jobs and caching nodes may tolerate more swap. For virtual machine hosts, balance between guest memory and host responsiveness.

Recommendations summary:

  • Databases: set vm.swappiness low, enable hugepages and ensure sufficient RAM
  • VM hosts: test with representative consolidation ratios, prefer zswap over disk swap
  • Containers: monitor OOM events and tune cgroup memory limits, use lower swappiness per container if supported

FAQ

Q: What value should I set vm.swappiness to for a PostgreSQL server? A: Start with 1 to 10, benchmark under heavy transactional load, and monitor page faults and latency. Many production Postgres systems use 1 or 0 to avoid swapping at all.

Q: Will disabling swap improve performance? A: Disabling swap removes the safety net and may cause OOM kills if memory is exhausted. It can improve latency if you have headroom, but only disable swap after testing and ensuring memory sufficiency.

See also  Linux Rootkit Removal for Production Servers, Step by Step

Q: How does zswap compare to zram? A: zswap is a compressed cache for existing swap devices, reducing disk writes. zram creates compressed swap in RAM, which can be faster but uses CPU and RAM for storage. Choose based on CPU availability and swap device speed.

Q: How do I monitor that my vm.swappiness change helped? A: Compare baseline and post change metrics: swapin/ swapout counters, application p99 latency, IOPS, and page faults. Use consistent load tests to validate improvements and ensure no adverse effects.

Conclusion

Tuning vm.swappiness on Linux servers is a practical, measurable approach to reduce latency and control swap I O behavior. The responsible process begins with baseline measurement, controlled benchmarking, and conservative changes applied via sysctl for temporary testing. For many production roles, lowering vm.swappiness reduces unnecessary disk I O and improves application response times, however every environment is different so testing under realistic load is essential. Complementary technologies such as zswap and zram offer ways to reduce disk swap activity by compressing pages in memory, but they introduce CPU cost that must be weighed against I O savings. Always persist changes through sysctl configuration files or your configuration management system, document the rationale, and prepare rollback steps that include reverting values and monitoring for regressions. By following a structured testing and rollback plan, system administrators can tune swapping behavior safely, improve server stability, and match settings to the demands of databases, virtual machines, and containerized workloads.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top