How To Boost Linux Server Performance By Enabling Swap

Photo by KUSHAGRA DHALL / Unsplash

How To Boost Linux Server Performance By Enabling Swap

Enhance The Speed And Responsiveness Of Linux Servers By Enabling Swap And Optimizing Memory Management

Paul Knulst  in  DevOps Feb 16, 2024 6 min read

💡
Yesterday, I tried to do a heavy job on one of my servers and quickly found out that using no Swap file could lead to out-of-memory errors which will end in rebooting. Then, I searched the Internet and found some ways in the Linux kernel documentation which I used to enable Swap and optimize it.

It worked so well that I wanted to write down my findings and explain to everyone how to do it in a (hopefully) well-documented way.

Introduction

A very practical strategy for preemptively avoiding getting out-of-memory errors within all kinds of applications is increasing the Swap space on your Linux server. By allocating Swap space you will effectively create a special area for the operating system to unload applications from the RAM to prevent memory exhaustion.

In this article, we will learn how to create a Linux Swap to boost our server performance. With detailed instructions and practical examples, you will understand the implementation process and be ready to optimize your server.

If you want to skip everything and just try out my recommendations, please jump to the section "Script To Do Everything Automatically".

But wait, What is Swap?

On a Linux system, Swap is a special area on your HDD that is designed to temporarily store RAM data to increase the "memory" with some limitations. Because the Swap file is on the HDD it will be significantly slower than your RAM. Therefore, it will only be used as the RAM gets full, to keep data from running applications in "memory" instead of throwing it away. So this Swap file is a good utility file to use if your RAM runs full and some kind of safety approach against out-of-memory exceptions on low RAM systems.

💡
Note: If using a lot of RAM (>64GByte) you don't really need a Swap file because normally your RAM should not be full in any case.

To learn more about the concept and get more insights about the process of "swapping" you should read this Wikipedia page where "Memory Paging" is explained in detail:

Memory paging - Wikipedia

After reading (or skipping) the Wikipedia page you can now follow this guide by applying all explained commands.

Check If Swap Is Already Enabled

The first step we have to do is check if our server already has a Swap file registered.

💡
Note: It is possible to have multiple Swap files!

To list all configured Swap files we have to type:

swapon --show

This command does not produce any output if the system does not have any Swap file available. Additionally, we can use the free utility on Linux to display information about the RAM which will also display information about the Swap file:

~# free -h
              total        used        free      shared  buff/cache   available
Mem:          7.6Gi       6.1Gi       170Mi       137Mi       1.3Gi       1.1Gi
Swap:            0B          0B          0B

In this snippet, we see that our server has a total of 8G of RAM and no Swap file configured.

Create a Swap File

Assuming we have enough free HDD space left, we can now create a new Swap file within our Linux filesystem. To do this we will create a file named swap in our root (/) directory with a utility tool called fallocate (should be installed on every Linux machine).

💡
Note: fallocate just creates a file with the specified size.

As our server has 8G of RAM we should create a Swapfile which is at least the same size. If you have another amount of RAM please adjust the following command to your needs:

fallocate -l 8G /swap

Enable the Swap File

Before we turn the allocated space into a Swap file, we should lock down the permissions to avoid users accessing it except them with root privileges. If not doing this all users on the server can access the file and read its content. This would be a major security issue and have to be avoided at all costs.

To make the file only accessible by root we use chmod:

chmod 600 /swap

Now to check if the file exists and has the correct permission use:

~# ls -lh /swap 
-rw------- 1 root root 8.0G Feb 15 20:40 /swap

If your output looks the same you can mark the Swap file as your Swap space by executing:

mkswap /swap

The command should output the following:

~# mkswap /swap
Setting up swapspace version 1, size = 8 GiB (8589930496 bytes)
no label, UUID=baf2b4a0-9ddd-4fb6-a941-289e85ff9dc4
💡
Note: UUID and size will be different on your system.

The last step is enabling the Swap file by executing:

