12

Today I noticed that I found the following thing:

enter image description here

As you can see the RAM is almost half-free and the usage of swap space is very high. From my textbook knowledge, I used to think that Linux OS tries to make best usage of RAM and when it gets short of RAM, it will move some of the least used pages from RAM to Swap space.

Can someone please explain me if my theoretical knowledge is incorrect and explain me how in the world of linux it actually works.

pradeepchhetri
  • 2,518
  • 6
  • 33
  • 45

3 Answers3

10

While it is true that kernel uses swap even if there may be memory left, using more than two thirds of it may be an indicator that historically the server may have been running out of memory and that is why it started swapping. I would correlate swap usage with memory usage in the sar reports to deduce whether the system has enough ram. I would also check dmesg or the logs to determine if the server has in fact ran out of memory, and the oom-killer kicked in.

Petter H
  • 3,383
  • 1
  • 14
  • 18
8

The Linux Kernel starts to swap out memory pages even if you have plenty of ram free. You can fine tune this behaviour by setting a custom swappiness.

http://en.wikipedia.org/wiki/Swappiness

For servers, I'd recommend to set the swappiness to 1 if you have always enough memory for your workload. For workstations, I'd recommend using the default of 60.

# check the current value
cat /proc/sys/vm/swappiness
60

# swappiness = 1 (swap only if necessary)
echo 1 > /proc/sys/vm/swappiness

# or use sysctl
sysctl -w vm.swappiness=1

Make the setting permanent in /etc/sysctl.conf by setting

vm.swappiness=1

and reload it with

sysctl -w
mgabriel
  • 1,091
  • 8
  • 15
  • I would argue swappiness of 1 would hurt performance. Let's say for instance, you're using 80% of RAM on a normal basis, so you have no swap in use but 20% of that RAM is stale data that hasn't been used. All of a sudden, a new application loads up (or web site gets loads of hits). You only have 20% of RAM left then the server will start swapping severely limiting performance. If you had a higher swappiness, those stale pages in the RAM would have already been swapped out so you would have had 40% free RAM to handle the spike in usage. – Devon May 17 '15 at 16:34
  • At least on Ubuntu, the "reload from sysctl.conf" recipe is `sysctl --system`, not `-w`. – rfay Feb 02 '20 at 14:23
0

Some applications will unfortunately hammer swap directly, intentionally skipping RAM. Looking at you, Chrome (and at one point Photoshop). The only way to get these applications not to swap is to run without a swap partition. Even swappiness 0 IIRC will still give them access since they explicitly demand it.

Changing swappiness per above will work for everything else though. I would suggest a value of 10-20 instead of 1 though.

Arthur Kay
  • 461
  • 2
  • 10