Linux Performance

Fixing High CPU Usage on Linux Servers (Real-World Checklist)

By Nikhil Bhangale··7 min read

Load average alone hides whether your Linux server is burning user-space CPU, choking on disk I/O, or losing cycles to noisy VPS neighbors. Walk through a battle-tested diagnostic workflow using vmstat, pidstat, MySQL process inspection, and systemd cgroup v2 guardrails.

Fixing High CPU Usage on Linux Servers (Real-World Checklist)

Last month a client messaged me ready to double their cloud server size because load averages had climbed past 14.00 on a 4-vCPU Ubuntu box. Before approving an upgrade that would double their monthly infrastructure bill, I ran vmstat 1 for five seconds and spotted 4% user CPU alongside 67% disk I/O wait and 19% hypervisor steal time. Buying four extra vCPUs on that oversold host would have burned budget without speeding up a single checkout request.

High load averages on Linux are a symptom, not a diagnosis. Unlike BSD kernels that count only runnable CPU threads, Linux includes processes stuck in uninterruptible sleep (D state, typically blocked on disk or network storage) directly inside the load average calculation. Whenever monitoring alerts me to elevated load, I run through this exact diagnostic sequence before restarting daemons or scaling hardware.

Step 1: Read Load Averages Against nproc

Compare the 1-minute, 5-minute, and 15-minute load figures against logical core count and active kernel scheduling entities:

bash · terminal
uptime
# 17:42:01 up 48 days, 3:14, 2 users, load average: 11.42, 8.91, 5.14

nproc
# 4

cat /proc/loadavg
# 11.42 8.91 5.14 9/418 29841

Reading left to right shows trajectory: 11.42 above 8.91 above 5.14 means contention is actively rising right now on a 4-core box, whereas 3.10, 7.80, 9.40 would show an incident already cooling down. The fourth field in /proc/loadavg (9/418) confirms 9 threads are currently runnable or blocked in uninterruptible I/O out of 418 total threads. Next, find out which subsystem those nine threads are fighting over.

Step 2: Classify the Bottleneck in Five Seconds With vmstat 1

Run vmstat 1 5, ignore line one (which shows averages since last boot), and inspect lines two through five:

bash · terminal
vmstat 1 5
# procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
#  r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
#  8  1  12288 314820  84120 1420900  0    0    12   410 4210 8940 78 14  2  1  5
#  9  0  12288 308116  84124 1421104  0    0     0   180 4590 9310 81 12  1  1  5
# 10  0  12288 301440  84124 1421380  0    0     8   220 4480 9120 83 11  0  1  5

The rightmost CPU columns tell you immediately which troubleshooting path to take:

vmstat MetricWarning LevelWhat Is Actually HappeningNext Diagnostic Command
us (User)Above 75%Application workers (PHP-FPM, Node.js, Python, SQL sorting, or compression) are burning cyclespidstat -u 1 5 and database process list
sy (System)Above 25%Kernel space is saturated by context switches (cs), fork storms, or packet filter interruptspidstat -w 1 5 and SYN flood / conntrack checks
wa (I/O Wait)Above 20%Cores sit idle waiting on slow storage (b above 0) or swap thrashing (si/so above 0)iotop -obn 3 and iostat -xz 1 3
st (Steal)Above 10%Noisy neighbors on an oversubscribed KVM/Xen hypervisor are starving your guest vCPUsStop/start VM onto fresh host hardware or migrate provider

Checking st (CPU steal) first prevents hours of wasted application tuning. When a noisy VPS host steals 20% of every clock tick, well-indexed SQL queries and cached PHP endpoints still crawl because the hypervisor refuses to schedule your virtual cores on physical silicon.

Step 3: Catch Fleeting and Sustained Hogs With pidstat

A single ps aux --sort=-%cpu snapshot misses short-lived cron workers that spawn and exit every second, and default top intervals smooth out fast bursts. Use pidstat (from the sysstat package) across five one-second samples to get exact per-PID attribution:

bash · terminal
pidstat -u 1 5
# Average:      UID       PID    %usr %system  %guest   %wait    %CPU   CPU  Command
# Average:       33     48219   64.20    3.80    0.00    6.40   68.00     -  php-fpm8.2
# Average:       33     48224   61.40    4.10    0.00    7.10   65.50     -  php-fpm8.2
# Average:      114      1942  118.60   14.20    0.00    2.10  132.80     -  mysqld

Here, two php-fpm8.2 children and mysqld consume over 2.6 cores combined. Now isolate whether the root cause sits in PHP code, missing SQL indexes, disk contention, or malware.

Step 4: Separate PHP Exhaustion, Slow SQL, Disk Locks, and /dev/shm Miners

PHP-FPM Pools vs. Unindexed MySQL Queries

When php-fpm and mysqld spike together, inspect MySQL before restarting PHP. Restarting PHP while ten unindexed full-table scans hold InnoDB buffer pool threads simply lets new HTTP requests trigger ten more identical table scans a second later:

