What is a Swap File and What is It Used For

The computer technologies are advancing rapidly. Remember how 20 years ago it was so cool to have a home computer with 1GB of RAM and a 2GHz single-core processor. And the equipment was extremely expensive. What about now? Many cell phones are more powerful and more productive than old computers. Back then one way to expand the capabilities of your computer was to use swap.

ATTENTION! Using swap on an SSD results in its quick failure. If you host your server on a hosting service - specify on what type of hard drives your server is located before switching to swap.

What is a Swap File

Swap (often you can see the term paging or swapping) is a virtual memory mechanism that moves unused memory pages (these are fragments of memory in modern computers) to another storage (hard disk or any other), thereby freeing up space in the RAM to load active memory pages. A partition (swap partition) or a file (swap-file) can serve as a storage.The swap partition is usually created at the time of installation of the operating system, and the swap file can be created at any convenient time, the main thing that's required is free space.

The system does not constantly use the swap area, it mostly does when the free RAM space for running applications (programs) has run out. Therefore, in modern computers, the use of swap is not so critical because of the large amount of RAM. In modern times even 8GB of RAM are considered small.

It should be understood that the transfer from the RAM to backup storage and backloading of memory pages to the RAM is an additional load on the system, and therefore decreases performance. In addition, the speed of the RAM is many times higher than that of all existing hard drives. So what about the SSD (solid-state drive), you may ask? One of the critical parameters of the SSD is the number of write cycles. This parameter directly affects the lifespan of such drives, thus using swap on SSD is not recommended.

Without using swap, memory errors can be observed in logs. If your computer at some point runs out of RAM, then you can try to use swap before increasing the RAM size. Therefore, we will consider creating a swap file on the example of the CentOS 7 operating system.

Checking Swap

First, let's see if swap is used in our system (note that all commands are executed from the root user, if you want to execute them from your user, then you need to use "sudo" before all commands):


# swapon --show

If there is no output, that means that swap is not used.


# free -h
       total   used   free   shared   buff/cache   available
Mem:   991M    80M    783M    6.6M    126M    768M
Swap:    0B    0B    0B

As you can see, we have only 1GB of RAM on the computer and swap is not used. Now let's check the availability of free hard disk space:


# df -h
Filesystem   Size   Used   Avail   Use%   Mounted on
/dev/vda2    4.8G   1.1G   3.8G   22%      /
devtmpfs     485M     0   485M    0%      /dev
tmpfs        496M     0   496M    0%      /dev/shm
tmpfs        496M  6.6M    489M   2%     /run
tmpfs        496M     0   496M    0%     /sys/fs/cgroup
/dev/vda1    240M   97M   127M   44%     /boot
tmpfs        100M     0   100M    0%     /run/user/0

In this case, the “/dev/vda2” partition has another 3.8 GB of free space. It is up to you personally to decide how much space to allocate for swap based on the applications used, but in most cases, it is recommended to allocate space equivalent to the size of the RAM, or to double it.

In our case the swap of 1-2GB is desirable. In general cases, if the RAM size is less than 2GB, we would advise you to use a double value for swap, if the size of the RAM is large, then you should use equal value, but no more than 4GB. Do you remember that swap is used on slower devices? This means that it has a direct impact on performance. If this parameter is critical - it is worth considering buying additional RAM.

Creating swap file

In our example, there is little space on the hard disk, so let's create a swap of 1GB. We will use the "fallocate" command because it allows you to specify the file size in advance. Let’s create a swap file in the root directory.


# fallocate -l 1G /swapfile

In this example, the "-l" parameter allows you to specify the file size. Next comes the size of 1GB and the full name of the file along with the path.


# ls -lh /swapfile
-rw-r--r-- 1 root root 1.0G Jan 13 22:25 /swapfile

The "-lh" parameters allow you to display data in a readable format. As we see the file size is 1GB.

Now it's time to think about security and restrict file access to root only:


# chmod 600 /swapfile
# ls -lh /swapfile
-rw------- 1 root root 1.0G Jan 13 22:25 /swapfile

Next, we fill the file with zero blocks of 1024KB and specify to do this procedure 1000 times, which in the end will be equal to 1GB.


# dd if=/dev/zero of=/swapfile bs=1024k count=1000

Now initializing the swap file:


# mkswap /swapfile
Setting up swapspace version 1, size = 1048572 KiB
no label, UUID=2d247a05-2677-4fda-966e-5b353ab678c9
# swapon /swapfile

Now let's check:


# swapon --show
NAME    TYPE  SIZE  USED  PRIO
/swapfile file 1000M 0B -2
# free -h
       total   used   free   shared   buff/cache   available
Mem:   991M    81M    65M    6.6M    843M    749M
Swap:   999M    0B    999M

But after reloading we will need to enable the swap file manually again, so we will automate this process with the help of "/etc/fstab" file, backing it up in advance in case of an error:


# cp /etc/fstab /etc/fstab.bkp
# echo '/swapfile none swap sw 0 0' | tee -a /etc/fstab
# cat /etc/fstab
 ## /etc/fstab# Created by anaconda on Sun Jan 13 15:28:36 2019## Accessible filesystems, by reference, are maintained under '/dev/disk'# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info#UUID=84c10b6f-4758-4877-ad89-a884b96f7473 / xfs defaults 0 0UUID=0ea9e01e-0d3b-41b4-91a9-95bd1ffbd9eb /boot ext4 defaults 1 2/swapfile none swap sw 0 0 

Setting Up OS Parameters with Swap

Setting some parameters can have a significant impact on system performance, so let's take it carefully. First, let's look at the “swappiness” parameter, which tells the system from what point to use swap. This is a number from 0 to 100, representing the percentage of the remaining free space in the RAM. For home computers, it is possible to set this setting to 60, but for server systems it is better to reduce it to at least 10, which is what we will do. First we check the current value:


# cat /proc/sys/vm/swappiness
30

Now we set it to 10 using “sysctl” utility::


# sysctl vm.swappiness=10
vm.swappiness = 10
# cat /proc/sys/vm/swappiness
10

To save this value after reboot, change the "/etc/sysctl.conf" file or redefine the parameter using a separate file. To do this, place it in the "/etc/sysctl.d/" directory, which is what we will do:


# touch /etc/sysctl.d/swap.conf
# echo 'vm.swappiness=10' | tee -a /etc/sysctl.d/swap.conf

The next parameter is "vfs_cache_pressure", which is responsible for the frequency of cache memory usage, i.e. swap. The larger the parameter, the less the cache will be used by the operating system, the more RAM will be used. By default, this parameter is 100. For systems with a small amount of RAM, it is better to set a smaller parameter, for example, 50:


# cat /proc/sys/vm/vfs_cache_pressure
100
# sysctl vm.vfs_cache_pressure=50
vm.vfs_cache_pressure = 50

Now, like the previous parameter, we need to add it to the “sysctl” utility configuration file:


# echo 'vm.vfs_cache_pressure=50' | tee -a /etc/sysctl.d/swap.conf

This concludes the setting up of the swap file. In order to return the values to the default settings it would be enough to delete the "/etc/sysctl.d/swap.conf" file and restart the server.

Conclusion

We learned how to give some more space for a maneuver for a little while and avoid out of memory errors in applications. If the RAM is full, the computer might “freeze”, which will stop all services. This is where the swap file will help us a lot.

But it should be understood that this is not an ultimate solution for all the issues. If in your case the RAM is constantly full - it is worth considering the option of optimizing the application code, replacing applications or purchasing a new computer/increasing the RAM size. For everything else there is swap.

Too complicated?
We offer server administration services.