BLOG POSTS
How to Add Swap Space on Ubuntu 24

How to Add Swap Space on Ubuntu 24

Managing server memory effectively is crucial for optimal system performance, especially when dealing with resource-intensive applications or unexpected memory spikes. Adding swap space on Ubuntu 24 serves as a safety net, providing virtual memory when physical RAM is exhausted and preventing system crashes or out-of-memory errors. In this comprehensive guide, you’ll learn how to create, configure, and optimize swap space on Ubuntu 24, understand the performance implications, and discover best practices for different server environments.

Understanding Swap Space and How It Works

Swap space acts as an extension of your system’s physical memory by using disk storage to temporarily hold data that would normally reside in RAM. When your system runs low on physical memory, the kernel moves less frequently accessed memory pages to swap space, freeing up RAM for active processes. While swap is significantly slower than RAM, it prevents system crashes and provides breathing room during memory-intensive operations.

Ubuntu 24 uses the kernel’s memory management system to automatically handle swap operations through a process called paging. The system monitors memory usage and uses algorithms to determine which memory pages should be moved to swap based on access patterns and priority levels. The swappiness parameter controls how aggressively the kernel uses swap space, with values ranging from 0 to 100.

Step-by-Step Swap Space Implementation

Before adding swap space, check your current memory and swap status to understand your system’s needs:

free -h
swapon --show
df -h

The most flexible approach is creating a swap file rather than a dedicated partition. Here’s the complete process for adding a 2GB swap file:

# Create a 2GB swap file
sudo fallocate -l 2G /swapfile

# Alternative method if fallocate isn't available
# sudo dd if=/dev/zero of=/swapfile bs=1024 count=2097152

# Set correct permissions (critical for security)
sudo chmod 600 /swapfile

# Set up the swap area
sudo mkswap /swapfile

# Enable the swap file
sudo swapon /swapfile

# Verify the swap is active
free -h
swapon --show

To make the swap permanent across reboots, add it to the fstab file:

# Backup the current fstab
sudo cp /etc/fstab /etc/fstab.bak

# Add swap entry to fstab
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

Swap Configuration and Optimization

The swappiness parameter significantly impacts system performance. You can check and modify it using these commands:

# Check current swappiness value
cat /proc/sys/vm/swappiness

# Temporarily change swappiness
sudo sysctl vm.swappiness=10

# Make swappiness change permanent
echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf

Here’s how different swappiness values affect system behavior:

Swappiness Value Behavior Best Use Case
0 Avoid swapping except to prevent OOM High-performance databases
1-10 Minimal swapping, prefer RAM Production servers with adequate RAM
60 (default) Balanced approach General-purpose systems
80-100 Aggressive swapping Systems with limited RAM

Another important parameter is vfs_cache_pressure, which controls how aggressively the kernel reclaims memory used for caching:

# Check current cache pressure
cat /proc/sys/vm/vfs_cache_pressure

# Optimize for better cache retention
echo 'vm.vfs_cache_pressure=50' | sudo tee -a /etc/sysctl.conf

Real-World Use Cases and Performance Considerations

Different server environments require different swap strategies. For VPS environments running web applications, a swap size equal to 50-100% of RAM typically provides good protection against memory spikes during traffic surges. Database servers often benefit from minimal swap to prevent performance degradation when large datasets are involved.

Here’s a practical example for a web server running multiple applications:

# Monitor memory usage patterns
vmstat 1 10

