News & Updates

How Swap Works in Linux and Why It Matters

By Dominic Hawke 11 min read 2715 views

How Swap Works in Linux and Why It Matters

What Exactly Is Swap?

Swap is a designated area of storage that the Linux kernel uses when physical RAM runs low. Think of it as an overflow parking lot for data that can’t fit in memory at the moment. It isn’t a replacement for RAM, but a safety net that lets the system stay responsive when demand spikes.

There are two common formats: a dedicated swap partition and a swap file placed on an existing filesystem. Both serve the same purpose; the choice often depends on how the system was initially set up.

Why Does Linux Need Swap?

Even the most generous RAM configurations can be exceeded, especially on servers handling many concurrent processes or on desktops with heavy multitasking. When RAM is exhausted, the kernel starts moving the least‑used pages to swap. This frees up RAM for active tasks and prevents the dreaded “out of memory” (OOM) killer from terminating processes abruptly.

  • Stability: Applications keep running instead of crashing.
  • Flexibility: You can run more programs than the physical memory would otherwise allow.
  • Hibernation support: Some distributions require swap to store the system state.

How Does the Kernel Choose What to Move?

The Linux memory manager constantly ranks pages by how recently they were accessed. Pages that haven’t been touched in a while become candidates for swapping. The algorithm isn’t a simple “oldest first” rule; it also considers the cost of writing to storage, which is why fast SSDs make swap feel less painful.

When a page is needed again, the kernel pulls it back into RAM, potentially swapping something else out in the process. This back‑and‑forth can introduce a slight lag, especially if the underlying storage is slow.

Setting Up Swap: Partition vs. File

Creating a swap partition is a bit of a legacy practice. It requires allocating a separate chunk of the disk during installation, and resizing it later can be cumbersome. A swap file, on the other hand, is just a regular file that you tell the kernel to treat as swap space.

To create a 2 GB swap file, you might run:

sudo fallocate -l 2G /swapfile

sudo chmod 600 /swapfile

sudo mkswap /swapfile

sudo swapon /swapfile

After that, add an entry to /etc/fstab so the swap persists across reboots. The steps are straightforward, and you can adjust the size later without repartitioning.

How Much Swap Should You Allocate?

There’s no one‑size‑fits‑all answer. Historically, the rule of thumb was “twice the RAM,” but that made sense when computers had only a few hundred megabytes. Modern recommendations are more nuanced:

  • If you have less than 4 GB of RAM, allocate at least the same amount in swap.
  • For systems with 8 GB – 16 GB of RAM, a 2 GB to 4 GB swap file usually suffices.
  • When you plan to use hibernation, match swap size to total RAM (plus a small cushion).

Ultimately, monitor your system’s memory pressure with tools like free -h or vmstat and adjust accordingly.

Performance Tips and Common Pitfalls

Swap performance hinges on the underlying storage. A mechanical HDD will make swapping feel like a noticeable pause, while an NVMe SSD reduces the impact dramatically. If you notice excessive swapping, consider these actions:

  • Increase RAM: The most effective remedy.
  • Fine‑tune swappiness: The kernel parameter vm.swappiness (0‑100) controls how eagerly it uses swap. Lower values keep data in RAM longer.
  • Use a dedicated swap partition on SSDs: Avoids fragmentation that can affect a swap file.

Beware of setting swappiness too low, though; the kernel might hold onto memory that could be better off swapped, leading to OOM situations.

Monitoring Swap Usage

Regularly checking swap helps catch misconfigurations before they become problems. The free command gives a quick snapshot:

              total        used        free      shared  buff/cache   available

Mem: 7.8Gi 5.2Gi 512Mi 256Mi 2.1Gi 2.0Gi

Swap: 2.0Gi 128Mi 1.9Gi

If the “used” column stays high for extended periods, investigate which processes are memory‑hungry. top, htop, or smem can provide deeper insight.

When to Disable Swap Entirely

In some high‑performance environments, administrators choose to run without swap, trusting that ample RAM and careful workload planning will avoid OOM scenarios. This eliminates the latency penalty entirely, but it also removes the safety net. Proceed with caution and have robust monitoring in place if you go down that route.

Bottom Line

Swap is a fundamental part of Linux memory management, offering a fallback when RAM runs out. Whether you opt for a swap file or a partition, size it sensibly, and keep an eye on swappiness, you’ll maintain a balance between performance and stability. A little extra storage can make a big difference when the system’s memory is stretched thin.

Linux Swap 介绍 - 知乎
A Step-by-Step Guide to Creating Filesystems in Linux
Linux Shared Memory and Swap Space Configuration: shmmax, shmall, and ...
How to Create a Swap File in Linux - YouTube

Written by Dominic Hawke

Dominic Hawke is a Chief Correspondent with over a decade of experience covering breaking trends, in-depth analysis, and exclusive insights.