TROUBLESHOOTING

High CPU or Memory Usage

Updated: December 2024
12 min read

Is your server slow or unresponsive? Learn how to identify resource-intensive processes and resolve high CPU or memory usage issues.

1 Identifying Resource Usage

Quick System Overview

# Quick resource check
top

# Better alternative with colors
htop

# Simple memory check
free -h

# CPU and load averages
uptime

Using htop (Recommended)

# Install htop if not available
sudo apt install htop -y

# Run htop
htop

Understanding htop Display:

  • CPU bars: Each bar represents one CPU core
  • Mem bar: Shows RAM usage
  • Swp bar: Shows swap usage (should be low)
  • Load average: 1-min, 5-min, 15-min averages
  • Process list: Sorted by CPU or memory usage

Find Top Resource Consumers

# Top 10 CPU consuming processes
ps aux --sort=-%cpu | head -11

# Top 10 memory consuming processes
ps aux --sort=-%mem | head -11

# Processes using most CPU right now
top -b -n 1 | head -20

2 High CPU Usage Solutions

Common Causes

Runaway Process

A single process consuming excessive CPU

Solution:

# Find the process ID (PID) ps aux --sort=-%cpu | head -5 # Kill the process sudo kill -9 PID_NUMBER # Or use htop: press F9, select signal, press Enter

Web Server Overload

Too many simultaneous connections or requests

Solutions:

# Check active connections netstat -an | grep :80 | wc -l netstat -an | grep :443 | wc -l # Restart web server sudo systemctl restart nginx # or sudo systemctl restart apache2
  • • Enable caching (Redis, Memcached)
  • • Optimize database queries
  • • Use a CDN for static content
  • • Consider upgrading VPS plan

Database Issues

MySQL/PostgreSQL using high CPU

Check slow queries:

# MySQL: Enable slow query log sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf # Add these lines: slow_query_log = 1 slow_query_log_file = /var/log/mysql/slow.log long_query_time = 2 # Restart MySQL sudo systemctl restart mysql # View slow queries sudo tail -f /var/log/mysql/slow.log

Malware or Mining Scripts

Cryptomining malware consuming resources

Check for suspicious processes:

# Look for unusual processes ps aux | grep -E 'xmr|miner|crypto' # Check for suspicious network connections sudo netstat -tunap | grep ESTABLISHED # Scan for rootkits sudo apt install rkhunter -y sudo rkhunter --check

Limit Process CPU Usage

# Use 'nice' to run with lower priority
nice -n 19 ./resource-heavy-script.sh

# Limit CPU with cpulimit
sudo apt install cpulimit -y
cpulimit -p PID -l 50  # Limit to 50% CPU

# Or use systemd to limit service
sudo systemctl set-property nginx.service CPUQuota=50%

3 High Memory Usage Solutions

Check Memory Status

# Detailed memory info
free -h

# Memory by process
ps aux --sort=-%mem | head -10

# Show swap usage
swapon --show

Understanding Memory Output

Linux caches frequently used files in RAM. "Available" memory is what matters, not "free". If "available" is low, you have a problem.

Common Memory Issues

Memory Leak in Application

Application continuously allocating memory without releasing it

# Monitor memory over time watch -n 1 free -h # Restart the problematic service sudo systemctl restart service-name # For persistent issues, schedule automatic restarts # Edit crontab: sudo crontab -e # Add: 0 3 * * * systemctl restart service-name

Clear Cache

Safe to do, won't hurt performance

# Drop caches (safe operation) sync echo 3 | sudo tee /proc/sys/vm/drop_caches # Clear swap (if enabled) sudo swapoff -a sudo swapon -a

Add or Increase Swap

Temporary solution for occasional spikes

# Create 2GB swap file sudo fallocate -l 2G /swapfile sudo chmod 600 /swapfile sudo mkswap /swapfile sudo swapon /swapfile # Make permanent echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab # Adjust swappiness (lower = use RAM more) sudo sysctl vm.swappiness=10 echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf

Optimize MySQL Memory

sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf

# For 2GB RAM VPS, add/modify:
[mysqld]
innodb_buffer_pool_size = 512M
key_buffer_size = 128M
max_connections = 50
query_cache_size = 32M
tmp_table_size = 32M
max_heap_table_size = 32M

# Restart MySQL
sudo systemctl restart mysql

Optimize PHP-FPM Memory

sudo nano /etc/php/8.1/fpm/pool.d/www.conf

# Adjust these values based on your RAM:
pm = dynamic
pm.max_children = 10
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3
pm.max_requests = 500

# Restart PHP-FPM
sudo systemctl restart php8.1-fpm

4 Long-term Monitoring

Install Monitoring Tools

# Install sysstat for historical data
sudo apt install sysstat -y

# Enable data collection
sudo systemctl enable sysstat
sudo systemctl start sysstat

# View CPU usage history
sar -u

# View memory history
sar -r

# View all stats for today
sar -A

Create Monitoring Script

sudo nano /usr/local/bin/resource-monitor.sh

Add this script:

#!/bin/bash
LOG="/var/log/resource-monitor.log"
DATE=$(date '+%Y-%m-%d %H:%M:%S')

CPU=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1)
MEM=$(free | grep Mem | awk '{print ($3/$2) * 100.0}')

echo "$DATE - CPU: ${CPU}% | Memory: ${MEM}%" >> $LOG

# Alert if CPU > 80%
if (( $(echo "$CPU > 80" | bc -l) )); then
    echo "HIGH CPU ALERT: $CPU%" | mail -s "Server Alert" [email protected]
fi
# Make executable
sudo chmod +x /usr/local/bin/resource-monitor.sh

# Run every 5 minutes via cron
sudo crontab -e
# Add: */5 * * * * /usr/local/bin/resource-monitor.sh

5 Prevention Tips

Optimize Applications

  • • Enable caching (Redis, Memcached)
  • • Optimize database queries
  • • Minify CSS/JS files
  • • Use CDN for static content
  • • Enable gzip compression

Security Measures

  • • Keep software updated
  • • Use fail2ban for brute force protection
  • • Regular security audits
  • • Monitor for unusual activity
  • • Disable unused services

Right-Size Your Server

  • • Monitor usage patterns
  • • Upgrade when consistently >70% usage
  • • Consider Streaming VPS for media
  • • Dedicated servers for high traffic

Regular Maintenance

  • • Clean up old logs regularly
  • • Remove unused packages
  • • Restart services periodically
  • • Monitor disk space
  • • Update and reboot monthly

When to Upgrade

If you're consistently using >70% of CPU or memory even after optimization, it's time to upgrade your VPS plan. X-ZoneServers makes scaling easy with no downtime!

Still Experiencing Issues?

Our support team can help diagnose and resolve performance problems

Get Expert Help

Was this article helpful?

Need assistance?

Contact Support