Last week I asked a boring capacity question: how much disk does this Postgres instance need? It is 123 GB. The application tables I care about — predictions, matches, models, call logs — total under 14 GB. So where is the other 109 GB?

Five queries produced one uncomfortable finding: the three largest relations are not application tables. They are three dated snapshots of a single 41,292-row table occupying 40.5% of every byte on disk. The largest has no indexes, has not been written to since mid-September, and is 25.7 GB.

This is the audit trail: how to account for bytes without installing anything, why heap size is a lie for text-heavy tables, and why three "row counts" disagreed by up to 67%.

Counting bytes without any extensions

You do not need pgstattuple. pg_class, pg_total_relation_size(), and pg_stat_user_tables are enough, and they answer different questions that people routinely conflate:

  • pg_relation_size() — heap only
  • pg_indexes_size() — all indexes
  • pg_total_relation_size() — heap + indexes + TOAST + TOAST index
  • n_live_tup — an estimate, not a count

Because big text columns live in a side table, any audit that stops at pg_relation_size() under-reports exactly the tables that eat the most disk. The query below joins the TOAST relation back in and closes the accounting against the whole database.

SET statement_timeout = '90s'; -- 1. Does table accounting explain the database? SELECT pg_size_pretty(SUM(pg_total_relation_size(c.oid))) AS tables_total, COUNT(*) AS n_tables, pg_size_pretty(pg_database_size(current_database())) AS db_size, ROUND(100.0 * SUM(pg_total_relation_size(c.oid)) / pg_database_size(current_database()), 2) AS pct FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = 'public' AND c.relkind = 'r'; -- 2. Twelve largest relations, TOAST split out SELECT c.relname, pg_total_relation_size(c.oid) AS total_b, pg_relation_size(c.oid) AS heap_b, pg_indexes_size(c.oid) AS idx_b, COALESCE((SELECT pg_relation_size(x.oid) FROM pg_class x WHERE x.oid = c.reltoastrelid), 0) AS toast_b, c.reltuples::bigint AS est_rows FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = 'public' AND c.relkind = 'r' ORDER BY 2 DESC LIMIT 12; 

The accounting closes to 99.85%: 1,709 heap relations, 123 GB, 0.15% outside tables.

The three biggest objects are copies

Here is what query 2 returned, largest first:

relation total heap indexes TOAST est. rows
training_words_backup_ah5s_20260915 25.7 GB 154 MB 0 25.3 GB 518,056
training_words_backup 15.7 GB 27 MB 4.4 MB 15.5 GB 187,733
training_words_backup_ahq_20260915 12.0 GB 75 MB 0 11.8 GB 248,339
the largest price table 11.4 GB 3.0 GB 7.8 GB 0 17,318,160
bf_uk_market 8.5 GB 6.7 GB 0.6 GB 0.7 GB 5,631,732
ai_call_logs 1.5 GB 843 MB 202 MB 0 2,344,148
training_words 1.4 GB 15 MB 4.4 MB 1.4 GB 41,292

The live table sits seventh at 1.4 GB. The copies contain 518,056, 187,733, and 248,339 rows against a live table of 41,292 — they are not faithful copies at all, but pre-dedup states frozen at 12.5×, 4.5× and 6.0× the live row count.

The 518,056-row copy keeps 154 MB of heap and 25.3 GB of TOAST: 49,640 bytes of payload per row. These are documents, not records, and the two largest have no index.

Sixteen relations of 1 GB or more hold 96 of 123 GB; 1,149 relations under 1 MB share 229 MB. The top 3 are 40.5%, the top 10 are 71%, and the remaining 1,659 tables share 10 GB.

A naming convention is not a retention policy

Matching the conventions people use before a risky migration — %backup%, %_bak%, %_bk%, %_old%, %_archive% in pg_class — returns 266 relations and 54 GB: 43.9% of the database behind names that mean "temporary" to every engineer who reads them and "permanent" to every process that does not. Nobody decided to keep 54 GB; each was a ten-minute decision that never got a delete date.

Why heap size lies for text-heavy tables

The live table has its own surprise: training_words is 1.4 GB total but only 15 MB of heap. 95% of its bytes are TOAST.

SELECT c.relname, pg_size_pretty(pg_relation_size(c.oid)) AS heap, pg_size_pretty(pg_relation_size(t.oid)) AS toast, c.reltuples::bigint AS rows, ROUND(pg_relation_size(t.oid)::numeric / NULLIF(c.reltuples, 0)) AS toast_bytes_per_row FROM pg_class c JOIN pg_class t ON t.oid = c.reltoastrelid WHERE c.relname = 'training_words'; 

15,539 characters per row on average, 60,018 at the maximum. Postgres out-lines anything above roughly 2 KB, so the heap keeps a pointer and TOAST keeps the payload. A dashboard reading pg_relation_size() shows 15 MB and calls it free; it is 1,423 MB. Prompts, training texts and analysis blobs all look like small rows to the planner and like gigabytes to the disk.

The row that got rewritten 515 times

ai_predictions is the opposite problem — not size but churn. It holds 51,689 rows and 462 MB of heap, and has absorbed 26,643,381 updates. That is 515 updates per row that currently exists.

