Insufficient Memory in Linux Servers?
“Insufficient Memory” in Lower-Spec Servers is a Nightmare Every Server Administrator May Encounter
When an application suddenly requires more memory, or when the system load surges, physical memory (RAM) can quickly be exhausted. This leads to a sharp decline in system performance and may even trigger the OOM (Out of Memory) Killer process, forcibly terminating critical applications.
At this point, Swap space acts like an emergency “airbag”—it’s not real physical memory but a special area reserved on the hard disk to temporarily store inactive memory pages when RAM is insufficient. Although Swap read/write speeds are far inferior to RAM (especially when using traditional hard disk drives), it can effectively prevent the system from crashing due to memory exhaustion, buying valuable time to resolve the underlying issue.
This tutorial will cover the working principles of Swap, configuration methods, and optimization techniques:
- Establishing Swap for a server
- Reasonably adjusting the size of existing Swap space
- Optimizing Swap usage policies to balance performance and stability
- Monitoring Swap usage to identify memory issues promptly
Whether you are a system administrator managing a production environment or a developer looking to optimize a personal Linux device, mastering Swap management is an essential skill. Let’s get started!
What is Swap?
Swap (swap space) is a virtual memory technology in Linux systems. When physical memory (RAM) is insufficient, the system temporarily stores part of the data from memory to a Swap partition or Swap file on the hard disk, freeing up RAM space for other processes to use.
Check Current Swap Usage
Before starting to manage Swap, check the system’s current Swap status:
sudo swapon --show
free -h
cat /proc/swapsThese commands will display:
- Activated Swap devices/files
- Total Swap space and usage
- Overall memory and Swap usage
Create a Swap File (When No Swap Partition Exists)
If the system does not have a Swap partition, you can create a Swap file:
- Create an empty file (here, creating a 4GB Swap file):
sudo fallocate -l 4G /swapfileIf fallocate is not available, you can use:
sudo dd if=/dev/zero of=/swapfile bs=1M count=4096- Set the correct permissions:
sudo chmod 600 /swapfile- Format it as a Swap file:
sudo mkswap /swapfile- Enable the Swap file:
sudo swapon /swapfile- Make the configuration permanent (automatically mounted after system reboot):
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstabAdjust Swap Usage Tendency
The Linux kernel parameter swappiness controls the system’s tendency to use Swap, with a value range of 0-100:
- 0: Avoid using Swap as much as possible
- 100: Aggressively use Swap
Check the current value:
cat /proc/sys/vm/swappinessTemporary modification (invalid after reboot):
sudo sysctl vm.swappiness=10Permanent modification:
echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf
sudo sysctl -pAdjust Swap Space Size
Increase Swap Space
- Disable the current Swap:
sudo swapoff /swapfile- Adjust the file size (e.g., increase to 8GB):
sudo fallocate -l 8G /swapfile- Reformat and enable:
sudo mkswap /swapfile
sudo swapon /swapfileDecrease Swap Space
- Disable Swap:
sudo swapoff /swapfile- Shrink the file (e.g., reduce to 2GB):
sudo truncate -s 2G /swapfile- Reformat and enable:
sudo mkswap /swapfile
sudo swapon /swapfileDelete a Swap File
If the Swap file is no longer needed:
- Disable Swap:
sudo swapoff /swapfile- Remove the relevant line from
/etc/fstab - Delete the file:
sudo rm /swapfileUsing Multiple Swap Areas
The system can use multiple Swap partitions or files simultaneously:
sudo swapon /swapfile1
sudo swapon /swapfile2View all active Swap areas:
swapon --showPerformance Optimization Recommendations
- SSD vs HDD: Swap performs better on SSDs, but it consumes SSD lifespan.
- Swappiness Value: Recommended 10-30 for servers, slightly higher for desktop systems.
- Swap Size:
- Memory < 2GB: Swap = 2x memory
- Memory 2-8GB: Swap = equal to memory
- Memory > 8GB: Swap = 0.5x memory or less
- Monitoring: Regularly check Swap usage. Frequent Swap usage may indicate a need to increase memory.
Monitor Swap Usage
# Real-time monitoring
watch -n 1 free -h
# View detailed Swap usage
vmstat 1 5
# Check which processes are using Swap
sudo smem --sort swapManage the Swap space in your Linux system reasonably and adjust its size and usage policies according to actual needs.
Linux Swap Performance Impact and Usage Recommendations
The Performance Cost of Swap: Why Excessive Use Can Be Terrible
Swap can prevent system crashes due to memory exhaustion, but it comes at the severe cost of performance degradation. Here are the key performance issues:
1. Swap Read Speed vs. RAM (A Stark Contrast)
| Storage Type | Typical Latency | Typical Bandwidth | Suitable Use Cases |
|---|---|---|---|
| RAM (DDR4) | ~100 ns | 20-50 GB/s | High-speed computing, caching |
| NVMe SSD (Swap) | ~50-100 μs | 2-5 GB/s | Emergency memory extension (still has performance impact) |
| SATA SSD (Swap) | ~100-200 μs | 0.5-1 GB/s | Barely acceptable, noticeable impact |
| HDD (Swap) | ~5-10 ms | 50-200 MB/s | Use only in extreme cases, otherwise the system will nearly freeze |
Practical Impact:
- If an application frequently swaps out to HDD Swap, response times can become over 1000 times slower, causing service timeouts.
- Even with SSD/NVMe Swap, it’s still 100-1000 times slower than RAM and can still cripple performance under high load.
2. Typical Problem Scenarios: Performance Disasters Caused by Swap
Case 1: Database Server Crashes Due to Swap
- Phenomenon: MySQL queries suddenly slow down, jumping from 10ms to 10s.
- Cause: Insufficient memory, query cache swapped out to HDD Swap.
- Result: Database connections pile up, eventually making the entire service unavailable.
Case 2: Java Application Stalls Due to Swap
- Phenomenon: JVM performs frequent GC, with each Full GC duration increasing from 1s to 30s.
- Cause: JVM heap memory swapped out to Swap, GC needs to repeatedly read from Swap.
- Result: The application becomes almost unresponsive, and user requests time out.
Case 3: Kubernetes Node Evicted Due to Swap
- Phenomenon: A K8s node suddenly becomes
NotReady, and Pods are evicted. - Cause: Node memory exhausted, high Swap usage triggers Kubelet to deem the node unhealthy.
- Result: Pods are rescheduled, causing brief service interruption.
3. When Should You Use Swap? When Should You Avoid It?
✅ Scenarios Suitable for Using Swap
- Low-memory servers (< 4GB RAM): To avoid the OOM Killer directly terminating processes.
- Sudden memory demands: To temporarily handle traffic spikes, buying time for scaling.
- Development/Testing environments: To prevent system crashes caused by memory leaks.
❌ Scenarios Where Swap Should Be Avoided
- High-performance databases (MySQL, Redis, Elasticsearch): Disable Swap or set
vm.swappiness=1. - Kubernetes production environments: By default, it’s recommended to disable Swap (use
--fail-swap-on=falsewith caution). - Latency-sensitive applications (high-frequency trading, real-time computing): Swap can cause unpredictable delays.
4. Best Practices: How to Mitigate Swap’s Performance Impact?
- Prioritize adding RAM: Swap is an emergency measure, not a replacement for RAM.
- Use SSD/NVMe for Swap (avoid HDD): At least 100 times faster than mechanical drives.
- Adjust
vm.swappiness(recommend 1-10): Reduces the kernel’s proactive tendency to use Swap. - Monitor Swap usage (e.g.,
vmstat 1,sar -S 1): Identify anomalies promptly for scaling or application optimization. - Limit memory for critical services (
cgroups,docker --memory): Prevent a single process from exhausting memory and triggering Swap.
Swap is the Last Resort, Not the Solution
Swap can prevent system crashes but cannot provide good performance.
- If Swap usage is frequently > 0%, it indicates insufficient memory, and RAM should be upgraded.
- If Swap is being read from/written to frequently, the system is already in a dangerous state and must be optimized!
Use Swap wisely, but never rely on it! 🚀