Add Memory Swap - Arch Linux

Difficulty: 2
Time: 30 minutes

If you’re trying to improve your server’s performance, adding swap space (or memory swap) is a powerful and relatively simply place to start.

Swap space is a dedicated portion of your server’s hard drive where the operating system can dump the contents of its RAM to, once the RAM gets full. To understand the real benefit of that, you need to be familiar with processor architecture - but here's a brief explanation:

  • RAM provides data to the processor quickly, which makes it very valuable.
  • Once your RAM is full it needs to either delete or move the data elsewhere.
  • Deleting the data from RAM means it must be found and retrieved from the hard drive (which is slow) the next time the data is requested.
  • By moving the data out of RAM and into a swap space instead of simply deleting it from RAM, it’s much faster to find the data the next time it’s requested.
  • Moving data from RAM to the swap space consumes the processor’s resources, so doing it continually will actually degrade your application’s performance. (This is known as swap thrashing.) To find the optimal swap rate, it requires tuning.

Lastly — though differences are minute, for the sake of clarity, this article walks you through create a swap file - not a swap partition. If you don't know what that means, don't worry about it.

Check current swap space usage

To prevent any issues when adding swap, first check that your system does not have already have a swap space enabled.

  • Find any active swap space on the drive:
    free -m

The output looks similar to this, in which the total swap space in the system is 0:

total        used        free      shared  buff/cache   available
Mem:           2005          24        1870           0         111        1953
Swap:             0           0           0

This shows available memory, and should display a zero for swap memory.

Check your available space

Now that you're ready to create a swap file, you need to find out space your server's hard drive has.

  • Check the amount of space available on the server:
    df -h

This command shows the free space on your hard disk. In the following example, you have 40 GB available. Make sure that there is enough free space for your swap file. The space you need depends on your requirements but, in general, an amount equal to or double your system's RAM.

Filesystem      Size  Used Avail Use% Mounted on    
/dev/vda         50G  10G   40G   20% /             
none            4.0K     0  4.0K   0% /sys/fs/cgroup  
udev            2.0G   12K  2.0G   1% /dev           
tmpfs           396M  312K  396M   1% /run    
none            5.0M     0  5.0M   0% /run/lock  
none            2.0G     0  2.0G   0% /run/shm  
none            100M     0  100M   0% /run/user

Create a swap file

Add swap space to your system by creating a file called swapfile in your root (/) directory and assigning it as swap. There are two commands you can use to create swap files:

  • fallocate
  • dd

You only need to use one of these. We recommend using fallocate, but if it isn't supported on your file system, you can use dd instead.

