Featured image of post It's Almost Always the Queries, Part III: When the CPU Is Pegged

It's Almost Always the Queries, Part III: When the CPU Is Pegged

This part of the series is about a database server that keeps getting busier. The slowest statement anyone can find takes half a second and runs every two seconds. Sorted by average time it leads the list by a wide margin, and it is the only statement in the slow-query log. Fixing it would give back about a quarter of the query time. Which statement has the other three quarters, and why does no list sorted by speed show it?

TL;DR
A database pinned on CPU is rarely running one expensive query. More often a cheap query runs very often, and both the slow-query log and any list sorted by average time put it at the bottom. Sorting by total time finds it, and the fixes are ways to run it less or to make each run read fewer rows. A workload of evenly expensive queries is the exception, and that one needs the cores.

The habit when a database is busy is to look for the slow query. It is a reasonable habit, because the slow-query log exists for exactly that and a 500 ms statement is easy to feel bad about. But CPU is spent by time per call multiplied by calls, and the log only looks at the first number.

To see how far apart those two views get, I ran four statements against the 5-million-row orders table from Part I for a minute, at 4,300 queries a second on a 2-CPU PostgreSQL 18 server. The mix is an ordinary one: a count for a badge, a lookup by primary key, an order list showing an account’s 20 newest orders, and a 30-day revenue report that scans the whole table and ran about once every two seconds.

StatementCalls in 60 sMean per callTotal timeShare of totalIn the slow log
Order list, 20 newest17,7183.0 ms53.8 s72%0
30-day report35503.6 ms17.6 s24%35
Open-order count179,1900.013 ms2.3 s3%0
Lookup by id59,8740.009 ms0.5 s1%0

PostgreSQL 18, 2 CPUs, pg_stat_statements after one 60 s run, slow log threshold 100 ms. The server averaged 55% CPU.

Two bar panels over the same four statements. Sorted by mean time: the 30-day report at 503.6 ms, then the order list at 3.0 ms, the count at 0.013 ms and the lookup at 0.009 ms. Sorted by total time: the order list at 53.8 s, the report at 17.6 s, the count at 2.3 s and the lookup at 0.5 s.

The slow log recorded 35 statements in that minute and every one was the report. Sorted by mean time the report is 166 times slower than anything else. And it accounts for a quarter of the time the server spent running queries. The order list, at 3 ms a call, has nearly three quarters, and it never came within 40 ms of the log’s threshold.

MySQL 8.4 gave the same ranking from events_statements_summary_by_digest. The order list had 204 s of total time against 27 s for the report, and of the 50 slow-log entries, 31 were the report.

A faster report would not have helped

The first move is to fix the report, since it is the only statement with evidence against it. Rewriting it or moving it to a replica is worth doing, and it would give back 24% of the query time. The server would be busy again at the next step in traffic, because the statement that grows with every page view is still there. The bigger instance has the same problem, and Part I measured it: four times the CPUs served four times the queries.

What finds the order list is the sort order. In pg_stat_statements it is total_exec_time, and on MySQL SUM_TIMER_WAIT in performance_schema.events_statements_summary_by_digest. Two more columns say why a statement is there. This is a second run of the same mix, a little slower because later tests had grown the table to 6.1 million rows:

1
2
3
4
5
6
               query                |  calls  | mean_ms | total_ms | pct | pages_per_call | rows_per_call
