linux

Swap Space And Swap File: Linux Virtual Memory Guide

Your operating system runs out of physical memory faster than you'd expect. When RAM fills up, your system needs a fallback to keep running without crashing. That fallback is virtual memory, managed t

Swap Space And Swap File: Linux Virtual Memory Guide
In this story

Your operating system runs out of physical memory faster than you'd expect. When RAM fills up, your system needs a fallback to keep running without crashing. That fallback is virtual memory, managed through swap space and swap files.

Understanding how your system handles overflow memory prevents unexpected crashes and severe performance slowdowns. Let's break down how swap space works, the difference between partitions and files, and how to configure them for optimal system stability.

What Is Virtual Memory and Swap?

Physical RAM is fast, but it's also limited. When you open heavy applications, browser tabs, and background services, your system eventually exhausts its physical RAM modules.

Virtual memory combines your physical RAM with disk storage. When RAM runs low, the kernel moves inactive memory pages out of RAM and onto secondary storage. This process frees up RAM for active tasks.

[ Active Processes ] ---> [ Physical RAM ]
                                | (RAM Full)
                                v
                         [ Swap Space / File ] (Disk Storage)

The reserved storage area used for this overflow is called swap. Without swap, your operating system would trigger the Out-Of-Memory (OOM) killer and terminate your running applications the moment RAM hits 100%.

The Difference Between Swap Space and Swap Files

People often use these terms interchangeably, but they refer to different implementation methods on Linux systems.

  • Swap Partition: A dedicated, standalone slice of your physical hard drive or SSD formatted specifically for swapping. It operates independently of any filesystem.
  • Swap File: A normal file living inside an existing filesystem (like ext4 or XFS) that the kernel treats as swap space.

Historically, swap partitions offered better raw performance because the kernel could write directly to raw disk blocks. Modern filesystems have largely closed that performance gap. Swap files are now the preferred default for most distributions because you can resize, move, or delete them without repartitioning your drives.

How the Linux Kernel Manages Swapping

The kernel doesn't wait until RAM is completely full to start swapping. It uses a background mechanism to evaluate memory pages continuously.

Memory pages fall into two categories:

  • Anonymous memory: Data generated by running programs, such as variables in a Python script or user input in a text editor. This data has no file backing, meaning it must go to swap if evicted from RAM.
  • File-backed memory: Data read directly from files on disk, like binaries or cached documents. The kernel can simply drop these pages and reload them from the original file later if needed, avoiding disk writes.

Understanding Swappiness

The kernel parameter swappiness controls how aggressively your system moves anonymous memory to swap. You can check your current swappiness value in Linux by running:

cat /proc/sys/vm/swappiness

The value ranges from 0 to 100:

  • 0: The kernel avoids swapping as much as possible, only swapping when RAM is nearly exhausted and the OOM killer is imminent.
  • 60: The default setting on many Linux distributions, balancing RAM preservation and swap usage.
  • 100: The kernel aggressively swaps out anonymous memory early.

If you run a database server with 64GB of RAM, you usually want a low swappiness value (like 10) to keep active queries cached in fast RAM. If you run a desktop workstation with moderate RAM, the default of 60 works well.

Creating and Managing a Swap File

If your Linux installation didn't create enough swap space during setup, you can easily add a swap file. Here is how to set up a 2GB swap file on a modern Linux distribution like Ubuntu.

Step 1: Allocate the Space

Use the fallocate command to create a file of your desired size. For a 2GB file:

sudo fallocate -l 2G /swapfile

If your filesystem doesn't support fallocate (like older XFS setups), use dd instead:

sudo dd if=/dev/zero of=/swapfile bs=1M count=2048

Step 2: Set Secure Permissions

A swap file contains raw memory dumps from running programs, including potential passwords or encryption keys. Lock down permissions immediately so only the root user can read it:

sudo chmod 600 /swapfile

Step 3: Format and Enable the Swap File

Mark the file as swap space using mkswap:

sudo mkswap /swapfile

Activate the swap file immediately:

sudo swapon /swapfile

Verify that the system recognizes the new swap space:

sudo swapon --show

Step 4: Make the Swap File Permanent

To ensure your system enables the swap file automatically after a reboot, add an entry to your filesystem table. Open /etc/fstab with a text editor and append this line:

/swapfile none swap sw 0 0

Swap Space Sizing Best Practices

Choosing the right amount of swap depends heavily on your system's total RAM and your specific workload.

Total RAM Recommended Swap Use Case
2 GB 2 GB to 4 GB Low-memory servers, lightweight containers
8 GB 4 GB to 8 GB Standard desktop workstations, development machines
16 GB 8 GB Heavy multitasking, moderate virtualization
64 GB+ 4 GB to 8 GB High-performance databases, large build servers

Older guidelines suggested making swap twice the size of your RAM. On modern servers with 128GB of RAM, allocating 256GB of swap wastes valuable disk space and rarely improves performance.

Hibernation Requirements

The only major exception to modern sizing rules is system hibernation. When your laptop or workstation hibernates, the kernel writes the entire contents of physical RAM into swap space before powering down.

If you want to use hibernation, your swap space or swap file must be at least as large as your physical RAM, plus an extra buffer for active kernel processes. For detailed guidance on kernel memory management, check the Red Hat Enterprise Linux Documentation.

Common Misconceptions and Performance Pitfalls

Misunderstanding how swap works leads to common administrative errors.

  • Swap speeds up your computer: False. Swap is drastically slower than physical RAM. If your system is constantly swapping (thrashing), your hard drive will bottleneck performance. Swap prevents crashes; it doesn't make slow hardware faster.
  • SSDs wear out instantly with swap: While write endurance was a concern for early solid-state drives, modern enterprise and consumer Solid State Drives handle heavy write cycles easily. Swap won't destroy a modern SSD under normal usage.
  • Disabling swap improves speed: Turning off swap entirely on a system with limited RAM only guarantees that heavy tasks will trigger sudden application terminations.

Frequently Asked Questions

How do I check current swap usage on Linux?

Run the free -h command in your terminal. It displays total physical RAM, used RAM, and total swap space alongside available free memory in a human-readable format. You can also use htop or top for real-time monitoring of swap consumption per process.

Can I have multiple swap files active at the same time?

Yes. Linux allows you to activate multiple swap files and partitions simultaneously. The kernel assigns a priority value to each swap area. It uses the highest priority swap space first before moving on to lower priority areas.

How do I safely delete an old swap file?

First, deactivate the swap file by running sudo swapoff /swapfile. Next, remove the entry you added to /etc/fstab. Finally, delete the file from your disk using sudo rm /swapfile.

What is swap thrashing and how do I fix it?

Swap thrashing occurs when your system spends more time moving memory pages back and forth between RAM and disk than it does running actual applications. Your system freezes up entirely. Fix thrashing by adding more physical RAM, closing heavy applications, or adjusting your swappiness value downward if you have plenty of unused RAM.

CR

Written by

Chloe Ramirez

Chloe Ramirez excels at making complicated information accessible, turning dense research into clear narratives that engage diverse audiences.

More from linux