Skip to content

Diagnosing table and index bloat in PostgreSQL — measure before you rewrite

Measure PostgreSQL bloat with pgstattuple and pg_stat_user_tables, read autovacuum progress, and decide when routine VACUUM is enough versus pg_repack or VACUUM FULL.

A table that keeps growing on disk while its row count stays flat is bloated: dead row versions and unused free space that vacuum has not reclaimed, or cannot reclaim without a rewrite. Before you reach for VACUUM FULL or pg_repack, you need a number — how much of the table is actually dead space, and whether autovacuum is keeping up or falling behind. This article is about that measurement. You will use pg_stat_user_tables for a fast, always-available signal, pgstattuple for an exact count, and pg_stat_progress_vacuum to see what autovacuum is doing right now, then map those numbers onto a decision: leave it alone, tune the per-table thresholds, or rewrite the table. It assumes PostgreSQL 16 or 17 and does not re-explain how vacuum works — for that, start with VACUUM and autovacuum.

What you’ll accomplish

  • Get a fast dead-tuple ratio for every table from pg_stat_user_tables, with no locks and no extension.
  • Get an exact bloat percentage for a suspect table with pgstattuple, and understand why it costs a full scan.
  • Read pg_stat_progress_vacuum to tell whether autovacuum is running, stalled, or never scheduled.
  • Decide, from the measured numbers, whether routine autovacuum suffices, the thresholds need tuning, or the table needs a rewrite.
  • Set per-table autovacuum_vacuum_scale_factor so a hot table is vacuumed on its own schedule.

Prerequisites

  • PostgreSQL 16 or 17. The catalog columns and progress views used here also exist back to PostgreSQL 13, with pg_stat_progress_vacuum present since 9.6; pgstattuple has been a contrib module for many years.
  • A role that can read the statistics views (any login role can) and, for pgstattuple, either superuser or membership in pg_stat_scan_tables.
  • The pgstattuple extension available as a package. On Debian and Ubuntu it ships in postgresql-contrib; on RHEL family it is in postgresql16-contrib. Installing the package does not enable the extension — you still run CREATE EXTENSION.
  • Some idea of your busiest tables. Bloat that matters is almost always on tables that take heavy UPDATE or DELETE traffic; append-only tables rarely bloat.

One honest caveat: the fast statistics are estimates. n_dead_tup comes from the cumulative statistics system and can drift, reset on crash, or lag reality. Treat it as a smoke alarm, not a scale.

How it works

PostgreSQL never updates a row in place. An UPDATE writes a new version and marks the old one dead; a DELETE just marks it dead. Those dead versions stay on the page until vacuum visits them, at which point their space is marked reusable — for a future INSERT or UPDATE on the same table. Plain vacuum does not shrink the file; it recycles space inside it. The table only stays flat if new rows keep reusing what vacuum frees.

Lifecycle of a row version from live to dead to reclaimed free space to reused, with a note that plain VACUUM does not return disk to the OS

Bloat is what happens when that loop breaks. If vacuum falls behind the write rate, dead tuples accumulate faster than they are reclaimed, and the table grows new pages to hold them. Even after vacuum catches up, that growth is permanent free space — the file is large, mostly empty, and plain vacuum will never give the disk back. Diagnosis is therefore two questions: how much dead space and empty space is in the table right now (pgstattuple), and is autovacuum currently keeping pace (pg_stat_user_tables deltas and pg_stat_progress_vacuum). The answers pick your remedy.

Step-by-step

  1. Get the fast dead-tuple ratio for every table. This reads cached statistics, takes no locks, and runs in milliseconds. It is your triage list.
SELECT schemaname, relname,
       n_live_tup, n_dead_tup,
       round(n_dead_tup * 100.0 / nullif(n_live_tup + n_dead_tup, 0), 1) AS dead_pct,
       last_autovacuum, last_analyze
FROM pg_stat_user_tables
WHERE n_dead_tup > 0
ORDER BY n_dead_tup DESC
LIMIT 20;

Expected output is one row per table, most-dead first:

 schemaname |   relname    | n_live_tup | n_dead_tup | dead_pct |        last_autovacuum        | last_analyze
------------+--------------+------------+------------+----------+-------------------------------+--------------
 public     | orders       |    2841002 |     418773 |     12.8 | 2026-07-24 09:12:41.882+00    | ...
 public     | sessions     |      90114 |     220548 |     71.0 | 2026-07-23 22:05:10.114+00    | ...

A high dead_pct with an old or null last_autovacuum — like sessions above — is the signature of autovacuum not keeping up.

  1. Confirm the suspect with an exact count. pg_stat_user_tables estimates; pgstattuple reads every page and reports the truth. Enable it once per database, then scan the table.
CREATE EXTENSION IF NOT EXISTS pgstattuple;
SELECT * FROM pgstattuple('public.sessions');

Expected output — one row of exact byte accounting:

-[ RECORD 1 ]------+-----------
table_len          | 486539264
tuple_count        | 90088
tuple_len          | 61259840
tuple_percent      | 12.59
dead_tuple_count   | 220548
dead_tuple_percent | 24.7
free_percent       | 58.3

Read it as two separate problems. dead_tuple_percent is space vacuum can still reclaim in place. free_percent is empty space already reclaimed but not returned — 58 percent here means the file is more than half air. High free space plus low dead space means vacuum already ran; the table is simply oversized and only a rewrite shrinks it.

  1. Use the estimate function on very large tables. A full pgstattuple scan reads the whole table and competes for I/O. On a multi-hundred-gigabyte table, use the sampling estimator instead — it reads a fraction of pages.
