MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Linux + MySQL/MariaDB: “Who’s eating CPU/RAM?

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:

  1. Confirm the resource. Use vmstat 1 5 and free -h. A high r column means CPU pressure. Non-zero si/so means the server is swapping. A high wa means it is waiting on disk I/O, not CPU.
  2. Find the process with a live sampler such as top, pidstat -u 1 5 or systemd-cgtop. Don't rely on ps alone (see the next section).
  3. If php-fpm, httpd or apache2 is the top consumer, the database may only be a symptom. Find the hot pool or vhost first.
  4. If mysqld/mariadbd is the top consumer, run the processlist sampling loop while the spike is happening, then check Performance Schema digests for cumulative cost.
  5. Map the hottest OS threads of the database process to SQL statements (shown below), then fix or kill that query.
  6. 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. A mysqld that has been idle for weeks can look quiet in ps while it uses 400% in top right now. Use top -b -n1, pidstat or mpstat to 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 top and ps for multi-threaded processes. 100% equals one full core.
  • Long usernames get truncated. Use ps -eo user:32,... so names like www-data or 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 apache2 and PHP-FPM is php-fpm8.x, so -C httpd or -C php-fpm returns nothing. Use pgrep -a php-fpm to see the real names. Recent MariaDB releases run as mariadbd instead of mysqld.

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

ItemMariaDBMySQL
log_slow_verbosity=query_planSupportedUnknown variable, so the server refuses to start
userstat / TABLE_STATISTICSBuilt inNot available (Percona Server has it)
Performance Schema defaultOff; enabling it needs a restartOn by default
Service namemariadbmysqld (RHEL) or mysql (Debian/Ubuntu)
Default slow log directory in examples/var/log/mariadb/ (RHEL)Often /var/log/mysql/
Persist a runtime settingEdit the config fileSET PERSIST or edit the config file
Live processlistinformation_schema.PROCESSLISTperformance_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

SymptomCauseFix
ERROR 1064 ... near 'Database'Reserved word used as an aliasUse an alias like db_name
Unknown column 'db' on TABLE_STATISTICSWrong column nameUse TABLE_SCHEMA
mpstat: command not foundsysstat not installedInstall the sysstat package
Slow log stays emptyDirectory not writable by the mysql user, SELinux label, or threshold too highCheck SHOW VARIABLES LIKE 'slow_query_log%', fix ownership, run restorecon on SELinux hosts
Performance Schema queries return no rowsperformance_schema is OFF (MariaDB default)Enable it in the config and restart; it cannot be turned on at runtime
Processlist shows only your own threadsAccount lacks the PROCESS privilegeGrant 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

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services — all in one place.

Explore Hospitals
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.

Related Posts

Icinga Install and Configuration

This guide shows how to set up Icinga 2 with a MariaDB backend on Ubuntu. It covers preparing MariaDB, resetting a lost root password on a system…

Read More

Complete Guide for Socket based vs TCP Based Application Connection

Here’s a clear, end-to-end tutorial you can keep handy. It explains what “socket-based” vs “TCP-based” really means, how to tell which one you’re using, and how to…

Read More

keycloak: Installing keycloak with mysql (socket + TCP enabled)

To run Keycloak 17+ (Quarkus) with MySQL on the same server (XAMPP/LAMPP). It covers two supported setups. Pick A (TCP) for a production-style config, or B (UNIX…

Read More

Managing MariaDB Root Password and Connection Behavior in XAMPP (Ubuntu)

☁️ Introduction When working with MariaDB/MySQL inside XAMPP on Ubuntu, many developers face confusing issues related to root password behavior, localhost vs 127.0.0.1 access, and authentication plugins.This…

Read More

Icinga: How to Install Icinga 2 on Ubuntu

Prerequisites Step 1. Update the System Before we start to install the software, we need to update the system packages to the latest versions available. $ sudo…

Read More

List of Compreshive Checklist to do Security Audit in XAMPP server

Conducting a security audit on a XAMPP server is crucial, especially if you’re considering moving a local development environment to a production setting. XAMPP is primarily designed…

Read More
Subscribe
Notify of
guest
1 Comment
Newest
Oldest Most Voted
Jason Mitchell
Jason Mitchell
8 months ago

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.

1
0
Would love your thoughts, please comment.x
()
x