finding slow queries
pg_stat_statements, auto_explain, and the N+1 pattern seen from the database's side.
- address
- everything.optimizer.finding_slow_queries
- part
- part 10, the optimizer
- chapter
- chapter 9 of 10
- reading time
- 8 min
pg_stat_statements keeps a running total for every distinct statement the server runs: calls, rows, time, pages. sort it by total time and you know where the database spends its day. auto_explain writes the plan of any statement slower than a threshold to the log, so you see the plan it actually ran with.
and the N+1 pattern, invisible in any single query, is obvious there: one statement with thousands of calls and one row per call.
the picture
you know how everyone has a "slow query" story, and the query turns out to be fast? 2 ms, run 400,000 times an hour. no single execution is slow. the total is.
think of a shop's receipts. looking at one receipt tells you nothing about where the money goes. a summary by product does: "milk, 900 sales, 1 each". pg_stat_statements is the summary by product, with each query's constants taken out so WHERE id = 42 and WHERE id = 43 count as one statement.
here's an orders page loaded two ways, seen from a real server:
| callsint8 | rowsint8 | pagesint8 | querytext |
|---|---|---|---|
| 100 | 100 | 301 | SELECT sum(qty) FROM order_items WHERE order_id… |
| 1 | 0 | 728 | DO $$ DECLARE r record; n bigint; BEGIN FOR r I… |
| 1 | 100 | 89 | SELECT id FROM orders ORDER BY ordered_at DESC,… |
| 1 | 100 | 242 | SELECT o.id, sum(oi.qty) AS items FROM (SELECT … |
pg_stat_statements
it's an extension that ships with postgres, but it has to be loaded when the server starts, because it hooks into every backend:
shared_preload_libraries = 'pg_stat_statements'then restart, and CREATE EXTENSION pg_stat_statements; in the database you'll query it from. it can't run in this page: the browser's postgres is a single process with no server to restart, and the extension isn't built into it. that's why everything in this chapter's figures comes from a real server.
on a server, the view has one row per (user, database, normalized query). the columns that matter most:
- calls and rows: how many times, and how many rows in total.
- total_exec_time, mean_exec_time, max_exec_time, stddev_exec_time: milliseconds. total is load, mean is latency.
- shared_blks_hit, shared_blks_read: pages from the buffer pool and from outside it. reads are the I/O.
- total_plan_time: planning, when
pg_stat_statements.track_planningis on. - query: the text with constants replaced by
$1,$2. that's what makes 400,000 calls one row.
the two queries everyone keeps around:
-- where does the time go? (load)
SELECT calls, round(total_exec_time) AS total_ms, round(mean_exec_time, 2) AS mean_ms, rows, query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;
-- what's slow per call? (latency)
SELECT calls, round(mean_exec_time, 2) AS mean_ms, query
FROM pg_stat_statements
WHERE calls > 10
ORDER BY mean_exec_time DESC
LIMIT 10;totals accumulate until SELECT pg_stat_statements_reset(). reset before a test, or compare two snapshots, so last month's traffic doesn't drown today's.
N+1, from the database's side
an ORM loads 100 orders, then touches order.items on each one, and each touch is a query. in the application's logs it's 101 fast queries. in pg_stat_statements it's this:
any one of those 100 calls, on its own, looks perfect:
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF)
SELECT sum(qty) FROM order_items WHERE order_id = 9999;an index scan on the primary key, a handful of pages. nothing for EXPLAIN to improve, and nothing a slow query log would ever catch. the problem is the count, and only the summary shows it.
the signature: calls in the thousands, rows per call around 1, a filter on a foreign key, and a twin query with LIMIT $1 whose calls match the page loads. each call is cheap, but each one is a network round trip, a parse, a plan (unless prepared) and an executor start-up, and that overhead is most of the cost. the fix lives in the application (eager loading, a join, WHERE order_id = ANY($1)), which is ORMs and N+1's subject.
calls = 48,000, rows = 48,000, mean 0.05 ms. what is it most likely? calls | rows | mean_ms | query
--------+-------+---------+-----------------------------------------
48000 | 48000 | 0.05 | SELECT * FROM order_items WHERE order_id = $1auto_explain: the plan it actually ran
pg_stat_statements tells you which statement. it doesn't keep plans. auto_explain logs the plan of every statement that runs longer than auto_explain.log_min_duration, with EXPLAIN ANALYZE numbers if you ask, at the moment it ran slowly: with the parameters, statistics and cache it had then, which a later EXPLAIN in psql may not reproduce.
it can be loaded into a single session with LOAD (as a superuser), or for every session with session_preload_libraries or shared_preload_libraries. in the browser's postgres the module isn't there:
LOAD 'auto_explain';on a real server, with the shop dataset, every statement logged and the log sent to the client so we can see it:
LOAD 'auto_explain';
LOAD
SET auto_explain.log_min_duration = 0;
SET
SET auto_explain.log_analyze = on;
SET
SET auto_explain.log_timing = off;
SET
SET auto_explain.log_level = notice;
SET
SELECT count(*) FROM orders WHERE customer_id = 42;
NOTICE: duration: 0.247 ms plan:
Query Text: SELECT count(*) FROM orders WHERE customer_id = 42;
Aggregate (cost=208.01..208.02 rows=1 width=8) (actual rows=1.00 loops=1)
-> Seq Scan on orders (cost=0.00..208.00 rows=5 width=0) (actual rows=7.00 loops=1)
Filter: (customer_id = 42)
Rows Removed by Filter: 9993
count
-------
7
(1 row)in production you'd set log_min_duration to something like 250ms and leave log_level at its default (the server log). log_analyze makes every statement pay for instrumentation, not just the slow ones, so keep log_timing off and consider auto_explain.sample_rate on a busy server. log_nested_statements catches the queries inside functions.
the loop
hover a stage.
the reproduce step is EXPLAIN ANALYZE. the fix step is most of this part: when estimates go wrong, extended statistics, generic plans for the "fast in psql, slow in the app" case, why an index isn't used, and steering the planner for the last resort. two smaller tools fill gaps: log_min_duration_statement logs slow statements' text without plans, and pg_stat_activity shows what's running right now.
keylines
- pg_stat_statements: one row per normalized statement, with calls, rows, time and pages. needs shared_preload_libraries.
- sort by total time for load, by calls for chatty code, by mean for latency.
- N+1 from the database's side: huge calls, about one row per call.
- auto_explain logs the plan a slow statement actually ran with.
- find, catch, reproduce, fix, check. settings come last.