Create a swap file using fallocate command

  1. Create the file to be used for swap (for this example, we're adding a 4GB file):
    sudo fallocate -l 4G /swapfile
  2. Verify that the correct amount of space was reserved:
    ls -lh /swapfile
    This result shows that the file was added with the correct amount of space set aside:
    -rw-r--r-- 1 root root 4.0G Jul 08 10:52 swapfile

Create a swap file using dd comand

In this example, we'll add a swap file of a different size, 1 GB, in order to accommodate smaller-sized servers.

  1. Add the 1 GB swap file by specifying a block size bs of 250 MB and a count of 4.
    Warning: Remember to double check your instructions! This command has the potential to destroy data if of (output file) points to the wrong location.
    sudo dd if=/dev/zero of=/swapfile bs=250M count=4
    After a few seconds, the generated output looks like this:
    4+0 records in
    4+0 records out
    1048576000 bytes (1.0 GB) copied, 1.47414 s, 711 MB/s
  2. Verify that the file has been created on the server:
    ls -lh /swapfile
    The command returns something similar to this:
    -rw-r--r-- 1 root root 1000M Jul 08 22:27 swapfile
    The system created the file by writing 1 GB (1000M) of zeroes to the disk and, in this case, took 1 second to complete.

Enable the swap file

Now that your swap file's been created, tell the system to format your file as swap, and then enable it.

  1. Lock the swap file's permissions so that only the root user can access it:
    sudo chmod 600 /swapfile
    When first created, swap files are readable by the world, so locking permissions prevents users from reading potentially sensitive information.
  2. Verify that the file has the correct permissions:
    ls -lh /swapfile
    The command returns something similar to this:
    -rw------- 1 root root 4.0G Jul 08 10:40 swapfile
    This confirms that only the root has read and write permissions enabled.
  3. Format that file to create a swap space.
    sudo mkswap /swapfile
    The command returns something similar to this:
    Setting up swapspace version 1, size = 4 GiB (4294963200 bytes)
    no label, UUID=f86d9832-7d9b-4325-93a5-e806815372e5
  4. Mount/enable the swap space in the system.
    sudo swapon /swapfile
  5. Verify that the swap space was enabled by checking the system reports:
    sudo swapon -s

Make the swap file permanent

The last step is to integrate the swap file into your system's storage partitions and devices through fstab.

  1. Open fstab:
    sudo vim /etc/fstab
  2. At the end of the fstab file, add this line to tell the system to automatically use the newly created swap space:
    /swapfile none swap sw 0 0
  3. Save and close the file:
    :wq!

After the next restart, the swap is used automatically.

Tune the swap file

Now that you've created the swap file, you should work on tuning it to ensure it's giving you optimal performance. This isn't something you can easily do in one sitting, but is something you'll work on periodically as an admin.

Tuning your swap file means tinkering with the settings that make it perform a swap (that is, move data from RAM into your swap):

  • Swappiness
  • Cache Pressure

Tuning is important because a poorly configured swap file can actually hurt your application's performance. The interactions between your system's RAM and the swap space are time-intensive (on a computational scale) and trying to swap too often (that is swap thrashing) can take more time than just retriving your data from your hard drive.

Swappiness

Swappiness is simply a setting that controls how often the swap file is used.

As a percentage between 0 and 100, a swappiness value of:

  • 0 means swapping processes out of physical memory are avoided until absolutely necessary (memory is depleted)
  • 100 means aggressively (almost instantly) moving swap processes out of physical memory and into the swap cache

You can change your server's swapiness in 99-sysctl.conf.

  1. Create or open your 99-sysctl.conf file:
    sudo vim /etc/sysctl.d/99-sysctl.conf
  2. At the end of the file, add this line:
    vm.swappiness=10
  3. Save and close the file:
    :wq!

To tune your application, you can test changes to your swappiness value (between 0 and 100) and running performance tests.

Cache pressure

Another setting is the vfs_cache_pressure. Changing this setting could help when the VFS (virtual file system) cache objects (called dentry and inode_cache objects) consume a larger amount of memory versus other data like page cache and swap. Because VFS cache accesses data about the file system, it's frequently requested and very resource-intensive. Thus, it's a prime setting for your system to cache.

The higher the value of the vfs_cache_pressure, the more likely your server is to use its swap.

You can change your server's cache pressure (again) in 99-sysctl.conf.

  1. Create or open your 99-sysctl.conf file:
    sudo vim /etc/sysctl.d/99-sysctl.conf
  2. At the end of the file, add this line:
    vm.vfs_cache_pressure = 50
  3. Save and close the file:
    :wq!

Like swappiness, you can work on increasing performance by testing different values here.

Verify that swap space was enabled

Check your work with any of these three commands:

  • For a general report:
    sudo swapon -s
    Output may look like this:
    Filename                Type        Size    Used    Priority 
    /swapfile               file        4194300 0       -1
    You'll see that a swapfile of 4 G.0 was added.
  • For a more detailed report:
    free -m
  • For a report on just swap details:
    cat /proc/meminfo | grep -i swap

Conclusion

Swapping can be beneficial in allowing your system to harness more memory than originally available. It's a viable option before having to optimize your application configurations, add more RAM, or upgrade your server.

However, it's important to remember to periodically tune your swap file to ensure you're getting the most out of it.


Oliko tästä artikkelista hyötyä?
Kiitoksia palautteestasi. Jos haluat puhua asiakaspalveluedustajan kanssa, käytä yllä näkyvää puhelinnumeroa tai chat-vaihtoehtoa.
Kiva, että meistä oli apua. Voimmeko tehdä jotain muuta?
Olen pahoillani asiasta. Kerro meille, mikä on epäselvää tai miksi ratkaisu ei toiminut oman ongelmasi kohdalla.