The kernel uses heuristics to guess which pages of memory are likely to be needed in the near future and tries to keep those pages in memory, regardless of whether they belong to processes or kernel caches. It is normal for the kernel to swap out process memory, even when there is plenty of cache memory that could easily be freed.
The swappiness parameter controls the tendency of the kernel to move processes out of physical memory and onto the swap disk. The kernel heuristics can be tuned by changing the vm.swappiness parameter of sysctl. The default value, which is 60 on CentOS/RHEL 5 & 6 and 30 on CentOS/RHEL 7, is reasonable for most workloads, but some systems may benefit from lower or higher values. Increasing this value will make the system more inclined to swap inactive memory pages to disk, rather than dropping pages from the page cache, leaving more memory free for cached I/O. This may be preferred for heavy I/O workloads. Decreasing this value will make the system less inclined to swap, and more inclined to drop pages from the page cache.
Tuning vm.swappiness may hurt performance, or may have a different impact between light and heavy workloads. Changes to this parameter should be made in small increments, and should be tested under the same conditions that the system normally operates. For example, to set the vm.swappiness parameter to 50:
# echo '50'> /proc/sys/vm/swappiness
To make this setting persistent across reboots, add this line to the /etc/sysctl.conf file:
# vi /etc/sysctl.conf vm.swappiness = 50
While vm.swappiness accepts 0–100 values, it should not be set to 0, as this can cause an unexpected behaviour on the system. 0 is a special value which works differently depending on the RHEL version in use:
- Prior to CentOS/RHEL 6.4: vm.swappiness = 0 disables swapping for the most part, except to avoid an out-of-memory situation.
- RHEL CentOS/6.4 and later: vm.swappines = 0 disables swapping in most cases, If we set swappiness==0, the kernel does not swap out completely (for global reclaim until the amount of free pages and filebacked pages in a zone has been reduced to something very very small (nr_free + nr_filebacked < high watermark)).
Value of swappiness can be checked as follow:
$ cat /proc/sys/vm/swappiness