# Check which processes are using swap
for file in /proc/*/status ; do 
    awk '/VmSwap|Name/{printf $2 " " $3}END{ print ""}' $file
done | sort -k 2 -n -r | head -10

For dedicated servers handling high-performance computing tasks, you might want to create multiple swap files on different storage devices for improved I/O performance:

# Create swap files on different devices
sudo fallocate -l 1G /mnt/ssd1/swapfile1
sudo fallocate -l 1G /mnt/ssd2/swapfile2

# Configure both with different priorities
sudo mkswap /mnt/ssd1/swapfile1
sudo mkswap /mnt/ssd2/swapfile2

# Enable with priority settings
sudo swapon -p 10 /mnt/ssd1/swapfile1
sudo swapon -p 5 /mnt/ssd2/swapfile2

Monitoring and Troubleshooting Swap Performance

Regular monitoring helps identify swap-related performance issues before they impact your applications. Use these tools to track swap usage patterns:

# Detailed swap information
cat /proc/swaps

# Real-time swap monitoring
watch -n 1 'free -h && echo && swapon -s'

# Check swap I/O statistics
iostat -x 1

# Monitor swap-related kernel parameters
sysctl vm.swappiness vm.vfs_cache_pressure vm.dirty_ratio

Common issues and their solutions:

  • High swap usage with available RAM: Reduce swappiness value or check for memory leaks in applications
  • Slow system performance: Monitor swap I/O and consider faster storage or more RAM
  • Swap file creation fails: Check available disk space and filesystem compatibility
  • Permission errors: Ensure swap file has 600 permissions and correct ownership

Swap Space Sizing and Best Practices

Choosing the right swap size depends on your specific use case and system resources. Here are evidence-based recommendations:

RAM Size Recommended Swap (No Hibernation) With Hibernation High Memory Usage
≀ 2GB 2x RAM 3x RAM 2-4x RAM
2-8GB Equal to RAM 2x RAM 1-2x RAM
8-64GB 4-8GB RAM + 8GB 0.5-1x RAM
> 64GB 4GB minimum RAM + 4GB 4-32GB

Security considerations for swap space include:

  • Always set swap file permissions to 600 to prevent unauthorized access
  • Consider encrypted swap for sensitive data using cryptsetup
  • Monitor swap usage for potential information disclosure
  • Disable swap on systems handling highly sensitive data if RAM is sufficient

For encrypted swap setup:

# Install cryptsetup if not available
sudo apt update && sudo apt install cryptsetup

# Create encrypted swap
sudo swapoff /swapfile
echo "cryptswap /swapfile /dev/urandom swap,cipher=aes-xts-plain64,size=256" | sudo tee -a /etc/crypttab

Advanced Swap Management Techniques

For production environments, consider implementing swap management automation and monitoring. Here’s a script to dynamically adjust swap based on memory pressure:

#!/bin/bash
# Dynamic swap management script

MEMORY_THRESHOLD=80
CURRENT_USAGE=$(free | awk 'FNR==2{printf "%.0f", $3/($3+$4)*100}')

if [ $CURRENT_USAGE -gt $MEMORY_THRESHOLD ]; then
    echo "Memory usage high: ${CURRENT_USAGE}%"
    # Temporarily increase swappiness
    echo 20 | sudo tee /proc/sys/vm/swappiness
else
    # Normal swappiness
    echo 10 | sudo tee /proc/sys/vm/swappiness
fi

You can also use zswap, a compressed cache for swap pages, which can improve performance on systems with fast CPUs:

# Enable zswap
echo 1 | sudo tee /sys/module/zswap/parameters/enabled

# Configure zswap parameters
echo lz4 | sudo tee /sys/module/zswap/parameters/compressor
echo z3fold | sudo tee /sys/module/zswap/parameters/zpool

# Make permanent by adding to kernel boot parameters
sudo sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="/&zswap.enabled=1 zswap.compressor=lz4 /' /etc/default/grub
sudo update-grub

Understanding swap space management is essential for maintaining stable and performant Ubuntu 24 systems. Whether you’re running lightweight applications or memory-intensive workloads, proper swap configuration provides a crucial safety net while optimizing system resources. Regular monitoring and adjustment of swap parameters ensure your system continues to perform optimally as requirements change.

For additional information on memory management and system optimization, refer to the official Linux kernel documentation and the Ubuntu community swap FAQ.



This article incorporates information and material from various online sources. We acknowledge and appreciate the work of all original authors, publishers, and websites. While every effort has been made to appropriately credit the source material, any unintentional oversight or omission does not constitute a copyright infringement. All trademarks, logos, and images mentioned are the property of their respective owners. If you believe that any content used in this article infringes upon your copyright, please contact us immediately for review and prompt action.

This article is intended for informational and educational purposes only and does not infringe on the rights of the copyright owners. If any copyrighted material has been used without proper credit or in violation of copyright laws, it is unintentional and we will rectify it promptly upon notification. Please note that the republishing, redistribution, or reproduction of part or all of the contents in any form is prohibited without express written permission from the author and website owner. For permissions or further inquiries, please contact us.

Leave a reply

Your email address will not be published. Required fields are marked