bash · terminal
mysql -e "SHOW FULL PROCESSLIST;" | awk '$5 != "Sleep" && $6 > 2'
# 88412  app_user  localhost  shop_prod  Query  14  Sending data  SELECT * FROM orders WHERE customer_email LIKE '%@gmail.com' ORDER BY created_at DESC

Queries stuck in Sending data or Creating sort index point straight to missing composite indexes or leading-wildcard LIKE scans. Run EXPLAIN against that query in staging or read-only mode before altering production tables. Conversely, if SHOW FULL PROCESSLIST is clean while php-fpm pins cores at 99%, enable request_slowlog_timeout = 5s and slowlog = /var/log/php8.2-fpm-slow.log inside your pool config to dump exact line-by-line PHP call stacks of runaway regexes or hung external API calls.

D-State Disk I/O Bottlenecks

When load climbs past 12.0 while us + sy CPU stays below 20%, check for threads trapped in uninterruptible sleep (D state) and pinpoint which process owns block I/O:

bash · terminal
ps -eo pid,user,stat,wchan:20,comm | awk 'NR==1 || $3 ~ /D/'
#   PID USER     STAT WCHAN                COMMAND
#  1942 mysql    D    blk_mq_get_tag       mysqld
# 61204 root     D    ext4_sync_file       rsync

iotop -obn 3

Unthrottled rsync or archive jobs saturating NVMe write queues routinely stall database fsync() commits, a failure pattern we permanently isolated after our late-night SaaS export incident.

Hidden Malware and Miners in /dev/shm

On compromised CMS accounts, attackers disguise XMRig cryptominers under kernel-style names like [kworker/u8:2], launch them from world-writable tmpfs directories (/dev/shm or /tmp), and unlink the binary so ls shows nothing. Inspect /proc/<PID>/exe directly for any suspicious high-CPU PID:

bash · terminal
ls -la /proc/51908/exe /proc/51908/cwd
# lrwxrwxrwx 1 www-data www-data 0 Nov 14 17:44 /proc/51908/cwd -> /var/www/site/public/uploads
# lrwxrwxrwx 1 www-data www-data 0 Nov 14 17:44 /proc/51908/exe -> '/dev/shm/.cache/kworker (deleted)'

An unlinked (deleted) binary running from /dev/shm as www-data confirms a breached web application. Check crontab -l -u www-data and user systemd timers for persistence, kill the process group, mount /dev/shm and /tmp with noexec,nosuid,nodev in /etc/fstab, and patch the exploited plugin or PHP runtime immediately.

Step 5: Enforce Permanent systemd cgroup v2 Guardrails

After resolving the immediate trigger, configure systemd cgroup v2 limits (standard on Ubuntu 22.04+, Debian 12+, and RHEL 9+, verifiable via stat -fc %T /sys/fs/cgroup/) so no runaway service can starve SSH or the OS scheduler again. Apply live caps immediately without restarting the daemon:

bash · terminal
systemctl set-property php8.2-fpm.service CPUAccounting=yes CPUQuota=250% MemoryHigh=2560M MemoryMax=3072M

To make limits survive apt package upgrades, never edit /lib/systemd/system/*.service directly because vendor updates overwrite those files. Create a drop-in override at /etc/systemd/system/php8.2-fpm.service.d/limits.conf, then run systemctl daemon-reload and verify live enforcement with systemd-cgtop:

config / ini
[Service]
CPUAccounting=yes
CPUQuota=250%
MemoryAccounting=yes
MemoryHigh=2560M
MemoryMax=3072M
IOWeight=100

One trap to avoid in production: do not slap a tight CPUQuota onto mysqld or postgresql. If the kernel throttles a database worker mid-slice while it holds an InnoDB page latch or WAL lock, every query queued behind that latch stalls with it, multiplying active connections. Cap stateless web pools and batch slices with CPUQuota and MemoryMax, and protect database daemons using CPUWeight=200 and IOWeight=200 priority shares instead.

#linux#performance#systemd#cgroups#cpu
← Back to all posts

Related Articles

Browse all articles →
Linux Performance10 min read

Tuning Slow Linux VPS Nodes Without Upgrading RAM

When a 2 or 4 GB Linux VPS slows down under traffic, hosting support almost always tells you to buy a bigger plan. Here is the exact kernel, database, web server, and process tuning workflow I use to make existing VPS nodes fly.

Read article →
Linux Performance8 min read

Stop AI Scraper Bots Crashing Your Linux Web Server

If your Linux server suddenly hits 100% CPU and throws 503 or 508 errors while Google Analytics shows normal traffic, aggressive AI scraper bots are likely bypassing your page cache. Here is my exact Nginx, Apache, and Fail2ban defense playbook.

Read article →
Daily Work Log13 min read

SolusVM 2 Migration Guide: Fix Agents, License & WHMCS

Today's hands-on work log: migrating a live SolusVM 2 Management Server to a new VPS without touching running Compute Resource VMs, fixing the license IP lock, debugging RabbitMQ and solus-agent start/stop/create failures, and restoring WHMCS automation.

Read article →
Chat on WhatsApp