Swap space in Linux provides virtual memory that extends physical RAM, allowing systems to handle memory-intensive workloads without crashing when RAM is fully utilized. When physical memory becomes full and applications need more memory, Linux moves inactive pages from RAM to swap space on disk. While swap is not a substitute for adequate RAM, it provides crucial breathing room for systems under memory pressure, prevents out-of-memory (OOM) kills, and enables hibernation on desktop systems. This comprehensive guide covers creating, managing, and optimizing swap partitions and files in Linux.
📑 Table of Contents
- Understanding Linux Swap Space
- What is Swap Space?
- How Swap Works
- Checking Current Swap Configuration
- View Swap Partitions and Size
- View Detailed Swap Information
- Creating Swap Space: Three Methods
- Method 1: Create Swap from Raw Disk Partition
- Method 2: Create Swap from File
- Method 3: Create Swap with LVM
- Increasing Existing Swap Space
- Add Additional Swap File
- Extend LVM Swap Logical Volume
- Managing Swap Space
- Disable Swap
- Remove Swap
- Set Swap Priority
- Swap Performance Tuning
- Swappiness Parameter
- How Much Swap Space Do You Need?
- Modern Recommendations
- Server Recommendations
- Monitoring Swap Usage
- Frequently Asked Questions
- Do I need swap if I have lots of RAM?
- Why is swap being used when I have free RAM?
- Should I use a swap partition or swap file?
- Can swap damage my SSD?
- How do I know if my system needs more swap?
- What’s the difference between swap and virtual memory?
- Can I use swap for hibernation (suspend-to-disk)?
- Should database servers use swap?
- How do I completely disable swap?
- What is zswap and should I use it?
- Conclusion
Understanding Linux Swap Space
What is Swap Space?
Swap space is disk storage used as virtual memory when physical RAM is exhausted. The Linux kernel’s memory management system moves less-frequently-used memory pages to swap, keeping active data in faster RAM. This mechanism prevents system crashes due to memory exhaustion and allows running more processes than available RAM would normally support.
How Swap Works
When RAM fills up, the kernel identifies inactive memory pages—data not recently accessed—and writes them to swap space. This process is called “swapping out.” When swapped data is needed again, it’s read back from disk into RAM (“swapping in”), potentially swapping out other inactive pages. Because disk I/O is much slower than RAM access, excessive swapping (thrashing) degrades performance significantly.
Checking Current Swap Configuration
View Swap Partitions and Size
# Display swap devices and usage
swapon -s
# Example output:
Filename Type Size Used Priority
/dev/mapper/VolGroup00-LogVol01 partition 2064376 0 -1
# Alternative: Use free command
free -m
# Example output:
total used free shared buffers cached
Mem: 1002 377 624 0 55 200
-/+ buffers/cache: 121 880
Swap: 2015 0 2015
In this example, the system has 2 GB (2015 MB) of swap space, currently unused (0 MB used).
View Detailed Swap Information
# Show swap with human-readable sizes
free -h
# Display swap usage by process
smem -s swap
# Check swap usage with top
top
# Press 'M' to sort by memory
Creating Swap Space: Three Methods
Method 1: Create Swap from Raw Disk Partition
Step 1: Create partition with fdisk
# Start fdisk
fdisk /dev/sdb
# Commands within fdisk:
n # Create new partition
p # Primary partition
1 # Partition number
# Accept default start
+1G # Size: 1 GB
t # Change partition type
82 # Linux swap type
w # Write changes and exit
Step 2: Create swap filesystem
# Make swap on the partition
mkswap /dev/sdb1
# Example output:
Setting up swapspace version 1, size = 1048572 KiB
no label, UUID=a1b2c3d4-e5f6-7890-abcd-ef1234567890
Step 3: Enable swap
# Activate swap immediately
swapon /dev/sdb1
# Verify swap is active
swapon -s
free -h
Step 4: Make swap permanent
# Add to /etc/fstab for automatic mounting at boot
echo '/dev/sdb1 swap swap defaults 0 0' >> /etc/fstab
# Or edit /etc/fstab manually:
vim /etc/fstab
# Add line:
/dev/sdb1 swap swap defaults 0 0
Method 2: Create Swap from File
Swap files are more flexible than partitions—easier to create, resize, and remove without repartitioning.
Step 1: Create swap file
# Create 1 GB swap file using dd
dd if=/dev/zero of=/swapfile bs=1M count=1024
# Or use fallocate (faster)
fallocate -l 1G /swapfile
# Set correct permissions (security requirement)
chmod 600 /swapfile
Step 2: Make it a swap file
# Set up swap area
mkswap /swapfile
# Output:
Setting up swapspace version 1, size = 1048572 KiB
no label, UUID=generated-uuid
Step 3: Enable swap file
# Activate swap file
swapon /swapfile
# Verify
swapon -s
free -h
Step 4: Make permanent
# Add to /etc/fstab
echo '/swapfile swap swap defaults 0 0' >> /etc/fstab
Method 3: Create Swap with LVM
LVM swap allows dynamic resizing and management through logical volume tools.
Step 1: Create logical volume for swap
# Create 1 GB swap LV
lvcreate -L 1G -n swap_lv VolGroup00
# Output:
Logical volume "swap_lv" created
Step 2: Format as swap
# Create swap on LV
mkswap /dev/VolGroup00/swap_lv
Step 3: Activate swap
# Enable swap
swapon /dev/VolGroup00/swap_lv
# Verify
swapon -s
Step 4: Add to fstab
# Make permanent
echo '/dev/mapper/VolGroup00-swap_lv swap swap defaults 0 0' >> /etc/fstab
Increasing Existing Swap Space
Add Additional Swap File
# Create second swap file
fallocate -l 2G /swapfile2
chmod 600 /swapfile2
mkswap /swapfile2
swapon /swapfile2
# Add to fstab
echo '/swapfile2 swap swap defaults 0 0' >> /etc/fstab
# Total swap is now original + 2GB
Extend LVM Swap Logical Volume
# Disable swap
swapoff /dev/VolGroup00/swap_lv
# Extend LV
lvextend -L+1G /dev/VolGroup00/swap_lv
# Recreate swap
mkswap /dev/VolGroup00/swap_lv
# Re-enable
swapon /dev/VolGroup00/swap_lv
Managing Swap Space
Disable Swap
# Disable specific swap
swapoff /swapfile
# Disable all swap
swapoff -a
# Re-enable all swap from /etc/fstab
swapon -a
Remove Swap
# Disable swap
swapoff /swapfile
# Remove from /etc/fstab
vim /etc/fstab
# Delete the swap line
# Delete swap file
rm -f /swapfile
# For partition:
swapoff /dev/sdb1
# Remove from fstab, then delete partition with fdisk
Set Swap Priority
# Higher priority swap used first
swapon -p 10 /swapfile1 # Higher priority
swapon -p 5 /swapfile2 # Lower priority
# In /etc/fstab:
/swapfile1 swap swap pri=10 0 0
/swapfile2 swap swap pri=5 0 0
Swap Performance Tuning
Swappiness Parameter
Swappiness controls how aggressively the kernel swaps memory pages (0-100):
# Check current swappiness
cat /proc/sys/vm/swappiness
# Default: 60
# Set temporarily
sysctl vm.swappiness=10
# Make permanent in /etc/sysctl.conf
echo 'vm.swappiness=10' >> /etc/sysctl.conf
# Apply changes
sysctl -p
Swappiness values:
- 0: Swap only to avoid OOM (Out of Memory)
- 10: Recommended for servers (minimal swapping)
- 60: Default balanced setting
- 100: Aggressive swapping (rarely recommended)
How Much Swap Space Do You Need?
Modern Recommendations
RAM Size | Swap Size (No Hibernation) | Swap Size (With Hibernation) |
---|---|---|
< 2 GB | 2x RAM | 3x RAM |
2-8 GB | Equal to RAM | 2x RAM |
8-64 GB | 0.5x RAM (minimum 4 GB) | 1.5x RAM |
> 64 GB | 4-8 GB minimum | RAM + 4 GB |
Server Recommendations
- Web servers: 2-4 GB swap (even with large RAM)
- Database servers: Minimal swap (databases should stay in RAM)
- General purpose: Equal to RAM up to 8 GB
- Memory-intensive apps: Monitor usage, add as needed
Monitoring Swap Usage
# Real-time swap monitoring
watch -n 1 free -h
# Swap usage by process
for file in /proc/*/status ; do awk '/VmSwap|Name/{printf $2 " " $3}END{ print ""}' $file; done | sort -k 2 -n -r | head
# Detailed swap statistics
vmstat 1 10
# I/O wait and swap activity
iostat -x 2
Frequently Asked Questions
Do I need swap if I have lots of RAM?
Yes, even systems with abundant RAM benefit from modest swap space (2-4 GB). Swap serves as emergency overflow preventing OOM crashes, enables memory overcommit for efficiency, allows the kernel to swap out rarely-used pages freeing RAM for cache, and is required for hibernation. Modern best practice recommends at least 2 GB swap regardless of RAM size for system stability.
Why is swap being used when I have free RAM?
This is normal and intentional. Linux uses swap proactively to free RAM for disk cache, swapping out inactive pages. The “swappiness” parameter controls this behavior. If you see swap usage but system performs well, it’s working as designed. Only worry if swap usage is high AND you see performance degradation (thrashing). Lower swappiness (e.g., 10) if you prefer keeping more in RAM.
Should I use a swap partition or swap file?
Swap files are generally recommended for modern systems due to flexibility—easy to create, resize, and remove without repartitioning. Performance difference between partition and file is negligible on modern filesystems and SSDs. Use swap files unless you have specific requirements for partitions. LVM swap combines benefits of both with dynamic resizing capabilities.
Can swap damage my SSD?
Swap on SSD is safe for modern drives with wear leveling and high endurance ratings. Typical swap usage generates far less writes than normal system operation. For additional SSD longevity, set swappiness to 10 to minimize swapping, use TRIM/discard on swap, and ensure adequate RAM to reduce swap reliance. Consumer SSDs easily handle years of swap usage without issues.
How do I know if my system needs more swap?
Monitor with “vmstat” and “free” commands. If swap usage consistently exceeds 80%, swap is frequently in/out (“si”/”so” columns in vmstat are high), system feels sluggish with high I/O wait, or you see OOM killer messages in logs (/var/log/messages), you need more swap or preferably more RAM. Occasional swap usage is normal; constant swapping (thrashing) indicates insufficient memory.
What’s the difference between swap and virtual memory?
Virtual memory is the entire memory management system combining RAM and swap into a unified address space. Swap is the on-disk component of virtual memory. Virtual memory provides abstraction allowing processes to use more memory than physically available; swap is the storage mechanism enabling this. All modern OSes use virtual memory; swap is the disk backing store for it.
Can I use swap for hibernation (suspend-to-disk)?
Yes, hibernation requires swap space at least equal to RAM size. When hibernating, the kernel writes RAM contents to swap and powers off. On resume, it restores RAM from swap. Configure hibernation in GRUB with “resume=/dev/swap_device” parameter. Some distributions configure this automatically; others require manual setup. Swap files work for hibernation on recent kernels (5.0+).
Should database servers use swap?
Database servers should minimize swap usage since databases rely on fast memory access. Set swappiness to 1 (not 0, to avoid OOM), configure database with appropriate memory limits, and size RAM to keep working set in memory. A small swap (2-4 GB) prevents OOM crashes but databases swapping indicates insufficient RAM, causing severe performance degradation. Databases and swap don’t mix well—add RAM instead.
How do I completely disable swap?
Run “swapoff -a” to disable immediately, comment out or remove swap entries from /etc/fstab, reboot to verify swap remains disabled. Check with “free -h” (swap should show 0). Disabling swap is generally inadvisable—even small swap prevents OOM kills. If you must disable it, ensure ample RAM (2-3x your usage) to prevent crashes during memory spikes.
What is zswap and should I use it?
Zswap is compressed swap in RAM—pages are compressed before swapping to disk, reducing disk I/O. It acts as a cache between RAM and disk swap, improving performance when swapping occurs. Enable with “zswap.enabled=1” kernel parameter. Zswap is beneficial for systems with limited RAM that swap frequently, reducing the performance penalty of disk swap. Not needed on systems that rarely swap.
Conclusion
Swap space remains essential for Linux system stability and performance, even on modern systems with abundant RAM. Whether using traditional swap partitions, flexible swap files, or dynamic LVM swap volumes, properly configured swap prevents out-of-memory crashes, enables memory overcommit optimization, and provides a safety buffer for memory-intensive workloads. By understanding the three methods of swap creation, tuning swappiness parameters, and monitoring swap usage, administrators can optimize their systems for reliability and performance across diverse workloads.
Was this article helpful?