Home›Operate›Run it well 6: find the slow queries
Run it well

Find the queries that eat the database

A database is rarely slow everywhere. A few query shapes use most of its time, and every engine already counts them for you. This chapter shows where those counts live and how to read them before the incident, not during it.

The problem

Monday morning, and nobody deployed anything

Checkout p99 went from 80 ms to 2 seconds over the weekend. CPU on the primary sits at 85%. Nobody shipped code. Your app sends about 400 different queries to the database, and right now you have no idea which ones are eating it.

Here is the part people miss: it is almost never the query that looks scary. The slow, ugly report query that runs twice a day is not your problem. The problem is usually a 5 ms query that runs 2,000 times a second. That one query costs 10 seconds of database time every second. No single run of it looks slow.

So the real question is not "which query is slow?" It is "which query shape uses the most total time?" Total time is calls times average time. Keep that in your head for the rest of this chapter.

The naive way

Log every query, then read the log

The first instinct is to log everything. Set long_query_time = 0 in MySQL, or log_min_duration_statement = 0 in PostgreSQL, and look at the file.

Do the math first. Say the server runs 5,000 queries a second and each log entry is about 500 bytes. That is 2.5 MB a second, or about 9 GB an hour (derived, not measured). Now you have a disk problem and an I/O problem on top of a CPU problem. And a 9 GB file of single queries still does not tell you which shape costs the most.

The second instinct is the opposite: only log queries slower than 1 second. That is quiet and cheap, and it misses exactly the query that is hurting you, the 5 ms one that runs 2,000 times a second.

So what do you actually want?

Every query, grouped by its shape, with the literal values stripped out. WHERE id = 42 and WHERE id = 97 are the same query. Then rank the shapes by total time. Every engine can do this, and it costs far less than logging every statement.

PostgreSQL

pg_stat_statements: every query shape, already added up

PostgreSQL ships an extension that does exactly this. It normalizes each statement into a shape, keeps running totals per shape in shared memory, and lets you query them like a table. It has to be loaded at server start, so this is a restart the first time.

# postgresql.conf (needs a restart)
shared_preload_libraries = 'pg_stat_statements'
track_io_timing = on                 # adds read and write time per query; check your platform with pg_test_timing first

-- then, once, in the database you care about
CREATE EXTENSION pg_stat_statements;

Now ask the question from the top of the page: which shapes use the most total time?

SELECT left(query, 60)                        AS query,
       calls,
       round(total_exec_time)                 AS total_ms,
       round(mean_exec_time::numeric, 2)      AS mean_ms,
       round(100 * total_exec_time / sum(total_exec_time) OVER (), 1) AS pct,
       shared_blks_read                       AS disk_blocks
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;

Read the pct column first. On most systems a handful of shapes add up to most of the time. That is your list. The disk_blocks column tells you which ones are reading from disk instead of from shared buffers.

The numbers are totals since the last reset. To see what changed this week, save a snapshot, call pg_stat_statements_reset(), and compare next week. Or diff two snapshots without resetting.

You also want the plan of the slow runs, not just the totals. auto_explain writes the plan of any statement slower than a threshold into the server log:

# postgresql.conf
session_preload_libraries = 'auto_explain'
auto_explain.log_min_duration = '500ms'
auto_explain.log_analyze = off       # on means every statement is timed, which costs CPU on a busy server
log_min_duration_statement = '1s'    # a plain catch-all for the really slow ones
log_lock_waits = on                  # logs waits longer than deadlock_timeout
SHOW log_min_duration_statement; SHOW shared_preload_libraries;
MySQL

The digest table, and the slow log as a second opinion

MySQL already keeps the same kind of totals. Performance Schema groups statements by digest, which is the normalized shape. It is on by default in MySQL 8. Times are in picoseconds, so divide by 1e12 for seconds.

SELECT LEFT(DIGEST_TEXT, 60) AS query, COUNT_STAR AS calls, ROUND(SUM_TIMER_WAIT / 1e12, 1) AS total_s, ROUND(AVG_TIMER_WAIT / 1e9, 2) AS mean_ms, SUM_ROWS_EXAMINED AS rows_examined, SUM_ROWS_SENT AS rows_sent FROM performance_schema.events_statements_summary_by_digest ORDER BY SUM_TIMER_WAIT DESC LIMIT 10;

