Recycling Swap

Now and then, heavily used systems may need to have their swap usage cycled (reset) to increase performance. There are many occasions where even though a system has enough RAM, there may still be a growing swap usage. The steps I outline here are safe to run on a production host to reduce swap usage and return swap contents to RAM.

Check current swap use:

root@pkvm1:~# free -m
              total        used        free      shared  buff/cache   available
Mem:           7800        4822         383           1        2594        2668
Swap:          4095         429        3666
root@pkvm1:~#

We can see here that about 430MB of swap is used even though there is plenty of RAM available. In this case, the system gets average consistent use and has been up for 206 days. We want to also see what the swappiness setting is currently set at and maybe reduce it:

root@pkvm1:~# cat /proc/sys/vm/swappiness
60
root@pkvm1:~#

root@pkvm1:~# sysctl vm.swappiness=20
vm.swappiness = 20
root@pkvm1:~# cat /proc/sys/vm/swappiness
20
root@pkvm1:~#

This new setting of 20 should help the system swap less often. We now want to force the system to move swap contents back to RAM where it belongs. To do that, we’ll turn swap off, and WAIT approx. 30 seconds, then turn swap back on:

root@pkvm1:~# swapoff -a
root@pkvm1:~# swapon -a
root@pkvm1:~# free -m
              total        used        free      shared  buff/cache   available
Mem:           7800        5295         143           2        2360        2194
Swap:          4095           0        4095
root@pkvm1:~#

We can now see that swap contents has been moved to RAM and that swap has reclaimed space. It should be easy to write a cron job to check swap usage and periodically do this when swap usage goes above an acceptable threshold.

Leave a Reply

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