Symptom
CPU on the MySQL host goes to 80–100%, every query gets slower, and the application starts timing out. You open the slow query log to find the bad query, and there's nothing in it, or only the usual few long reports.
Why it happens
The slow query log judges each execution on its own: a statement gets logged only if that one run took longer than long_query_time (10 seconds by default). CPU is the total of all runs. A statement that takes 2 ms but runs 500 times a second from many connections costs a full CPU core, and no single run comes close to the threshold.
It usually comes from:
- A code path that runs a query per item in a loop (the N+1 pattern), and a page or job that suddenly loops over a lot more items.
- A cache that stopped working, so every request goes to the database.
- A new feature, or a client's retry storm, calling a cheap lookup far more often than anyone expected.
Once the CPU is saturated, everything waits for it, so the statement causing the load and its victims all get slower together. Lowering long_query_time then logs everything at once and doesn't point at anything.
Check
Rank statements by total time instead of time per call. performance_schema already counts every statement by digest (the statement with its literals replaced by ?):
-- top_digests_now.sql: statements by total execution time since the digest table was last reset
-- Copyright (c) HASHJOIN. MIT License (https://hashjoin.com/kb/license/)
-- https://hashjoin.com/kb/mysql/high-cpu-empty-slow-log/
--
-- Usage: mysql -t < top_digests_now.sql
--
-- Sorted by total time, not time per call, which is what the slow query log can't do: a 2 ms
-- query run 500 times a second costs a full CPU core and never shows up in the slow log.
-- per_sec is averaged since the digest was first seen, so it smooths out bursts; for "what ran
-- during the spike" take snapshots (awr-statement-digest-snapshots on this site).
SELECT IFNULL(SCHEMA_NAME, '') AS schema_name,
LEFT(DIGEST, 12) AS digest,
COUNT_STAR AS calls,
ROUND(COUNT_STAR / GREATEST(TIMESTAMPDIFF(SECOND, FIRST_SEEN, LAST_SEEN), 1), 1) AS per_sec,
ROUND(SUM_TIMER_WAIT / 1e12, 1) AS total_sec,
ROUND(SUM_TIMER_WAIT / NULLIF(COUNT_STAR, 0) / 1e9, 3) AS avg_ms,
ROUND(MAX_TIMER_WAIT / 1e9, 1) AS max_ms,
ROUND(SUM_ROWS_EXAMINED / NULLIF(COUNT_STAR, 0)) AS exam_per_call,
ROUND(100 * SUM_TIMER_WAIT / SUM(SUM_TIMER_WAIT) OVER (), 1) AS pct_of_all,
LEFT(REPLACE(DIGEST_TEXT, '\n', ' '), 70) AS statement
FROM performance_schema.events_statements_summary_by_digest
ORDER BY SUM_TIMER_WAIT DESC
LIMIT 15;curl -O https://hashjoin.com/kb/mysql/high-cpu-empty-slow-log/top_digests_now.sql
mysql -t < top_digests_now.sql
Look at the top rows' calls, per_sec and avg_ms. The statement causing the load usually has a small avg_ms and a very large calls, and a big share of pct_of_all. The sys schema gives the same ranking, if it's installed: SELECT * FROM sys.statement_analysis LIMIT 10;.
These totals count from the last restart (or the last time someone truncated the table), so a statement that has run all month can outrank the one that caused this morning's spike. To see what ran during the spike, either:
- While it's happening, take two readings a minute apart and compare
callsand total time, or - For the next time, keep 5-minute snapshots with the CPU next to them: AWR for MySQL. Comparing a bad window with a normal one (
awr_diff.sql) puts the statement responsible at the top.
Reading the output
From the lab, after 16 connections ran one indexed SELECT 4,000 times each, with the slow log on at its default 10-second threshold. The slow log had 0 rows. top_digests_now.sql (columns trimmed):
+-------------+--------------+-------+-----------+--------+--------+---------------+------------+--------------------------------------+
| schema_name | digest | calls | total_sec | avg_ms | max_ms | exam_per_call | pct_of_all | statement |
+-------------+--------------+-------+-----------+--------+--------+---------------+------------+--------------------------------------+
| kblab | 2c589e59cbb7 | 63973 | 5.9 | 0.092 | 30.2 | 40 | 99.8 | SELECT `id` , `project_id` , `par... |
| kblab | 4fc400849e85 | 200 | 0 | 0.029 | 0.1 | 99 | 0.1 | SELECT COUNT ( * ) FROM `kblab` .... |
| kblab | 2d78f9f1fe71 | 200 | 0 | 0.018 | 0 | 1 | 0.1 | SELECT NAME FROM `kblab` . `items... |
One statement, averaging under a tenth of a millisecond, has 99.8% of all statement time. Its slowest run took 30 ms, nowhere near 10 seconds.
Fix
Make each call cheaper, or make fewer of them. In order of how often it's the answer:
- Fewer calls. Find the caller: the statement's text usually points at one code path. Batch the per-item queries into one, cache the result in the application, or fix the cache that stopped working.
- Cheaper calls.
EXPLAINthe statement. A sort on every call (Using filesort) or a lookup back to the table for every row can often be removed with an index that matches theWHEREand theORDER BY. For example,(project_id, parent_id, created_at)forWHERE project_id = ? ORDER BY parent_id, created_at. - Fewer at once. Hundreds of connections all running the same statement make CPU contention worse. A smaller application connection pool, or a proxy that queues, often brings throughput up and latency down.
- More CPU buys time while you do the above. On its own it only moves the ceiling.
Verify
top_digests_now.sqltaken twice, a few minutes apart: the statement'scallsgrows more slowly, or itsavg_msdropped.- CPU on the host is back to normal at the same traffic.
In the incident behind this page
The primary was RDS MySQL 5.6, in 2017. Its CPU kept spiking above 90%, and one spike took the application down. The slow query log had nothing useful. Snapshots of the digest table every 5 minutes, with the CPU from CloudWatch next to each one, showed what was going on. Comparing a 90%-CPU snapshot with a 12% one put a single-table SELECT by an indexed column, with an ORDER BY, at the top: about 58,000 calls in five minutes, around 190 a second, from many connections at once. Each call was cheap. Together they were most of the CPU.
Gotchas
long_query_time = 0for a few minutes is another way to see everything, but it writes every statement to the log. Do it on a replica that gets the same traffic, or keep it brief, and use pt-query-digest to summarize the result.- The digest table has a size limit. If
Performance_schema_digest_lostis growing, new statements are being counted in one catch-all row with no digest. See the AWR page. - Truncating the digest table to "start fresh" resets the numbers for every other tool that reads it. Take two readings and subtract them instead.
What it reads
performance_schema.events_statements_summary_by_digest sys.statement_analysis mysql.slow_log
Related
- AWR for MySQL: snapshots of performance_schema statement digests
- MySQL statements that examine far more rows than they return
- pt-query-digest on RDS when the slow log is a table (log_output=TABLE)
Running this fleet-wide, by hand?
HASHJOIN builds the control plane that runs upgrades, failovers and repairs like this one across every host, with a lock per unit, a drain on Ctrl-C and a log you can read at 3 a.m.
New fixes and field notes by email, about once a month.