Look at rows_examined next to rows_sent. A query that examines 2 million rows to send back 20 is a missing or wrong index. The sys schema has friendlier views of the same data, such as sys.statement_analysis.

The slow log is still useful, because it keeps individual runs with their timestamps. Turn it on with a threshold you can afford, and summarize it with pt-query-digest from Percona Toolkit, which groups the file by shape the same way:

SET GLOBAL slow_query_log = ON;
SET GLOBAL long_query_time = 0.5;        -- seconds; new connections pick it up
SET GLOBAL log_slow_extra = ON;          -- 8.0.14+: rows examined, bytes sent and more per entry

# on the server, summarize the file by query shape
pt-query-digest /var/lib/mysql/$(hostname)-slow.log > digest.txt
SHOW VARIABLES LIKE 'slow_query_log%'; SHOW VARIABLES LIKE 'long_query_time';
MongoDB

The profiler, and the slow operations in the log

MongoDB logs any operation slower than slowms (100 ms by default) to its log. The profiler goes further and stores those operations in the system.profile collection of each database, where you can query them. Level 1 profiles only slow operations, which is what you want in production. Level 2 profiles everything and has the same problem as logging every query.

// profile operations slower than 100 ms in this database
db.setProfilingLevel(1, { slowms: 100 })

// the shapes that cost the most total time recently
db.system.profile.aggregate([
  { $group: { _id: { ns: "$ns", shape: "$queryHash" },
              calls: { $sum: 1 }, total_ms: { $sum: "$millis" },
              examined: { $sum: "$docsExamined" }, returned: { $sum: "$nreturned" } } },
  { $sort: { total_ms: -1 } }, { $limit: 10 } ])

The same rule applies: compare documents examined to documents returned. A plan summary of COLLSCAN on a big collection is the MongoDB version of a missing index.

db.getProfilingStatus()
Follow one query

From the top of the list to a fix

Back to Monday. The first row in pg_stat_statements is a lookup of a customer's open orders. It runs 1,800 times a second, averages 6 ms, and accounts for 41% of all database time. Last week it averaged 0.4 ms. Nobody changed the query.

Step two is the plan. Run the query with real values from the slow log through EXPLAIN (ANALYZE, BUFFERS). It shows a sequential scan on orders. Step three is asking why the plan changed. The index on (customer_id, status) is still there, but a weekend backfill inserted 40 million rows with a new status value, and the planner's statistics are stale. It thinks the index will match most of the table.

The fix is boring: ANALYZE orders;. The mean drops back under a millisecond, and the shape falls off the top of the list. The real fix is the follow-up: the backfill job now runs ANALYZE when it finishes. The numbers in this story are an example, not a measurement. But the pattern of stale statistics after a bulk load, with the plan flipping to a scan, is one of the most common reasons a query gets slow with no code change.

Isn't pg_stat_statements expensive to leave on?

It is designed to stay on, and some managed services load it by default. It keeps a fixed number of shapes (pg_stat_statements.max, 5,000 by default) and drops the least used. The costs to measure on your own hardware are track_io_timing and auto_explain.log_analyze, because both read the clock on every operation.

What to watch

Make it a habit, not an incident

Finding slow queries during an outage is the hard way. The easy way is a weekly look at the same list while nothing is on fire.

  • Every week, save the top 20 shapes by total time and compare them with last week. A new shape in the top 10 is a code change or a plan change. Both are worth five minutes.
  • Alert on the mean time of your top 5 shapes, not only on CPU. A plan flip shows up there first.
  • Watch rows examined against rows returned. When it grows, an index stopped being used.
  • Keep the slow log on, with a threshold you can afford, and rotated. It is the record you need after an incident.
  • After any bulk load or backfill, refresh statistics: ANALYZE in PostgreSQL, ANALYZE TABLE in MySQL.

Next in this story: once you know which query is slow, the fix is often an index or a schema change on a table too big to lock. That is the next chapter.

Next · chapter 7Change huge tablesOnline schema changes and big deletes← Chapter 5: Connections
Part 4 of 4 · Operate · 21 pagesAll pages

How do I run it in production? What to check when it is slow or broken, where it runs and what it costs, how big it must be, pooling, backups, security, upgrades and other changes made safely.