High CPU or RAM
How to identify and resolve high CPU or memory usage problems
When the server is slow or not responding, often the cause is a process consuming too many resources. Here's how to diagnose and fix it.
Quick diagnosis
# See CPU, RAM and processes in real time
htop
# If htop is not installed
topIn top / htop:
- Sort by CPU: press
P - Sort by RAM: press
M - Kill a process: select it and press
k, then enter9
Find the "culprit" process
Top 5 processes by CPU
ps aux --sort=-%cpu | head -6Top 5 processes by RAM
ps aux --sort=-%mem | head -6Check load average
uptimeIf load average is much higher than number of CPU cores (nproc), the system is overloaded.
Kill a process
# Get the PID of the process
ps aux | grep process-name
# Terminate gracefully (process can clean up and exit)
kill PID
# Forcefully terminate (if kill doesn't work)
kill -9 PID
# By process name (more convenient)
pkill process-name
killall process-nameCommon causes of high CPU
1. Infinite loop in PHP/Python/other script
# Find PHP processes
ps aux | grep phpIf there are dozens of PHP processes, probably one script is looping. Kill PHP zombie processes:
pkill -9 php-fpm
systemctl restart php8.2-fpm2. Web scraper or DDoS attack
# Check active connections
ss -tn | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -rn | head -20If you see many connections from same IP, block it:
ufw deny from IP_TO_BLOCK3. MySQL / MariaDB with slow queries
# Check MySQL processes
mysql -u root -p -e "SHOW FULL PROCESSLIST;"
# Kill a blocking query
mysql -u root -p -e "KILL QUERY PROCESS_ID;"4. Service stuck in restart loop
# Check failed services
systemctl --failed
journalctl -u service-name -n 50Common causes of high RAM
Check what uses RAM
free -h
# Details per process
ps aux --sort=-%mem | head -10Free kernel cache (safe operation)
sync && echo 3 > /proc/sys/vm/drop_cachesKernel cache (buff/cache in free -h) is automatically freed when needed. It's not a problem if it's high: it's a Linux feature to use RAM efficiently.
OOM Killer: memory exhausted
If server ran out of RAM, kernel automatically kills processes (OOM Killer). Check if it happened:
dmesg | grep -i "oom\|out of memory\|killed process"If you see OOM messages, the plan's RAM might not be enough for the load. Consider:
- Optimize services (reduce workers, configure swap)
- Check for memory leaks in applications
- Upgrade the plan
Add a Swap file (temporary solution)
If RAM is insufficient, you can add swap:
# Create a 2GB swap file
fallocate -l 2G /swapfile
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile
# Make permanent
echo '/swapfile none swap sw 0 0' >> /etc/fstab
# Verify
free -h
swapon --showSwap on VPS (SSD disk) is much slower than RAM. It's a temporary measure, not a permanent solution. If server frequently uses swap, it's time to upgrade.