DEV Community

kingyou
kingyou

Posted on

How to Detect if Your Linux System is Running Low on Memory and About to Use Swap

Memory management is crucial for system performance and stability. When your Linux system runs low on physical RAM, it starts using swap space, which can significantly slow down operations. This guide shows you how to proactively monitor memory usage and detect when your system is about to start swapping.

Why Monitor Memory Before Swapping?

Swap space acts as overflow memory on your hard drive or SSD. While it prevents out-of-memory crashes, it's much slower than RAM:

  • RAM access time: Nanoseconds
  • SSD access time: Microseconds (1000x slower)
  • HDD access time: Milliseconds (1,000,000x slower)

Detecting low memory early allows you to:

  • Kill memory-hungry processes before performance degrades
  • Prevent system slowdowns
  • Plan memory upgrades
  • Optimize application resource usage

Method 1: Using the free Command

The free command is the quickest way to check memory status:

free -h
Enter fullscreen mode Exit fullscreen mode

Sample output:

              total        used        free      shared  buff/cache   available
Mem:           15Gi       8.2Gi       1.5Gi       234Mi       5.8Gi       6.9Gi
Swap:         2.0Gi          0B       2.0Gi
Enter fullscreen mode Exit fullscreen mode

Key metrics to watch:

  • available: This is the most important metric - it shows memory that can be allocated to applications
  • Swap used: If this number is greater than 0, swapping has already started
  • Warning threshold: When available drops below 10-15% of total memory

Method 2: Real-time Monitoring with top or htop

For continuous monitoring, use interactive tools:

Using top:

top
Enter fullscreen mode Exit fullscreen mode

Look at the memory section (lines 3-4):

MiB Mem :  15869.2 total,   1543.7 free,   8421.5 used,   5903.9 buff/cache
MiB Swap:   2048.0 total,   2048.0 free,      0.0 used.   7068.5 avail Mem
Enter fullscreen mode Exit fullscreen mode

Using htop (more user-friendly):

htop
Enter fullscreen mode Exit fullscreen mode

The memory bar at the top shows usage visually. Green indicates used memory, blue shows buffered memory, and yellow represents cache.

Method 3: Check Swap Activity with vmstat

The vmstat command shows if swapping is actively occurring:

vmstat 1 5
Enter fullscreen mode Exit fullscreen mode

This displays statistics every 1 second for 5 iterations:

procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
 1  0      0 1576832 185476 5903936  0    0     3    45   89  156  5  2 93  0  0
 0  0      0 1576544 185476 5903968  0    0     0     0  892 1456  3  1 96  0  0
Enter fullscreen mode Exit fullscreen mode

Critical columns:

  • si (swap in): Memory being moved from swap to RAM
  • so (swap out): Memory being moved from RAM to swap

If si or so show non-zero values, your system is actively swapping.

Method 4: Monitoring Available Memory Percentage

Create a simple script to check if available memory drops below a threshold:

#!/bin/bash

# Get available memory in MB
available=$(free -m | awk 'NR==2{print $7}')
total=$(free -m | awk 'NR==2{print $2}')
percentage=$((available * 100 / total))

echo "Available memory: ${percentage}%"

if [ $percentage -lt 15 ]; then
    echo "WARNING: Low memory! Only ${percentage}% available"
    echo "Top memory consumers:"
    ps aux --sort=-%mem | head -n 6
fi
Enter fullscreen mode Exit fullscreen mode

Save this as memory_check.sh, make it executable, and run it:

chmod +x memory_check.sh
./memory_check.sh
Enter fullscreen mode Exit fullscreen mode

Method 5: Check Swap Configuration

Verify your swap setup:

# View active swap devices
swapon --show

# Check swap details in /proc
cat /proc/swaps

# View swappiness setting (how aggressively kernel uses swap)
cat /proc/sys/vm/swappiness
Enter fullscreen mode Exit fullscreen mode

The swappiness value (0-100) controls swap usage:

  • 0-10: Minimal swapping (suitable for high-RAM servers)
  • 60: Default for most distributions
  • 100: Aggressive swapping

To temporarily change swappiness:

sudo sysctl vm.swappiness=10
Enter fullscreen mode Exit fullscreen mode

To make it permanent, add to /etc/sysctl.conf:

vm.swappiness=10
Enter fullscreen mode Exit fullscreen mode

Method 6: Automated Monitoring with Memory Pressure Alerts

For production systems, set up automated alerts using systemd:

# Check memory pressure (requires systemd 240+)
systemctl show --property=MemoryHigh system.slice
Enter fullscreen mode Exit fullscreen mode

You can also monitor memory pressure stall information:

cat /proc/pressure/memory
Enter fullscreen mode Exit fullscreen mode

Output shows what percentage of time the system spent waiting for memory:

some avg10=0.00 avg60=0.00 avg300=0.15 total=142893
full avg10=0.00 avg60=0.00 avg300=0.00 total=0
Enter fullscreen mode Exit fullscreen mode

Practical Warning Signs

Your system is likely to start swapping when:

  1. Available memory < 500 MB (for typical desktop/server)
  2. Available memory < 10% of total
  3. Buffer/cache being aggressively freed
  4. Applications becoming noticeably sluggish
  5. High I/O wait times in top (wa column)

Best Practices

  1. Monitor regularly: Check memory weekly or set up automated alerts
  2. Know your baseline: Understand normal memory usage for your workload
  3. Identify memory leaks: Watch for processes with constantly growing memory usage
  4. Plan capacity: Keep 20-30% memory free for peaks
  5. Use swap wisely: Swap is a safety net, not a RAM replacement

Quick Reference Commands

# Quick memory check
free -h

# Continuous monitoring
watch -n 2 free -h

# Check if swapping is active
vmstat 1 5 | grep -v "0  0" | head -n 5

# View top memory consumers
ps aux --sort=-%mem | head -n 10

# Check memory pressure
cat /proc/pressure/memory
Enter fullscreen mode Exit fullscreen mode

Conclusion

Proactive memory monitoring prevents performance degradation and system instability. By using tools like free, vmstat, and top, you can detect low memory conditions before swap usage begins.

The key is watching the available memory metric rather than just free memory, as Linux efficiently uses memory for caching. When available memory consistently drops below 15% of total, it's time to investigate memory usage or consider a RAM upgrade.

Remember: Swap is for emergencies, not for regular use. If your system regularly uses swap, you need more RAM or need to optimize your applications.

Top comments (1)

Collapse
 
patinthehat profile image
Patrick Organ

Thanks for this article, very helpful!