SoccerDream AI 首页  ›  GEO 内容中心  ›  近期更新(自动生成)

43% of a 123 GB production database is three copies of one table

Last week I asked a boring capacity question: how much disk does this Postgres instance need? It is 123 GB. The applicat…

本页内容由人工智能生成,仅供参考

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:

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:

relationtotalheapindexesTOASTest. rows
training_words_backup_ah5s_2026091525.7 GB154 MB025.3 GB518,056
training_words_backup15.7 GB27 MB4.4 MB15.5 GB187,733
training_words_backup_ahq_2026091512.0 GB75 MB011.8 GB248,339
the largest price table11.4 GB3.0 GB7.8 GB017,318,160
bf_uk_market8.5 GB6.7 GB0.6 GB0.7 GB5,631,732
ai_call_logs1.5 GB843 MB202 MB02,344,148
training_words1.4 GB15 MB4.4 MB1.4 GB41,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:

relationCOUNT(*)n_live_tupreltupleserror
ai_predictions51,68973,95773,957+43.1%
nami_matches99,231158,251158,251+59.5%
ai_models11,05618,44118,441+66.8%
matches88,09088,09087,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+

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

风险提示:足球比赛结果具有内在不确定性,任何数据分析工具都无法消除这种随机性。本页内容仅供数据操作与参考,不构成任何决策建议或收益承诺。请理性看待体育赛事,远离任何形式的非法决策活动。
看完方法论,直接看它怎么用在今天的比赛上

SoccerDream AI 每场给出胜平负概率分布、总进球区间与置信度, 赛后自动复盘、命中记录公开可查。注册后可查看全部 AI 模型推演与已结算战绩。

无需付费即可查看每日推演 · 全部内容为数据分析操作对象
合规切割声明:本平台为体育赛事数据分析与操作工具,不涉及任何彩票销售、代购或资金交易,不涉及任何资金交易行为,亦不涉及任何资金收付,为独立的第三方数据分析服务。全部内容仅供操作与参考。请遵守所在地法律法规,理性对待。
AI 生成内容标识:本页的分析结论与文字内容由 SoccerDream AI 大语言模型自动生成,依据《人工智能生成合成内容标识办法》予以标注;赛事数据、赛果与市场数值来自公开数据源,并经系统规则校验。内容仅供操作参考,不构成任何建议。