Why does the system swap while it has enough RAM and is this harmfull?
I operate a 64GB RAM root bare metal ubuntu 16.04 server with SSDs that is under pretty heavy load. Now I learned that cloud servers generally disables swap as it can wear the SSDs in the long run. This makes me worry about my server as it swaps while there is no need as enough RAM is available.
Dashboard screenshot here
Is this normal or would you recommend to take action, for example disable swapping?
Don't scream just because Linux is swapping, in fact in healthy server this is perfectly normal if not even a sign of a optimized server. This is because "low" swapping can sometimes save you and your drives precious IO actions on the drives. The less activities on the drive (expensive processes even on state of the art NVMe arrays), the better.
Also unless the swapping is aggressive it will do insignificant harm to a SSD. Especially many SSDs that are used for clouds are built to lasts in the PB(s) range before the cells all dies.
Memory is allocated and de-allocated all the time and this leads to fragmentation: a portion of allocated memory is followed by a portion of unallocated memory and so on. The unallocated(free) portions of memory may become smaller and smaller over time. At some point a process may need to allocate some amount of memory which is not available as a single contiguous block. Swapping helps in freeing memory and creating bigger contiguous portions of free memory which otherwise would not be available.
Short answer: yes, it is normal and you don't need to worry about it.
Long answer: linux does use some swap even if enough memory is available. The rationale is that caching recently read/written data can be more useful than keeping old, inactive program code & data in RAM. This bias can be modified via the swappiness
sysctl tunable. From the kernel docs:
swappiness
This control is used to define how aggressive the kernel will swap memory pages. Higher values will increase aggressiveness, lower values decrease the amount of swap. A value of 0 instructs the kernel not to initiate swap until the amount of free and file-backed pages is less than the high water mark in a zone.
The default value is 60.
If you really want to reduce swapping, you can lower the swappiness
value via sysctl vm.swappiness=10
or echo 10 > /proc/sys/vm/swappiness
. Remember that this is valid until a reboot; to keep it between reboots, you need to edit the /etc/sysctl.conf
file.
If you wan to completely disable swap, you can use swapoff -a
(commenting the relevant /etc/fstab
entry to let it persist between reboots).