48.9 seconds for 20 rows: auditing a Postgres database whose query statistics were never switched on
The instrument was installed, not switched on
Last week I asked production for the twenty most recent rows of a 17-million-row table. It took 48.9 seconds.
The same query, with three words added to the ORDER BY, returns in 0.21 ms. That is a 230,000x gap, and it is not the interesting part. The interesting part is that none of the instruments I thought I had could have found it for me.
One production instance throughout: PostgreSQL 15.18, 116 GB, shared_buffers 8 GB, work_mem 24 MB, max_parallel_workers_per_gather = 1.
pg_stat_statements requires a preload at postmaster start. The extension installs the view; the preload installs the numbers. I had the first, not the second:
SELECT extname FROM pg_extension ORDER BY 1;
-- dblink, pg_stat_statements, pg_trgm, plpgsql
SELECT count(*) FROM pg_stat_statements;
-- ERROR: pg_stat_statements must be loaded via shared_preload_libraries
Nothing in the application surfaced this. When the audit question is always "which query is expensive", a view without data means the answer is a guess - not "approximately", structurally unavailable.
What is left: lifetime counters with no attribution
Remove per-query history and all you have is pg_stat_user_tables: a lifetime counter bundle that knows a table was scanned 4 billion times and refuses to say by whom.
SELECT relname, n_live_tup, seq_scan, idx_scan, n_tup_ins, n_tup_upd, n_tup_del,
to_char(last_autovacuum, 'MM-DD HH24:MI') AS last_av,
to_char(last_analyze, 'MM-DD HH24:MI') AS last_an
FROM pg_stat_user_tables
WHERE relname IN ('ai_predictions', 'nami_matches', 'nami_europe_odds', 'odds_snapshot_ledger')
ORDER BY n_live_tup DESC;
| table | live rows | seq scans | index scans | updates | last analyze |
|---|---|---|---|---|---|
| nami_europe_odds | 17,147,413 | 14,041 | 4,157,882,455 | 82,289,979 | - |
| nami_matches | 133,734 | 2,333,243 | 17,068,342,053 | 1,368 | - |
| ai_predictions | 50,949 | 100,991 | 3,440,138,343 | 44 | 11-10 06:30 |
Read the last two rows together. ai_predictions holds 50,949 rows and has served 3.44 billion index scans: 67,521 scans per live row, which over the 160 days this platform has prediction history is roughly 250 per second.
nami_matches holds 133,734 rows and has served 17.07 billion: 127,630 per row. A 50k-row table probed 250 times a second is not a bad schema. It is a read pattern nobody measured, and the counters are the only evidence it exists.
The same counters cannot be reconciled
ai_predictions reports 25,676,350 inserts, 75 deletes, and 50,949 live rows: inserts minus deletes is off by a factor of 504.
The id sequence agrees something odd happened - it stands at 1,450,671, and the maximum surviving id is 1,450,671, minimum 8,733. Only a TRUNCATE or a table rebuild holds 25.7M inserts and 50k rows without an incrementing delete counter.
Neither leaves a trace, and stats_reset is NULL, so no timestamp bounds the window. I can read the counter; I cannot reconstruct the interval. Any rate derived from it - rows per day, growth per month - is an invented number wearing a real column name.
The instrument that always works: watch the buffers
EXPLAIN (ANALYZE, BUFFERS) needs no preload. It reports what the planner thought, what actually happened, and how much of it happened in 8 kB pages.
Five queries, measured back to back:
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT p.model_id, sum(CASE WHEN p.hit THEN 1 ELSE 0 END)::numeric / NULLIF(count(*),0)
FROM ai_predictions p WHERE p.settled GROUP BY 1 ORDER BY 2 DESC LIMIT 10;
| query | plan cost | actual | shared buffers | buffers in GiB |
|---|---|---|---|---|
| leaderboard (settled hit rate per model) | 36,962 | 61.1 ms | 22,353 | 0.17 |
| monthly hit rate | - | 64.8 ms | 22,350 | 0.17 |
| full count of nami_europe_odds | 262,731 | 1,386.0 ms | 810,899 | 6.2 |
| top 20 rows by changed_at DESC | 609,662 | 48,899.0 ms | 1,408,491 | 10.7 |
| fan-out join, prediction x price rows | 709,185 | 6,418.7 ms | 2,378,473 | 18.1 |
The real work of this platform is cheap. The two queries answering "how accurate is each model" and "how did accuracy move by month" cost 126 ms and 0.34 GiB of logical reads together. Everything expensive was something I wrote by accident.
Cost does not rank time either: the 709k-cost join finished 7.6x faster than the 610k-cost sort, because the sort paid 34,606 physical block reads and the join came out of cache. Cost is a cached-page fiction. Buffers are not.
48.9 seconds for 20 rows
Here is the pair, run minutes apart on the same table:
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT match_id, changed_at FROM nami_europe_odds ORDER BY changed_at DESC LIMIT 20;
-- Limit (actual time=48799.5..48898.9 rows=20)
-- -> Parallel Index Only Scan using idx_eu_match_company_time
-- (actual time=0.027..47911.0 rows=8611882 loops=2)
-- Heap Fetches: 407884
-- Buffers: shared hit=1,373,885 read=34,606
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT match_id, changed_at FROM nami_europe_odds ORDER BY changed_at DESC NULLS LAST LIMIT 20;
-- Limit (actual time=0.052..0.201 rows=20)
-- -> Index Scan using idx_neo_changed_desc (actual time=0.052..0.199 rows=20)
-- Buffers: shared hit=16
17,223,764 index tuples read to produce 20 rows, versus 16 pages. 270 MB pulled from disk.
The cause is not a missing index; an index for exactly this order exists, 543 MB of it:
CREATE INDEX idx_neo_changed_desc ON nami_europe_odds USING btree (changed_at DESC NULLS LAST);
PostgreSQL's default for DESC is NULLS FIRST. The index was declared NULLS LAST, so it cannot satisfy ORDER BY changed_at DESC, and the planner reached for the only index whose leading columns cover the query.
changed_at holds zero NULLs - count(*) WHERE changed_at IS NULL is 0 - but the column is nullable, and the planner may not reason from "currently zero" to "cannot be NULL". A NOT NULL constraint, or NULLS LAST in the query, and the 48.9 seconds disappears.
The 543 MB index has been scanned 3,841,275 times; the ..._changed_at_brin beside it, zero. Both facts are visible only because someone asked.
1,104 price rows per prediction
The expensive query I actually wrote was an attribution question: which price snapshot drove which prediction. The obvious join does it:
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT count(*) FROM ai_predictions p JOIN nami_europe_odds o ON o.match_id = p.match_id;
-- Nested Loop (actual time=0.086..4895.280 rows=28121691 loops=2)
-- Index Only Scan using idx_neo_mid_company on nami_europe_odds o
-- (actual time=0.006..0.102 rows=1104 loops=50949)
-- Execution Time: 6418.706 ms
50,949 predictions multiplied by an average of 1,104 price rows per fixture yields 56,243,382 intermediate rows - a 1,104x amplification of a question that only needed counts. Wrap it in GROUP BY model_id and it costs 12.3 seconds.
The reader wanted one number per model; the database built 56 million rows to find 4,008.
The guard I now put in front of every audit query costs one round trip and no execution:
import json, psycopg2
ROW_BUDGET = 200_000
def plan_rows(conn, sql):
with conn.cursor() as cur:
cur.execute("EXPLAIN (FORMAT JSON) " + sql)
node = cur.fetchone()[0][0]["Plan"]
total = 0
stack = [node]
while stack:
n = stack.pop()
total += n.get("Plan Rows", 0) if n["Node Type"] != "Limit" else 0
stack.extend(n.get("Plans", []))
return total
def guarded(conn, sql):
est = plan_rows(conn, sql)
if est > ROW_BUDGET:
raise RuntimeError(f"refused: plan builds ~{est:,} rows (budget {ROW_BUDGET:,})")
with conn.cursor() as cur:
cur.execute(sql)
return cur.fetchall()
On the join above it reports 26,459,498 estimated rows and refuses in 1.07 ms - the planning time the server printed. The estimate is 2.13x under the truth, which is fine: the budget is a floor check, not a model. A query wrong by 2x in the millions is never a query I wanted.
1,340 indexes that have never been scanned
Indexes charge every write, not the query you are optimizing.
SELECT tablename,
regexp_replace(indexdef, '^CREATE (UNIQUE )?INDEX \\S+ ON \\S+ ', '') AS shape,
count(*) AS n,
string_agg(indexname,' + ') AS names,
pg_size_pretty(sum(pg_relation_size(indexrelid))) AS total,
string_agg(s.idx_scan::text,' / ') AS scans
FROM pg_stat_user_indexes s
JOIN pg_indexes x ON x.indexname = s.indexrelname AND x.tablename = s.relname
WHERE s.schemaname = 'public' AND indexdef NOT LIKE '%WHERE%'
GROUP BY 1,2 HAVING count(*) > 1
ORDER BY sum(pg_relation_size(indexrelid)) DESC;
| table | shape | indexes | size | scans |
|---|---|---|---|---|
| nami_europe_odds | (match_id, company_id, changed_at DESC) | 2 | 1,557 MB | 1,907,403,484 / 0 |
| nami_bd_odds_snapshot | (nami_match_id, lottery_type, snapshot_time DESC) | 2 | 57 MB | 0 / 789,599 |
| nami_matches | (away_team_id, match_time DESC) | 2 | 6,008 kB | 0 / 9,543,153 |
Two byte-identical 1 GB-class b-trees on the hottest table: one served 1.9 billion scans, the other none, and all 82,289,979 updates to that table maintained both.
Across the schema: 3,079 indexes, 1,340 of them scanned zero times, occupying 3,060 MB. A unique constraint is a guard, not a plan node, so some idle indexes are legitimate. A 520 MB duplicate with a scan count of exactly zero is not a guard. It is a write tax.
Never analyzed, and one worker
last_analyze is NULL on nami_europe_odds: 17 million rows, 11 GB of heap, never analyzed at any point the statistics remember. And max_parallel_workers_per_gather is 1, so the 48.9-second sort split its scan across exactly two processes.
None of this needs a profiler. It needs five queries a week and a belief in buffer counts.
The preload is the real fix - one line in postgresql.conf, one restart - but it only tells you where the cost already went. EXPLAIN (ANALYZE, BUFFERS) tells you what a query will cost before you ship it, which is the only moment the information is still cheap.
What I changed:
- Plan first. Anything estimated above 200k intermediate rows is rewritten, not waited on.
- Specify
NULLS LASTwhen the index saysNULLS LAST, and addNOT NULLwherever "zero NULLs today" is load-bearing for a plan. - Quote a counter with no reset timestamp as a counter, never divided by a date.
- Delete a duplicate index only after reading its scan count; one side of that 1,557 MB pair had served 1.9 billion scans.
The 20-row query now takes 0.21 ms. What took 48.9 seconds was never the database. It was me, not looking.
Analytics and research content. Not betting advice. 18+ ๆฌๅ ๅฎนไป ไพๆฐๆฎๅๆไธ็ ็ฉถๅ่๏ผไธๆๆไปปไฝๅณ็ญๅปบ่ฎฎใ
Comments
No comments yet. Start the discussion.