------------------------------------+---------+---------+----------+-----+----------------+---------------
 SELECT id, total_cents, created_at |   17900 |   5.520 |    98805 |  77 |           2459 |            20
 SELECT status, count(*), sum(total |      30 | 732.103 |    21963 |  17 |          81931 |             4
 SELECT id, account_id, status, tot |   59427 |   0.070 |     4180 |   3 |              4 |             1
 SELECT count(*) FROM orders WHERE  |  180674 |   0.015 |     2759 |   2 |              5 |             1

pages_per_call is (shared_blks_hit + shared_blks_read) / calls. The order list reads 2,459 pages to return 20 rows, which is a query doing more work than its answer needs. The count reads 5 pages 180,674 times, which is a query that is as cheap as it will get and can only be run less.

Note
Two things about these views. pg_stat_statements adds up everything since the last pg_stat_statements_reset() or restart, so the top of the list is history. During an incident, compare two snapshots a minute apart, or reset and wait. And total time is elapsed time, so it includes waiting on locks and disk. A statement can lead the list while using no CPU at all. The pages column separates the two.

What a count costs, even with the right index

The count in that mix was cheap because Part I gave it an index on (account_id, status) and the account had 98 open orders. That index does not make a count free. It makes the cost follow the number of rows counted, and that number belongs to the customer.

A database cannot keep one stored total to hand back. Under MVCC two transactions can correctly see different counts at the same moment, and the PostgreSQL wiki says so directly: “PostgreSQL must walk through all rows to determine visibility.” The MySQL manual gives the same reason for InnoDB, which “does not keep an internal count of rows in a table because concurrent transactions might ‘see’ different numbers of rows at the same time.” (MyISAM did keep one, which is where the old advice that counting is free came from.)

I added four larger accounts to the table and timed three ways of answering “how many open orders”: the exact count, a count capped at 100, and the planner’s estimate read out of EXPLAIN.

Open orders in the accountExact countCapped at 100Planner estimateEstimate with extended statistics
980.04 ms0.04 ms540529
1,0000.06 ms0.04 ms540529
10,0000.32 ms0.04 ms2,21513,444
100,0002.80 ms0.04 ms23,21599,408
1,000,00017.65 ms0.04 ms221,520992,854

PostgreSQL 18, one connection, median of an 8 s run each, all pages marked all-visible (the fast-path condition explained below). The estimate took 0.06 ms at every size. The last two columns are the estimated row counts, not times.

Bar chart of count time by number of matching rows. Exact count: 0.04 ms for 98 rows, 0.06 ms for 1,000, 0.32 ms for 10,000, 2.80 ms for 100,000 and 17.65 ms for 1,000,000. The count capped at 100 takes 0.04 ms at every size.

The exact count is fine for the 98-order account and costs 440 times more for the largest one, so the badge is cheapest for the customers who matter least. The capped version stops after 100 index entries and stays at 0.04 ms:

1
2
3
SELECT count(*) FROM (
  SELECT 1 FROM orders WHERE account_id = $1 AND status = 'open' LIMIT 100
) t;

The estimate surprised me. I expected it to be close, and it was off by roughly five times at both ends: 540 for a real 98, and 221,520 for a real million. The planner multiplies the share of rows with that account by the share with that status as if the two were unrelated, and here they are not. CREATE STATISTICS ... (mcv, dependencies) ON account_id, status brought the three large accounts to within 35% (13,444 for 10,000 was the worst), and left the small ones at 529. An estimate is usable for “about a million” and not for a badge that says 98.

Answering from the index alone, which the plan calls an index-only scan, has its own condition. PostgreSQL can do it only for pages the visibility map marks all-visible, meaning every row on the page is visible to every transaction, and it is VACUUM that sets those marks. For any other page it goes to the table to check the row, and the plan counts each of those trips as a heap fetch. I updated 10% of the 100,000-order account’s rows and ran the count again:

State of the tableHeap fetchesPages readTime
All pages all-visible0825.2 ms
After updating 10,000 of the account’s rows110,0001,55810.7 ms
After a plain VACUUM100,0001,4249.2 ms
After VACUUM (INDEX_CLEANUP ON)090not re-timed

EXPLAIN (ANALYZE, BUFFERS) on PostgreSQL 18, autovacuum off for the table during the test. These times are higher than the table above because EXPLAIN ANALYZE adds its own overhead.

The third row is the one I did not expect. VACUUM ran, finished, and the count still went to the table for every row. Its verbose output says why: index scan bypassed: 1334 pages from table (1.63% of total) have 10000 dead item identifiers. When few pages hold dead rows, VACUUM skips the index pass to save work (the documentation describes this as the default AUTO behavior of INDEX_CLEANUP), and a page that still holds dead item identifiers, the stubs removed rows leave behind until the index pass clears them, cannot be marked all-visible. So on a big table where a small, busy slice keeps changing, the slice a count reads can stay off the fast path through several vacuums. It doubled the cost here. It did not break anything, and it is the sort of thing that makes a count slower over months with no change to the query.

More connections than cores

The other way to waste CPU has nothing to do with any one statement. I ran the order list from 2 connections up to 500 against the same 2-CPU server, each connection sending as fast as it could.

ConnectionsQueries per secondp50p95p99
29611.9 ms2.8 ms4.8 ms
49154.3 ms7.3 ms12.0 ms
1688219.1 ms32.3 ms42.8 ms
6491773.5 ms126.3 ms161.4 ms
200845236.5 ms417.0 ms539.3 ms
500666639.6 ms1,555.4 ms2,468.7 ms

PostgreSQL 18, 2 CPUs, 25 s per run, CPU at 95–100% throughout.

Bar chart of queries per second by connection count on 2 CPUs: 961 with 2 connections, 915 with 4, 856 with 8, 882 with 16, 917 with 64, 845 with 200 and 666 with 500. The 95th-percentile response time under each label rises from 2.8 ms to 1,555 ms.

This came out milder than the usual warning. From 4 to 200 connections the server finished within 12% of its best run, so a pool ten times too large cost little throughput. At 500 it finished 31% fewer queries, with the CPU graph still reading 96%. That missing third is the server switching between 500 processes on 2 cores.

The response times need a caveat, because in a test like this more connections always means more waiting. What the table shows is where the waiting happens. With 500 connections each query waits inside the database, holding a server process (a backend) and its memory. With a pooler such as PgBouncer set near the core count, the same queries wait in the pooler and the database runs the 4-connection row. The cost is a queue to watch, and a pool set too small becomes its own outage when every slot is held by something slow.

The fixes, and what each one costs

The order list was the statement worth fixing. An index is not the only way to make a statement cheaper, and which way fits depends on what the answer is used for. The one I measured for the list is an index that hands back rows already in order:

1
CREATE INDEX orders_account_created_idx ON orders (account_id, created_at DESC);

The plan went from an index scan plus a sort over 2,500 rows (2,461 pages, 4.98 ms) to reading the first 20 entries (23 pages, 0.14 ms). On the same 2 CPUs with 4 connections, the ceiling for that query went from 915 a second to 63,913. The index is 158 MB on the 6.1-million-row table and every insert now maintains it, a write cost I did not measure.

A cache in front of the query is the other common route. The first page of an account’s orders, kept in the application or a cache server for a few seconds, takes the statement off the top of the list without touching the schema. What it costs is a list that can be stale by the cache lifetime, plus invalidation on every write wherever stale is not acceptable. I did not measure it.

A count has more options than a list does, because many counts do not need to be exact, or current, or either.

Way to answer “how many”What comes backWhat it costsWhere it fits
Exact count on the covering indexExact, currentGrows with the rows counted: 0.04 ms for 98, 17.65 ms for 1,000,000Small counts, or a number shown rarely
Count capped with LIMIT 100Exact up to the capFlat at 0.04 ms; the interface says “99+”Badges
Cached count, in the application or a summary tableExact as of the last refreshOne count per refresh interval, and a number that is stale by that intervalDashboards, and anything nobody acts on within the minute
Counter kept up to date on writeExact, currentEvery insert and status change also updates the counter row, and writers sharing one counter queue on itA number that must be exact and is read far more often than it changes
Planner estimate for the filter, read from EXPLAINApproximateFlat at 0.06 ms; off by about five times here until extended statistics were addedOrder-of-magnitude decisions about a filtered set
Table statistics from the catalogApproximate, whole table onlyOne catalog read; as fresh as the last ANALYZE or autovacuum runGuardrails

The exact, capped and planner-estimate rows are the measurements from the count section above. The cached count, the counter and the catalog read are reasoned from how they work; I did not run them. A per-account counter spreads the write queue out, and a single global one concentrates it.

The last row is the one that tends to be overlooked. A lot of counts are guardrails. A build or migration job that checks how big a table is, to decide whether it can run now or has to wait until after hours, does not need the number. It needs to know whether the table holds ten thousand rows or a hundred million. SELECT reltuples FROM pg_class WHERE relname = 'orders' answers that from the catalog without reading the table, and on MySQL information_schema.TABLES.TABLE_ROWS does the same job, as an estimate that the manual itself calls rough for InnoDB. Running count(*) for that question reads the whole table to find out whether reading the whole table is safe.

Warning
A badge in the global navigation is the expensive place for a count. It runs on every page of every signed-in user, so its call count follows total page views instead of visits to one screen. That is the pattern to look for in the calls column: one statement with ten times the calls of anything near it.

Some servers are busy because the work is real. A reporting database, or a nightly load, will sit at high CPU with a top-ten list of statements that each read about as many pages as their answers need. That list has no outlier in calls and none in pages per row, and more cores is the right purchase. The check before buying them is one query, sorted by total time, with calls and pages per call beside it. In the run above the order list is the first line of that output: 17,900 calls, 2,459 pages each, 20 rows back.

SELECT insights FROM experience WHERE downtime = 0; -- Ruslan Tolkachev