When a Linux database server slows down, start with the OS to find the busy process, user or service. If that turns out to be mysqld or mariadbd, use processlist sampling, the slow query log and Performance Schema to find which database and query is responsible. The cheat sheet below gives the commands. The sections after it explain how to read the numbers, map a hot OS thread to a specific SQL statement, and fix several commands from the cheat sheet that fail or return nothing as written.
A triage order that works under pressure
The cheat sheet above is a list of commands. During an incident it helps to run them in an order where each step narrows down the next one:
- Confirm the resource. Use
vmstat 1 5andfree -h. A highrcolumn means CPU pressure. Non-zerosi/someans the server is swapping. A highwameans it is waiting on disk I/O, not CPU. - Find the process with a live sampler such as
top,pidstat -u 1 5orsystemd-cgtop. Don't rely onpsalone (see the next section). - If
php-fpm,httpdorapache2is the top consumer, the database may only be a symptom. Find the hot pool or vhost first. - If
mysqld/mariadbdis the top consumer, run the processlist sampling loop while the spike is happening, then check Performance Schema digests for cumulative cost. - Map the hottest OS threads of the database process to SQL statements (shown below), then fix or kill that query.
- Turn on the slow query log so the next spike leaves evidence even if nobody is watching.
Note: mpstat and pidstat come from the sysstat package (dnf install sysstat or apt install sysstat). pt-query-digest comes from percona-toolkit. Neither is installed by default on most distributions.
Reading the Linux numbers correctly
ps%CPU is a lifetime average. It is total CPU time divided by the process's elapsed time, not current usage. Amysqldthat has been idle for weeks can look quiet inpswhile it uses 400% intopright now. Usetop -b -n1,pidstatormpstatto see what is happening now.- %MEM double-counts shared memory. Each PHP-FPM or Apache worker's RSS includes shared libraries and opcache, so the per-user and per-command totals in the example above can add up to more than 100%. Treat them as a ranking, not an exact figure.
smem(if installed) reports PSS, which divides shared pages fairly. - CPU above 100% is normal in
topandpsfor multi-threaded processes. 100% equals one full core. - Long usernames get truncated. Use
ps -eo user:32,...so names likewww-dataor cPanel account names are not cut off or replaced by a UID before the awk aggregation. - Process names vary by distribution. On Debian and Ubuntu, Apache is
apache2and PHP-FPM isphp-fpm8.x, so-C httpdor-C php-fpmreturns nothing. Usepgrep -a php-fpmto see the real names. Recent MariaDB releases run asmariadbdinstead ofmysqld.
Map a hot mysqld thread to the exact query
The cheat sheet stops at database-level rankings. To find the specific statement burning a core, look at the server's threads in top, then look up those OS thread IDs in Performance Schema. This works on MySQL 5.7 and later and on recent MariaDB versions with performance_schema=ON.
# 1. Show per-thread CPU for the database server (H toggles thread view)
top -H -b -n1 -p "$(pgrep -d, -x 'mysqld|mariadbd')" | head -20
# 2. Take the PID column of the hottest thread (e.g. 23817) and look it up
mysql -e "
SELECT THREAD_OS_ID, PROCESSLIST_ID, PROCESSLIST_USER, PROCESSLIST_DB,
PROCESSLIST_TIME, LEFT(PROCESSLIST_INFO, 300) AS query
FROM performance_schema.threads
WHERE THREAD_OS_ID = 23817\G"
# 3. If it is a runaway query, stop the statement but keep the connection
mysql -e "KILL QUERY 4512;" # 4512 = PROCESSLIST_ID from step 2Code language: PHP (php)
If the hot thread has no PROCESSLIST_ID, it is a background thread such as InnoDB purge, page cleaner or replication. In that case, check SHOW ENGINE INNODB STATUS\G for a long history list (purge lag) or heavy flushing rather than looking for a user query.
Note: Performance Schema digest counters accumulate from server start. To measure only the current spike, reset them with TRUNCATE TABLE performance_schema.events_statements_summary_by_digest;, wait a few minutes, then run the top-digest query from the example above.
Corrected commands
Several commands in the cheat sheet fail or silently return nothing. Database size. DATABASE is a reserved word, so AS Database causes ERROR 1064. Backticks would fix the SQL, but inside a double-quoted bash string they would trigger command substitution. A plain alias avoids both problems:
mysql -e "
SELECT table_schema AS db_name,
ROUND(SUM(data_length + index_length)/1024/1024, 2) AS size_mb
FROM information_schema.tables
GROUP BY table_schema
ORDER BY size_mb DESC;"Code language: PHP (php)
MariaDB userstat. information_schema.TABLE_STATISTICS has no db column. The schema column is TABLE_SCHEMA. Also, userstat is a dynamic variable, so it can be enabled without a restart:
mysql -e "SET GLOBAL userstat = 1;"
# ...let traffic run, then:
mysql -e "
SELECT TABLE_SCHEMA AS db,
SUM(ROWS_READ) AS rows_read,
SUM(ROWS_CHANGED) AS rows_changed,
SUM(ROWS_READ) + SUM(ROWS_CHANGED) AS activity
FROM information_schema.TABLE_STATISTICS
GROUP BY TABLE_SCHEMA
ORDER BY activity DESC
LIMIT 10;"
# Reset counters for a fresh window: FLUSH TABLE_STATISTICS;Code language: PHP (php)
Slow queries per schema. MariaDB writes the schema on a line like # Thread_id: 8 Schema: shop QC_hit: No, so grep '^# Schema:' matches nothing. Match the field wherever it appears instead:
grep -o 'Schema: [^ ]*' /var/log/mariadb/slow.log | awk '{print $2}' | sort | uniq -c | sort -nrCode language: JavaScript (javascript)
Aggregations. Print the header separately so sort cannot move it to the bottom, and widen the user column:
printf "%-25s %-10s %-10s\n" COMMAND "CPU(%)" "MEM(%)"
ps -eo comm,%cpu,%mem --no-headers \
| awk '{cpu[$1]+=$2; mem[$1]+=$3} END {for (i in cpu) printf "%-25s %-10.2f %-10.2f\n", i, cpu[i], mem[i]}' \
| sort -k2,2nr | head
printf "%-20s %-10s %-10s\n" USER "CPU(%)" "MEM(%)"
ps -eo user:32,%cpu,%mem --no-headers \
| awk '{cpu[$1]+=$2; mem[$1]+=$3} END {for (i in cpu) printf "%-20s %-10.2f %-10.2f\n", i, cpu[i], mem[i]}' \
| sort -k2,2nrCode language: JavaScript (javascript)
The sampling loop uses {1..30}, which is bash brace expansion. Under /bin/sh on Debian or Ubuntu (dash), it runs only once. Run it with bash, or use for i in $(seq 1 30). Its 2>/dev/null also hides authentication errors, so test the inner mysql command once on its own first.
Keep passwords off the command line
-pYOURPASS makes the password visible to other users through ps, and it stays in shell history. Put the credentials in an option file instead, so every command in this guide can drop -u root -p:
cat > ~/.my.cnf <<'EOF'
[client]
user=root
password=YOURPASS
EOF
chmod 600 ~/.my.cnf
mysql -e "SELECT CURRENT_USER();"Code language: PHP (php)
On many MariaDB installs, and on MySQL from Debian or Ubuntu packages, the local root account uses socket authentication, so sudo mysql works with no password at all. For monitoring, use a dedicated account with only the PROCESS privilege, plus SELECT on performance_schema. Without PROCESS, the processlist shows only that account's own threads.
MySQL vs MariaDB differences that break the cheat sheet
| Item | MariaDB | MySQL |
|---|---|---|
log_slow_verbosity=query_plan | Supported | Unknown variable, so the server refuses to start |
userstat / TABLE_STATISTICS | Built in | Not available (Percona Server has it) |
| Performance Schema default | Off; enabling it needs a restart | On by default |
| Service name | mariadb | mysqld (RHEL) or mysql (Debian/Ubuntu) |
| Default slow log directory in examples | /var/log/mariadb/ (RHEL) | Often /var/log/mysql/ |
| Persist a runtime setting | Edit the config file | SET PERSIST or edit the config file |
| Live processlist | information_schema.PROCESSLIST | performance_schema.processlist preferred; the I_S table is deprecated in newer versions |
Note: SET GLOBAL long_query_time=2 applies only to connections opened after the change. Long-lived pooled connections keep the old value until they reconnect. Every SET GLOBAL is also lost on restart unless it is also written to the config file.
When mysqld is the memory hog
A large, steady RSS for mysqld is usually expected. The InnoDB buffer pool is allocated to cache data and is not released when the server goes idle. Check what the server is configured to use before you call it a leak:
mysql -e "SELECT @@innodb_buffer_pool_size/1024/1024/1024 AS buffer_pool_gb,
@@max_connections, @@tmp_table_size/1024/1024 AS tmp_table_mb;"
# Did the kernel OOM killer hit the database?
dmesg -T | grep -iE 'out of memory|killed process'
journalctl -k --since '-1 day' | grep -i oomCode language: PHP (php)
Real memory growth beyond the buffer pool usually comes from per-connection buffers (sort_buffer_size, join_buffer_size, tmp_table_size) multiplied by many concurrent connections. Rising Created_tmp_disk_tables and Threads_running in the cheat sheet's status commands point that way. To see per-second deltas instead of running the commands twice, use mysqladmin -r -i 10 extended-status | grep -E 'Threads_running|Created_tmp_disk|Questions'.
Common errors and fixes
| Symptom | Cause | Fix |
|---|---|---|
ERROR 1064 ... near 'Database' | Reserved word used as an alias | Use an alias like db_name |
Unknown column 'db' on TABLE_STATISTICS | Wrong column name | Use TABLE_SCHEMA |
mpstat: command not found | sysstat not installed | Install the sysstat package |
| Slow log stays empty | Directory not writable by the mysql user, SELinux label, or threshold too high | Check SHOW VARIABLES LIKE 'slow_query_log%', fix ownership, run restorecon on SELinux hosts |
| Performance Schema queries return no rows | performance_schema is OFF (MariaDB default) | Enable it in the config and restart; it cannot be turned on at runtime |
| Processlist shows only your own threads | Account lacks the PROCESS privilege | Grant PROCESS to the monitoring user |
Frequently asked questions
How do I find which query is using the most CPU in MySQL or MariaDB?
Run top -H -p on the server process to find the hottest threads, then look up their IDs in the THREAD_OS_ID column of performance_schema.threads to get the running SQL. For cost over time, sort events_statements_summary_by_digest by SUM_TIMER_WAIT.
Why does mysqld use so much RAM even when the server is idle?
The InnoDB buffer pool is allocated to cache data and indexes and stays allocated whether or not queries are running. Compare RSS with innodb_buffer_pool_size before you suspect a leak.
Is the %CPU column from ps the current CPU usage?
No. ps reports total CPU time divided by the process's lifetime. Use top, pidstat -u 1 or mpstat to see current usage.
Can I enable Performance Schema without restarting MariaDB?
No. The performance_schema variable is read only at startup, so add performance_schema=ON under [mysqld] and restart. The slow query log and userstat can be switched on at runtime with SET GLOBAL.
How do I stop a runaway query without dropping the client connection?
Use KILL QUERY <id> with the ID from the processlist. This cancels the statement but keeps the connection open. Plain KILL <id> closes the whole connection.
Related tutorials
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services — all in one place.
Explore Hospitals
Good read! The tips for finding what’s using CPU/RAM with Linux, MySQL, and MariaDB are explained clearly — really helpful for troubleshooting performance issues.