SELECT relname, n_tup_ins, n_tup_upd, n_tup_del, n_tup_hot_upd, n_live_tup, ROUND(100.0 * n_tup_hot_upd / NULLIF(n_tup_upd, 0), 2) AS hot_pct, ROUND(n_tup_upd::numeric / NULLIF(n_live_tup, 0), 1) AS upd_per_row FROM pg_stat_user_tables WHERE relname IN ('ai_predictions', 'matches', 'ai_models') ORDER BY n_tup_upd DESC; -- live payload vs file size: how much of the heap is not row data SELECT COUNT(*) AS n, ROUND(AVG(pg_column_size(t))::numeric, 0) AS avg_row_b, SUM(pg_column_size(t)) AS live_b, pg_relation_size('ai_predictions') AS heap_b, ROUND(100.0 * (1 - SUM(pg_column_size(t))::numeric / pg_relation_size('ai_predictions')), 1) AS dead_pct FROM ai_predictions t; 

Only 48.19% of updates were HOT: 13,803,908 touched every index because they changed an indexed column. With 29 indexes, each non-HOT update writes 29 new tuples and orphans 29 old ones. Autovacuum has run 5,638 times and holds dead tuples at 29; it cannot return space to the filesystem.

The rows occupy 222,046,308 bytes; the heap file is 462,413,824. 52.0% of the heap is not live row data. Average row width is 4,296 bytes, maximum 58,429 — a 13.6× spread driven by one analysis field averaging 1,180 characters and peaking at 98,455. TOAST holds 118,640 tuples for 51,689 rows, a 2.30× ratio.

Three row counts, three answers

Three families of numbers describe these tables:

relation COUNT(*) n_live_tup reltuples error
ai_predictions 51,689 73,957 73,957 +43.1%
nami_matches 99,231 158,251 158,251 +59.5%
ai_models 11,056 18,441 18,441 +66.8%
matches 88,090 88,090 87,059 −1.2%
SELECT c.relname, c.reltuples::bigint AS reltuples, s.n_live_tup, s.n_tup_ins, s.n_tup_del FROM pg_class c JOIN pg_stat_user_tables s ON s.relname = c.relname WHERE c.relname IN ('ai_predictions', 'nami_matches', 'ai_models', 'matches'); 

Two things are wrong at once, in a way that proves neither number is a count.

First, the insert counter contradicts the row count. ai_predictions reports 5,527 lifetime inserts and 44 lifetime deletes yet contains 51,689 rows. matches reports 8,628 inserts, 0 deletes, 88,090 rows. Either the counters were reset, or the table was rebuilt by a path that never touched the row-level insert counter — a CREATE TABLE AS, a restore, a logical reload. All are normal; none announce themselves.

Second, the estimate is stale by an era. nami_matches estimates 158,251 against 99,231 actual — a 59,000-row gap the delete counter (1,394 lifetime) cannot explain. That is not minute-level churn; it is an estimate from a previous shape of the table.

Put together: the counter family and the estimator family are from different epochs and disagree by 43–67% on the three tables that matter most. A capacity alert on n_live_tup > X would have fired 22,000 rows early. A backtest dividing by estimated rows would have understated every rate by 43%.

Only COUNT(*) and pg_total_relation_size() survived verification. Both are expensive, both are honest.

A ledger that fails loudly

Manual queries answer today's question. I wanted a weekly job that reconciles estimated rows, real rows and bytes, and fails when any pair drifts.

import psycopg2 WATCH = ["ai_predictions", "nami_matches", "ai_models", "training_words"] def ledger(cur): rows = [] for t in WATCH: cur.execute(f"SELECT COUNT(*) FROM {t}") real = cur.fetchone()[0] cur.execute("SELECT reltuples::bigint FROM pg_class WHERE relname = %s", (t,)) est = cur.fetchone()[0] or 0 cur.execute("SELECT pg_total_relation_size(%s)", (t,)) total = cur.fetchone()[0] rows.append((t, real, est, total, abs(est - real) / real if real else 0)) return rows with psycopg2.connect(DSN) as conn, conn.cursor() as cur: cur.execute("SET statement_timeout = '120s'") name, real, est, total, drift = max(ledger(cur), key=lambda r: r[4]) if drift > 0.10: raise SystemExit( f"row-count drift {drift:.1%} on {name}: estimate {est} vs actual {real} " f"— rewrite the table or reset stats before trusting any per-row metric" ) 

10% is arbitrary but useful: tight enough to catch an epoch change, loose enough to survive a day of inserts. The failure names the table and demands a rewrite.

What I actually changed

Nothing on disk, deliberately. Those snapshots are the only pre-dedup states of the training corpus; deleting them to reclaim 40% of the disk would be data loss dressed as housekeeping. The sequence is: prove the live table is a superset rows-for-rows, export the diff, then drop.

What changed is the instrument: capacity reporting sums pg_total_relation_size() by bucket and prints the top 3 explicitly; every published rate divides by COUNT(*) or a materialised count, never n_live_tup; non-HOT update share is tracked per table, because at 51.8% of writes touching every index that ratio predicts write latency better than row count does.

The lesson applies to any audit: when three numbers claim to describe the same object, the work is not choosing the convenient one. It is writing down all three and the reason they differ.

Analytics and research content. Not betting advice. 18+

本内容仅供数据分析与研究参考,不构成任何决策建议。