OS Notes
Swap space management — purpose of swap, swap allocation strategies, swap file vs partition, performance implications, and how the OS uses swap to extend virtual memory beyond physical RAM.
Introduction
Swap space is an area on secondary storage (disk) that the operating system uses as an extension of physical RAM. When the system runs low on physical memory, the OS moves less-used pages from RAM to swap space — a process called "swapping out" or "paging out." When those pages are needed again, they are loaded back from swap — "swapping in" or "paging in."
Think of swap space like overflow parking for a busy mall. The main parking lot (RAM) has limited spots. When full, cars (pages) that have been parked the longest without being used are moved to a remote lot (swap). When their owners return, the cars are brought back to the main lot — which takes longer but prevents the mall from refusing new visitors entirely.
Why Swap Space Exists
Problem: Physical RAM is Limited and Expensive
A system with 8GB RAM running multiple applications might need 12GB total. Without swap, the system must either refuse to start new programs or kill existing ones. With swap, the OS moves inactive pages to disk, freeing RAM for active work.
Benefits of Swap
- Support processes larger than RAM: A single process can use more virtual memory than physical RAM available
- Handle memory spikes: Temporary peaks in memory usage do not cause crashes
- Efficient RAM utilization: Rarely-used pages (e.g., startup initialization code) moved to swap, freeing RAM for active data
- Enable hibernation: System state (entire RAM contents) written to swap for later restoration
- Memory overcommit: Linux can promise more memory than physically available, relying on not all allocations being fully used simultaneously
Swap Location: Partition vs. File
Swap Partition
A dedicated disk partition used exclusively as swap space:
# Create swap partition (using fdisk/gdisk to create partition, type 82)
mkswap /dev/sda2
swapon /dev/sda2
# Add to /etc/fstab for persistence
/dev/sda2 none swap sw 0 0Advantages: Slightly faster (no filesystem overhead), guaranteed contiguous space. Disadvantages: Fixed size (must repartition to change), must be set up during installation.
Swap File
A regular file on an existing filesystem designated as swap space:
# Create a 4GB swap file
dd if=/dev/zero of=/swapfile bs=1M count=4096
# Or (faster):
fallocate -l 4G /swapfile
chmod 600 /swapfile # Security: only root should access
mkswap /swapfile
swapon /swapfile
# Add to /etc/fstab
/swapfile none swap sw 0 0Advantages: Easy to resize (create new, delete old), no repartitioning needed, flexible. Disadvantages: Slight overhead from filesystem layer, possible fragmentation.
Modern Linux (4.0+) handles swap files nearly as efficiently as partitions.
Swap Allocation Strategies
How Pages are Selected for Swapping
The OS uses page replacement algorithms (LRU approximation via the clock algorithm) to choose which pages to swap out:
- Anonymous pages: Process data (heap, stack) that has no file backing — must go to swap when evicted
- File-backed pages (page cache): Can be discarded and re-read from the original file — no swap needed
- Dirty file pages: Modified cached file data — must be written back to the file before eviction
Linux Swappiness
The swappiness parameter (0-100) controls the kernel's tendency to swap out anonymous pages vs. dropping file cache:
# View current swappiness (default: 60)
cat /proc/sys/vm/swappiness
# Lower value = prefer keeping anonymous pages in RAM (drop file cache instead)
# Higher value = more willing to swap out anonymous pages
# For database servers (keep data in RAM):
echo 10 > /proc/sys/vm/swappiness
# For general desktops:
echo 60 > /proc/sys/vm/swappiness
# Permanent setting in /etc/sysctl.conf
vm.swappiness = 10Swap Priority
When multiple swap devices exist, priority determines which is used first:
swapon -p 10 /dev/ssd_swap # Higher priority, used first (SSD — faster)
swapon -p 5 /dev/hdd_swap # Lower priority, used when SSD swap is full
# View active swap devices
swapon --show
# NAME TYPE SIZE USED PRIO
# /dev/sda2 partition 4G 1.2G 5
# /swapfile file 2G 0B 10Performance Implications
The Swap Death Spiral
When the system uses swap heavily, performance degrades dramatically:
| Normal operation: Application accesses RAM | ~100 nanoseconds |
| With swap: Application accesses swapped page | page fault → |
| read from disk | 5-15 milliseconds (HDD) or 50-200μs (SSD) |
Thrashing: When the working set exceeds available RAM, the system constantly swaps pages in and out. CPU utilization drops (processes waiting for I/O), disk utilization hits 100%, and the system becomes essentially unusable.
How Much Swap to Allocate
| System RAM | Recommended Swap | With Hibernation |
|---|---|---|
| ≤ 2 GB | 2× RAM | 3× RAM |
| 2-8 GB | Equal to RAM | 2× RAM |
| 8-64 GB | ≥ 4 GB | RAM + 2 GB |
| > 64 GB | ≥ 4 GB (or none) | Not practical |
For servers with abundant RAM, swap serves as an emergency buffer rather than regular overflow. Some administrators disable swap entirely for latency-sensitive services (databases, real-time systems) and rely on memory limits to prevent overcommit.
Swap in Different Operating Systems
Linux
- Supports swap partitions and swap files
- Multiple swap devices with priorities
- zswap: Compressed swap cache in RAM (pages compressed before going to disk)
- zram: RAM-based compressed block device used as swap (no disk I/O)
# zram swap: Compress pages in RAM instead of writing to disk
# Trades CPU cycles for avoiding slow disk I/O
modprobe zram
echo lz4 > /sys/block/zram0/comp_algorithm
echo 2G > /sys/block/zram0/disksize
mkswap /dev/zram0
swapon /dev/zram0Windows
- Uses a page file (pagefile.sys) — essentially a swap file
- System-managed or fixed size
- Located on the system drive by default (can be moved to faster drive)
macOS
- Uses swap files in /private/var/vm/
- Compressed memory (since macOS Mavericks) — similar to Linux zswap
- Dynamic sizing based on pressure
Monitoring Swap Usage
Key Takeaways
- Swap extends virtual memory by using disk space as RAM overflow
- Pages selected for swapping are typically least-recently-used anonymous pages
- Swap files are nearly as fast as partitions in modern Linux and easier to manage
- Heavy swap usage indicates insufficient RAM — it is an emergency measure, not a performance feature
- Swappiness controls the balance between evicting anonymous pages vs. file cache
- zswap/zram can dramatically improve swap performance by compressing pages in RAM
- Monitor swap activity — consistent swapping means the system needs more physical memory
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Swap Space Management - Virtual Memory.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Operating Systems topic.
Search Terms
operating-systems, operating systems, operating, systems, storage, management, swap, space
Related Operating Systems Topics