Swap space in Linux is an extension of physical RAM, offering virtual memory that helps maintain system stability and performance. It allows processes to continue running when RAM is fully used and prevents memory errors.
Swap space also enables hibernation and safeguards critical processes by temporarily offloading data. However, it should only be a complement to RAM because a system that relies on swap would suffer significant performance degradation.
This article aims to explain what swap space is, how it works, and how to check and resize it.
What Is Swap Space?
Swap space (also known as swap memory or paging space) is space on a hard drive (HDD or SSD) that represents a substitute for physical (RAM) memory. This feature allows an operating system to temporarily move inactive or less frequently used memory pages from RAM to a designated area on the hard drive
Swap frees up RAM for more important tasks that require more processing power by transferring data to and from a designated disk space. The data interchange is called swapping, while the designated space is called swap space. The swapping rate and assertiveness are determined by a parameter called swappiness.
Operating systems like Windows or Linux provide a certain amount of swap space by default, which users can later change in accordance with their requirements. Users can also disable swap space, but that means that the kernel must kill some processes to create enough free RAM for new processes.
Types of Swap Space
There are two types of swap space in Linux: swap files and swap partitions (also referred to as traditional swap space).
1. Traditional Swap Space
The classic form of swap space that has been in use for decades is traditional swap space. It involves the designation and use of a dedicated partition on a hard drive. A swap partition is formatted specifically for this purpose and is separate from the main system partitions.
Traditional swap space is suitable for scenarios where you have a dedicated server with specific disk partitions and need a fixed amount of swap space. Using swap space is common in server environments where a portion of the storage device is allocated for swap and isolated from the rest of the filesystem.
Traditional swap spaces are also useful in performance-critical systems because they offer better performance than a swap file. Since swap space is fixed, it also provides predictable behavior, which is an advantage when you must ensure a specific amount of swap is always available.
2. Swap File
A swap file is a file on the filesystem that the OS uses as swap space. Swap files offer more flexibility because users can create, resize, or remove the file without having to perform disk repartitioning.
In Linux, there are two types of swap files:
- Temporary swap file. It typically uses fragmented disk space and doesn’t reserve a part of the hard drive, making it suitable for limited disk space.
- Permanent swap file. It takes up a contiguous section of the hard drive, meaning it needs more disk space than a temporary swap file. The advantage of using a permanent swap file is that it requires fewer I/O operations, which makes it less resource-intensive than a temporary swap file.
Swap files are often easier to manage than traditional swap spaces, and they can even be placed on different storage devices, which provides greater control over swap space management. Their flexibility makes them great for scenarios with limited disk space.
Lastly, swap files are particularly advantageous for virtualized environments. Virtual machines often have dynamic memory requirements, and swap files allow users to easily adjust swap space without altering the underlying disk setup.
Swap Space vs. Virtual Memory
Swap space and virtual memory are related concepts in the context of OS memory management. However, they serve different purposes, and each has distinct characteristics.
Virtual memory in a system represents a combination of RAM and the swap space on a disk. This combined resource allows running processes to utilize it effectively. This memory type encompasses various memory management strategies and enables processes to use more memory than is physically available.
Virtual memory allows the OS to efficiently share physical memory among multiple processes, including paging, swapping, and memory mapping.
The following illustration shows how the OS uses virtual memory:
Thus, swap space is a part of the virtual memory on the hard drive, which the system uses when physical memory (RAM) is full. It supplements physical RAM, enabling the system to continue functioning when there is no more free RAM.
Swap space is a last resort when the physical RAM is fully utilized. The operating system moves less frequently used data from RAM to the swap space to free up memory for currently active tasks.
How Does Swap Space Work?
Swap space works by utilizing a part of the hard drive to temporarily store data that would normally be in the computer’s physical memory (RAM). This data ends up on the hard drive because the running programs fully use up the available RAM. Therefore, the OS moves some data from RAM to the swap space to free up space for new data. This process is known as paging out or swapping out, and it prevents the system from running out of memory.
However, accessing data stored in the swap space is slower than accessing it from RAM, impacting overall system performance. When the data in swap space is needed again, the operating system moves it back to RAM in a process called swapping in.
The swap space size is usually configured during system installation or by the swap file, and it plays a significant role in overall system performance.
Benefits of Using Swap Space
Using swap space provides multiple advantages. Some of them are:
- Preventing Memory-Related Crashes. Swap space prevents the system from crashing or becoming unresponsive when RAM becomes unavailable.
- Memory Overcommitment. Swap space enables memory overcommitment, where the system allocates more memory to processes than is physically available. This is useful when processes might not fully use their allocated memory.
- Large Programs and Multitasking Support. Swap space enables running large or multiple programs simultaneously, even when the available physical RAM is limited. This is especially helpful for systems with resource-intensive applications or with extensive multitasking.
- Improving Stability. Swap space allows the OS to continue functioning when there isn’t enough RAM for all processes. This prevents abrupt crashes, improves system stability, and allows users to close applications and save their work.
- Flexibility. When using swap files, users can adjust the swap space size according to the system’s needs. This allows users to tune the balance between physical RAM and swap space based on specific workloads and hardware configuration, leading to better overall performance.
- Virtual Memory Management. Swap space is a core component of virtual memory management. It allows the OS to provide the illusion of having abundant memory for applications, even when physical RAM is limited.
- Resource Allocation. Swap space helps optimize resource allocation by moving less frequently used data to the slower swap space while more frequently used data remains in RAM. Allocating resources in such a way helps manage memory efficiently.
Although swap space offers many advantages, relying heavily on it leads to degraded performance, as accessing data stored on a hard drive is slower compared to RAM. Therefore, balancing swap space with an appropriate amount of physical RAM is the best way to ensure optimal system performance.
Challenges of Using Swap Space
While swap space provides benefits, it also comes with some potential drawbacks and challenges, such as:
- Performance Degradation. Accessing data from swap space on a hard drive or SSD is significantly slower than accessing data from RAM. Thus, relying heavily on swap space can lead to performance degradation as processes wait longer while fetching data from slower storage.
- Hard Drive Wear. Using swap space frequently on a hard drive contributes to increased wear and reduces the device’s lifespan. Additionally, SSDs have limited write cycles, and excessive swapping can wear out the drive more quickly.
- Resource Conflicts. When the OS uses swap space actively, it competes for resources with other I/O operations on the drive. This can lead to conflicts and cause an overall system slowdown.
- Reduced Disk Space. Swap space takes up a portion of the hard drive, resulting in less disk space available to the user. This can be especially challenging with permanent swap partitions, which cannot be changed after partitioning the disk.
- Complex Memory Management. While swap space helps manage memory efficiently, configuring and tuning it for optimal system performance introduces complexity.
- Security Considerations. Placing sensitive data in swap space could potentially lead to unauthorized access if proper encryption and management measures are not in place.
How Much Swap Space Do You Need?
It was a common belief that swap space should be double the amount of RAM. However, such a setup isn’t always applicable in modern systems. The required swap space depends on several factors, such as RAM and workload size, hibernation support, hard drive type and speed, etc.
Additionally, swap size recommendations differ for each Linux distribution. The following guidelines outline the recommendations for RedHat, CentOS, Ubuntu, and Debian:
RedHat suggests a swap space size of 20% of the total available RAM in the system. The recommendation applies to modern systems with at least 4GB of RAM.
CentOS suggests to follow the following guidelines:
- Swap space should be twice the size of RAM in case the RAM amount is below 2 GB.
- If RAM amounts to more than 2 GB, then swap space should be the size of RAM + 2 GB. For example, 6GB of swap for 4GB of RAM.
Ubuntu’s recommendations take hibernation into account when determining the swap space size. If you use hibernation, the swap space size should equal the amount of RAM plus the square root of the RAM amount.
If you don’t need hibernation:
- If there is less than 1GB of RAM, the swap size should be at least the amount of RAM and, at most, double the amount of RAM.
- If there is more than 1GB of RAM, the swap size should be at least the square root of the RAM amount and, at most, double the RAM amount.
How to Check Swap Space
There are several different ways to check Linux swap space size and usage. Choose one of the methods in the following sections.
Use swapon Command
swapon command activates a swap partition in a specified device, but it can also show the details about an existing swap space. Follow the steps below:
1. Open a terminal window (Ctrl + Alt + T).
2. Run the following command:
The command outputs the path to the swap file, the type of swap space (either partition or file), its size, and the amount of it that’s currently being used. The Priority column determines in which order to use swap devices when swapping data.
Check /proc/swaps File
The /proc/swaps file measures swap space and its utilization. Use the cat command to view the file and see which swap areas are in use on your system:
The command outputs the same parameters as the
Use free Command
The free command in Linux is a utility that provides information about the system’s memory usage, including virtual memory. Run the following command to see RAM and swap space usage in Linux:
The command outputs details about RAM and swap space, including the total size, amount currently in use, free memory, etc.
Use top or htop Command
The Linux top command shows the usage of the system’s vital resources in real time. The
htop command is an alternative to
top and provides a more user-friendly interface. Use
htop to see swap space utilization in Linux.
Follow the steps below:
1. Enter one of the two commands, for example:
2. Press Shift+O keys to open the “Order By” prompt.
3. Type VIRT (virtual memory usage) and press Enter.
The command sorts the processes by virtual memory usage, which includes both RAM and swap space.
How to Increase/Decrease Swap Space
Changing swap space size involves different methods for temporary changes (swap space for the current session) and permanent changes (which survive reboots).
Important: Increasing the size of an existing permanent swap space might not always be straightforward or possible. This depends on the filesystem structure and other factors.
Follow the steps below to resize a swap partition to increase swap space in Linux:
1. Check existing swap space.
Use any of the above methods to check the current swap space and identify the swap partition. For example, we will use the
2. Turn off the swap.
Before resizing, disable the swap space with the following syntax:
sudo swapoff -v /[swap_path]
[swap_path] with the partition path. For example:
3. Resize the partition.
After disabling the swap space, use a partitioning utility such as fdisk or parted to shrink or expand the swap partition.
Note: For more information on how to use disk partitioning utilities, check out our guide on how to create a partition in Linux.
4. Update the partition table.
After resizing the swap partition, update the partition table using the following syntax:
sudo mkswap /[swap_path]
[swap_path] with the appropriate partition path.
5. Enable the swap space.
Enable the resized swap space using the following syntax:
sudo swapon /[swap_path]
[swap_path] with the appropriate partition path.
Increasing the size of an existing swap partition might not be possible if it already occupies the maximum available space on your storage device or if there are adjacent partitions.
In such situations, a better solution is to create a new swap file and delete the previous one. Ensure to have backups and consider the implications of changing swap space, especially in permanent changes.
This article has explained swap space in Linux, its types, and its benefits and drawbacks. The guide also provided instructions for checking your swap space and, if needed, increasing or decreasing it.
Đăng ký liền tay Nhận Ngay Bài Mới
Cám ơn bạn đã đăng ký !
Lỗi đăng ký !