swapon /swap

After we executed all previously shown commands we can use free and swapon to validate if the Swap file no is present on the Linux server:

swapon

~# swapon --show
NAME  TYPE SIZE USED PRIO
/swap file   8G   0B   -2

free

~# free -h
              total        used        free      shared  buff/cache   available
Mem:          7.6Gi       6.1Gi       162Mi       137Mi       1.3Gi       1.1Gi
Swap:         8.0Gi          0B       8.0Gi

Permanently Enable Swap File

Unfortunately, everything done in the previous chapters will be gone after we reboot our server. Luckily, we can change this by adding the swap file in the fstab file. This can be done in two ways:

1. Use Echo and Tee:

echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

2. Manually adding /swapfile none swap sw 0 0 at the end of the /etc/fstab file with your preferred Editor

Further Improvements

When using a Swap file there are two settings that I personally think are important to adjust. First, there is vfs_cache_pressure which controls the tendency of the kernel to reclaim the memory which is used for caching of inode and directory objects. The second setting is the swappiness which controls how much the kernel prefers Swap over Ram. Both settings should be adjusted to optimize Swap file usage on our server. For more settings just read the Linux kernel documentation

Adjust vfs_cache_pressure

Before we change the value of vfs_cache_pressure we should check the current value by executing:

cat /proc/sys/vm/vfs_cache_pressure

On my server running Linux, the initial value was set to 100 which is really high and will remove inode information too quickly. Because of this, we should set the value to 50 by using the sysctl command:

sysctl vm.vfs_cache_pressure=50

As with the Swap file, this setting is only valid until we reboot our server. To persist the vfs_cache_pressure setting in our server we have to adjust the sysctl.conf within the etc folder.

Open /etc/sysctl.conf with your preferred Editor (I use VIM) and add the following line at the bottom:

vm.vfs_cache_pressure=50

Adjust swappiness

As with the vfs_cache_pressure the first command we execute is used to check the current value of the Swappiness:

cat /proc/sys/vm/swappiness

On my server, this setting was 60 which is a good default setting for a desktop computer which will often use a GUI and other different programs. But, when used as a server the Swappiness should be much lower to boost Swap and Ram performance. You can play around with the settings but I recommend something between 10 - 20.

As done before we have to use sysctl to set the Swappiness on our server:

sysctl vm.swappiness=20

To persist the setting in our server we have to use our preferred Editor and open the /etc/sysctl.conf and add the following line at the bottom:

vm.swappiness=20

Script To Do Everything Automatically

If you trust me (obviously you do) and just want to enable Swap file, set the Swappiness, and adjust the Cache Pressure you can simply copy the following script:

fallocate -l 8G /swap
chmod 600 /swap
mkswap /swap
swapon /swap
echo '/swap none swap sw 0 0' | tee -a /etc/fstab
echo 'vm.swappiness=20' | tee -a /etc/sysctl.conf
echo 'vm.vfs_cache_pressure=50' | tee -a /etc/sysctl.conf

Then adjust your Swap file size (remember it should align with your RAM) and paste it into your CLI connected to your server.

Closing Notes

Managing the Swap space on Linux servers is important for preventing memory errors and boosting performance. If you followed this guide, you should now have set up and optimized your Swap space which normally should boost your server.

Hopefully, this article was easy to understand and your server is faster than ever and will not get any out-of-memory errors or reboots (like mine before I did it).

Do you have any questions regarding Swap? I would love to hear your feedback, your thoughts and answer all your questions. Please share everything in the comments.

Feel free to connect with me on Medium, LinkedIn, Twitter, and GitHub.


🙌 Support this content

If you like this content, please consider supporting me. You can share it on social media, buy me a coffee, or become a paid member. Any support helps.

See the contribute page for all (free or paid) ways to say thank you!

Thanks! 🥰

By Paul Knulst

I'm a husband, dad, lifelong learner, tech lover, and Senior Engineer working as a Tech Lead. I write about projects and challenges in IT.