How to Diagnose and Fix High RAM Usage on Linux Servers
Your server is slow and you think it's RAM. Or you got an alert saying memory is at 92%. Or your app is randomly crashing and you suspect a memory leak.
Here's the systematic approach.
Step 1: Check Overall Memory Usage
free -h
total used free shared buff/cache available
Mem: 3.8Gi 3.1Gi 142Mi 45Mi 612Mi 542Mi
Swap: 2.0Gi 1.4Gi 614Mi
Key numbers:
- available: what's actually usable for new processes (not "free")
- Swap used: if swap > 0, you're RAM-constrained. Swapping is ~100x slower than RAM.
If available < 10% of total and swap is active, you have a RAM problem.
Step 2: Find Which Process Is Using RAM
# Sort by memory usage
ps aux --sort=-%mem | head -20
# Or with more readable output
ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem | head -20
If you want live monitoring:
# top — press M to sort by memory
top
# htop (more readable, install if needed)
htop
Step 3: Investigate the Top Process
# Detailed memory breakdown for a specific PID
cat /proc/<PID>/status | grep -i mem
# Virtual vs resident memory
pmap -x <PID> | tail -1
For Node.js processes:
# Get V8 heap statistics
kill -USR2 <PID> # Generates heap dump if --inspect is set
# Or add this to your app
setInterval(() => {
const mem = process.memoryUsage();
console.log(`RSS: ${Math.round(mem.rss/1024/1024)}MB, Heap: ${Math.round(mem.heapUsed/1024/1024)}MB`);
}, 60000);
Step 4: Check for Memory Leaks
Is RSS growing over time?
# Watch a process's memory over 10 minutes
for i in $(seq 1 10); do
ps -o pid,rss,vsz -p <PID>
sleep 60
done
If RSS grows consistently without dropping, you have a leak.
Node.js specific:
# Install clinic for leak detection
npm install -g clinic
clinic heapprofile -- node server.js
# Run load against your app for a few minutes, then Ctrl+C
# Clinic generates a flamegraph showing memory allocation
Step 5: Immediate Relief Options
# Drop page cache (safe — kernel re-reads from disk as needed)
sync && echo 1 | sudo tee /proc/sys/vm/drop_caches
# If a specific process is leaking, restart it
pm2 restart your-app
sudo systemctl restart your-service
# Add swap if you're out of options temporarily
sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
Prevention: Set Memory Limits
# For systemd services
sudo systemctl edit your-service
[Service]
MemoryMax=512M
MemorySwapMax=0 # Prevent swap
# For Docker
docker run --memory=512m --memory-swap=512m your-image
# For PM2
pm2 start server.js --max-memory-restart 400M
I built ARIA to solve exactly this.
Try it free at step2dev.com — no credit card needed.
Top comments (0)