SELECT * FROM pgstattuple_approx('public.orders');

The output adds an approx_ prefix to the percentages and is close enough to decide. Use the exact function only on the one or two tables you have narrowed down to.

  1. Check index bloat separately. Indexes bloat independently of their table, and a bloated index slows every lookup. pgstattuple reads a B-tree index directly and reports the space actually holding entries.
SELECT avg_leaf_density, leaf_fragmentation
FROM pgstatindex('public.orders_customer_id_idx');

An avg_leaf_density well under 70 (a freshly built index sits near 90) means the index is loose and a REINDEX CONCURRENTLY will shrink it.

  1. See what autovacuum is doing right now. If a big table is being vacuumed, this view shows the phase and how far along it is.
SELECT p.pid, p.relid::regclass AS table, p.phase,
       p.heap_blks_total, p.heap_blks_scanned,
       round(p.heap_blks_scanned * 100.0 / nullif(p.heap_blks_total, 0), 1) AS pct_done
FROM pg_stat_progress_vacuum p;

Expected output when a vacuum is in flight:

  pid  |  table  |       phase        | heap_blks_total | heap_blks_scanned | pct_done
-------+---------+--------------------+-----------------+-------------------+----------
 48821 | orders  | scanning heap      |           59392 |             21044 |     35.4

No rows means nothing is vacuuming at this instant — which is normal between runs, but combined with a high dead_pct and an old last_autovacuum it says autovacuum is not scheduling the table often enough.

  1. Set a per-table threshold for a hot table. Autovacuum triggers when dead tuples exceed autovacuum_vacuum_threshold + autovacuum_vacuum_scale_factor * reltuples. The default scale factor of 0.2 means a table is not vacuumed until 20 percent of it is dead — far too loose for a large, hot table. Lower it per table.
ALTER TABLE public.sessions SET (autovacuum_vacuum_scale_factor = 0.02,
                                  autovacuum_vacuum_threshold = 1000);

There is no output; success is silent. This tells autovacuum to visit sessions once roughly 2 percent plus 1000 rows are dead, instead of 20 percent. Verify the setting landed with the next command.

Validate it works

Confirm the per-table override is stored:

SELECT relname, reloptions
FROM pg_class
WHERE relname = 'sessions';

Expected output:

 relname  |                      reloptions
----------+-------------------------------------------------------
 sessions | {autovacuum_vacuum_scale_factor=0.02,autovacuum_vacuum_threshold=1000}

Then trigger a manual vacuum and watch the dead-tuple count fall. Run VACUUM (VERBOSE) public.sessions; and re-run the step 1 query — n_dead_tup should drop toward zero and last_autovacuum or last_vacuum should update to now. Re-run pgstattuple on the table: dead_tuple_percent should be near zero. If free_percent is still high after that, plain vacuum has done all it can and the remaining bloat needs a rewrite — go to the decision diagram.

Decision tree mapping measured bloat percent and dead-tuple trend to routine autovacuum, threshold tuning, pg_repack, or VACUUM FULL

Troubleshooting

  • pgstattuple is very slow or spikes I/O. The exact function reads every page. Run it off-peak, on one table at a time, and use pgstattuple_approx for anything over a few tens of gigabytes. Never loop the exact function over every table in a database.
  • n_dead_tup reads zero but the table is clearly bloated. The cumulative statistics reset on crash recovery or a stats-file loss, and they lag. Trust pgstattuple over the estimate. A recent ANALYZE also refreshes reltuples, which sharpens the ratio.
  • Vacuum runs but dead tuples never drop. Something is holding an old snapshot: a long-running transaction, an idle-in-transaction session, an abandoned replication slot, or an old prepared transaction. Check SELECT max(age(backend_xmin)) FROM pg_stat_activity; and SELECT slot_name, active FROM pg_replication_slots;. Vacuum cannot remove a dead tuple newer than the oldest snapshot still in use anywhere on the cluster.
  • Bloat estimate query disagrees with pgstattuple. The popular pure-SQL bloat estimate (from check_postgres and pgexperts) infers bloat from column statistics and pg_class; it is fast but can be off by tens of percent on tables with variable-width columns or many nulls. Use it to screen, pgstattuple to confirm.
  • A rewrite finishes but the table bloats again within days. You reclaimed the symptom, not the cause. The write rate is outrunning the vacuum schedule — lower the per-table scale factor and, if the whole cluster lags, raise autovacuum_max_workers and autovacuum_vacuum_cost_limit so vacuum is allowed to do more work per round.

When this is the wrong approach

  • The table is append-only. Insert-only tables do not create dead tuples, so bloat diagnosis is beside the point. What they need is the visibility-map and freeze work covered by autovacuum for wraparound, not bloat measurement.
  • You already know you need to shrink a large table and can take a lock window. If you have measured high free_percent and can afford an ACCESS EXCLUSIVE lock, skip further diagnosis and rewrite. VACUUM FULL is simplest; for an online rebuild see pg_repack for online rebuilds, and for the broader playbook on very large tables see vacuum strategies for large tables.
  • The real symptom is slow queries, not disk growth. Bloat is one cause of slow scans, but stale planner statistics, missing indexes, or a bad plan are far more common. Confirm bloat is the bottleneck with EXPLAIN (ANALYZE, BUFFERS) before rewriting a table to chase it.

The authoritative references are the PostgreSQL documentation on routine vacuuming and the pgstattuple module.

If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.