PostgreSQL table bloat is disk space held by dead row versions and empty page space that a table no longer needs but has not given back. You find it by comparing dead tuples and free space against table size (pg_stat_user_tables, the pgstattuple extension, or a statistics-based estimate), and you fix it in two parts: stop it growing by tuning autovacuum and removing whatever blocks cleanup, then shrink what already exists with pg_repack, pg_squeeze, or on PostgreSQL 19 the new REPACK (CONCURRENTLY) command.

This guide covers why bloat happens, how to measure it accurately, how to tune autovacuum (including the settings added in PostgreSQL 18 and 19), and how to choose between VACUUM, VACUUM FULL, REPACK, pg_repack, pg_squeeze and REINDEX CONCURRENTLY. All SQL was run on a throwaway PostgreSQL 18.6 cluster on an Apple Silicon laptop. As of November 2026 the current releases are PostgreSQL 19.0 (released 2026-11-19) and 18.7; PostgreSQL 14 reached end of life on 2026-11-12.

Why PostgreSQL Table Bloat Happens: MVCC in One Paragraph

PostgreSQL never updates a row in place. An UPDATE writes a new row version (tuple) and marks the old one as expired; a DELETE only marks. The old versions must stay until no running transaction could still need to see them. VACUUM later marks that space as reusable for future inserts and updates on the same table. Three consequences follow:

  1. Ordinary VACUUM rarely shrinks the file. It makes space reusable inside the table. It only returns pages to the operating system when they are at the very end of the file.
  2. Anything that keeps an old snapshot alive blocks cleanup for every table in the database: a long transaction, an abandoned replication slot, a forgotten prepared transaction.
  3. Bloat is a rate problem. A table bloats when dead tuples are produced faster than autovacuum removes them, or when cleanup is blocked.

Here is what that looks like in practice. In our test, a 200,000-row table with autovacuum disabled was 47 MB. Two full-table UPDATEs later it was 145 MB. A plain VACUUM removed every dead tuple, and the table was still 145 MB, now two-thirds empty space. VACUUM FULL brought it back to 49 MB.

How to Measure PostgreSQL Table Bloat

Start with pg_stat_user_tables

The cumulative statistics views are free to query and tell you where dead tuples are piling up and when autovacuum last ran:

SELECT schemaname, relname, n_live_tup, n_dead_tup,
       round(100.0 * n_dead_tup / NULLIF(n_live_tup + n_dead_tup, 0), 1) AS dead_pct,
       last_autovacuum, last_vacuum, autovacuum_count
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC
LIMIT 20;

Read n_dead_tup as a signal rather than a measurement. In our test it reported 400,000 dead tuples after two updates, while a physical scan with pgstattuple counted 200,000, because page-level pruning during the second update had already cleaned up part of the first. What matters is the trend and whether last_autovacuum is recent on your busiest tables.

PostgreSQL 18 added total_vacuum_time, total_autovacuum_time, total_analyze_time and total_autoanalyze_time to these views (PostgreSQL 18 release notes), which makes it easy to spot tables where autovacuum is running constantly and still losing.

Measure Exactly with pgstattuple

The pgstattuple contrib extension reads the table and reports exact live, dead and free space. It requires superuser or membership in pg_stat_scan_tables:

CREATE EXTENSION IF NOT EXISTS pgstattuple;

SELECT table_len, tuple_count, dead_tuple_count,
       round(dead_tuple_percent::numeric, 1) AS dead_pct,
       round(free_percent::numeric, 1)       AS free_pct
FROM pgstattuple('orders');

Our bloated test table reported dead_pct 32.1 and free_pct 32.9 before vacuum; after VACUUM it showed 0 dead tuples and free_pct 66.5. That second number is the one that answers "how much would a rewrite save?"

pgstattuple does a full scan, which is expensive on a 500 GB table. pgstattuple_approx skips pages the visibility map marks all-visible and estimates their free space from the free space map, so it is far cheaper on mostly-static tables. Dead tuple counts remain exact; live tuples and free space are estimates:

SELECT table_len, round(scanned_percent::numeric, 1) AS scanned_pct,
       dead_tuple_count, round(approx_free_percent::numeric, 1) AS approx_free_pct
FROM pgstattuple_approx('orders'::regclass);

Estimate Without Scanning: the ioguix Queries

When you need a quick fleet-wide picture, the widely used estimation queries in the pgsql-bloat-estimation repository compute expected size from pg_stats column widths and compare it with actual size, for tables (table/) and B-tree indexes (btree/). They are fast and need no extension, but they are estimates. The README is candid about the limits: TOAST and compressed values are not accounted for (which can even produce negative bloat), alignment padding is counted as bloat and can reach around 10% of table size, small tables show high percentages because partly filled 8 kB pages are normal, and rows flagged is_na should not be trusted. Use them to find candidates, then confirm with pgstattuple before you schedule a rewrite.

Index Bloat

Indexes bloat independently of their tables. pgstatindex shows B-tree health:

SELECT tree_level, index_size,
       round(avg_leaf_density::numeric, 1)   AS leaf_density,
       round(leaf_fragmentation::numeric, 1) AS fragmentation
FROM pgstatindex('orders_pkey');

A freshly built B-tree typically sits near its fillfactor (90% for B-trees by default). After our update test the primary key had grown from 4.3 MB to 8.6 MB with avg_leaf_density of 45.1. That is an index worth rebuilding.

Find What Is Blocking Cleanup

Before tuning anything, check for the three things that stop VACUUM from removing dead tuples anywhere in the cluster. The tell-tale sign is in VACUUM (VERBOSE) output. With a REPEATABLE READ transaction open in another session, our test showed:

tuples: 0 removed, 250000 remain, 50000 are dead but not yet removable

Once that transaction committed, the next vacuum removed all 50,000.

Long-Running and Idle-in-Transaction Sessions

SELECT pid, usename, state, backend_xmin, age(backend_xmin) AS xmin_age,
       now() - xact_start AS xact_duration, left(query, 60) AS query
FROM pg_stat_activity
WHERE backend_xmin IS NOT NULL
ORDER BY age(backend_xmin) DESC
LIMIT 10;

The usual suspects are idle in transaction sessions from an application that forgot to commit, analytics queries running for hours, and pg_dump against the primary. Set idle_in_transaction_session_timeout for application roles, and run long reports on a replica (being aware that hot_standby_feedback = on pushes the replica's snapshot back to the primary).

Replication Slots

An inactive slot holds back xmin or catalog_xmin forever, and also retains WAL:

SELECT slot_name, slot_type, active, xmin, catalog_xmin,
       age(xmin) AS xmin_age, age(catalog_xmin) AS catalog_xmin_age
FROM pg_replication_slots
ORDER BY greatest(age(xmin), age(catalog_xmin)) DESC NULLS LAST;

Drop slots for consumers that no longer exist with pg_drop_replication_slot('name'). On PostgreSQL 18 and later you can let the server do it: idle_replication_slot_timeout invalidates inactive slots automatically (the default of 0 disables it).

Forgotten Prepared Transactions

SELECT gid, prepared, owner, database, age(transaction) AS xid_age
FROM pg_prepared_xacts
ORDER BY prepared;

If a two-phase-commit coordinator died, its prepared transactions stay until someone runs COMMIT PREPARED or ROLLBACK PREPARED. They survive restarts.

Tune Autovacuum So Bloat Stops Growing

How the Trigger Works

Per the autovacuum configuration docs, autovacuum vacuums a table when its dead tuples exceed autovacuum_vacuum_threshold + autovacuum_vacuum_scale_factor * reltuples. The defaults are 50 tuples and 0.2, so a 100-million-row table waits for 20 million dead rows. That is why large tables bloat first.

PostgreSQL 18 added autovacuum_vacuum_max_threshold, a cap on that calculated value, defaulting to 100,000,000 tuples (-1 disables the cap). It helps very large tables, but on most systems you still want per-table settings for hot tables.

Insert-only tables get their own trigger: autovacuum_vacuum_insert_threshold (default 1000) plus autovacuum_vacuum_insert_scale_factor (default 0.2) times, in the current docs, the table's unfrozen pages. That keeps the visibility map fresh for index-only scans and spreads out freezing work.

Per-Table Settings for Hot Tables

Global changes affect every table. Start with the handful of tables that churn:

ALTER TABLE orders SET (
  autovacuum_vacuum_scale_factor        = 0.02,
  autovacuum_vacuum_threshold           = 1000,
  autovacuum_vacuum_insert_scale_factor = 0.05,
  autovacuum_vacuum_cost_limit          = 1000
);

To see how far each table is from its trigger with default settings:

SELECT s.relname, s.n_dead_tup,
       current_setting('autovacuum_vacuum_threshold')::int
       + current_setting('autovacuum_vacuum_scale_factor')::float8 * c.reltuples AS trigger_at
FROM pg_stat_user_tables s
JOIN pg_class c ON c.oid = s.relid
ORDER BY s.n_dead_tup DESC
LIMIT 10;

Give Autovacuum Enough Throughput

Autovacuum is throttled by cost-based delay. vacuum_cost_limit defaults to 200 and autovacuum_vacuum_cost_delay to 2 ms, and autovacuum_vacuum_cost_limit (default -1, meaning use vacuum_cost_limit) is shared across all running workers. On modern SSDs, raising the limit to somewhere between 1000 and 2000 is common; measure I/O before and after. If you edit postgresql.conf on several servers, diffing the files in a code difference checker before reloading catches unintended changes.

Worker count matters for databases with many busy tables. autovacuum_max_workers defaults to 3. Since PostgreSQL 18, autovacuum_worker_slots (default typically 16, set at server start) reserves capacity, and autovacuum_max_workers can then be raised at runtime up to that number without a restart. More workers share the same cost limit, so raise both together.

What PostgreSQL 19 Adds

The PostgreSQL 19 release notes bring three autovacuum changes worth knowing:

  • Parallel index vacuuming in autovacuum, controlled by autovacuum_max_parallel_workers (default 0, so off) and the per-table storage parameter autovacuum_parallel_workers.
  • Prioritization scoring. Autovacuum now orders tables by a score, tunable with autovacuum_vacuum_score_weight, autovacuum_vacuum_insert_score_weight, autovacuum_analyze_score_weight, autovacuum_freeze_score_weight and autovacuum_multixact_freeze_score_weight (all default 1.0). A new view, pg_stat_autovacuum_scores, shows per-table details.
  • Shared cost limit for parallel vacuum. Parallel VACUUM workers now share the leader's cost-based delay budget, so a manual parallel VACUUM with cost delay enabled may run slower than on 18.

For a broader tour of the release, see our PostgreSQL 19 new features overview.

Reduce Bloat at the Source with Fillfactor and HOT

Heap-only tuple (HOT) updates put the new row version on the same page and skip index updates, which avoids index bloat entirely. They need free space on the page and no change to indexed columns. Our default-fillfactor test table recorded just 13 HOT updates out of 400,000 because every page was full. A table created WITH (fillfactor = 80) recorded 20,000 HOT updates out of 20,000, and its size did not change.

ALTER TABLE orders SET (fillfactor = 85);
-- applies to newly written pages; rewrite the table to apply it everywhere
SELECT relname, n_tup_upd, n_tup_hot_upd FROM pg_stat_user_tables WHERE relname = 'orders';

Lower fillfactor costs space up front, so use it on update-heavy tables only. Avoid indexing columns that change on every update, such as updated_at, unless you query by them.

Fix Existing Bloat: VACUUM vs VACUUM FULL vs REPACK vs pg_repack vs pg_squeeze

Method Returns space to OS Lock held Extra disk needed Availability
VACUUM Only trailing empty pages SHARE UPDATE EXCLUSIVE (reads and writes continue) None Core
VACUUM FULL / CLUSTER Yes ACCESS EXCLUSIVE for the whole run Table + indexes Core; kept for compatibility on 19
REPACK Yes ACCESS EXCLUSIVE for the whole run Table + indexes PostgreSQL 19
REPACK (CONCURRENTLY) Yes Brief ACCESS EXCLUSIVE at the swap Table + indexes PostgreSQL 19
pg_repack Yes Brief exclusive locks at start and end Table + indexes Extension, 1.5.3 on PGXN
pg_squeeze Yes Brief exclusive lock at the end Table + indexes Extension, needs shared_preload_libraries
REINDEX INDEX CONCURRENTLY Index space only Does not block writes Index Core since 12

REPACK on PostgreSQL 19

REPACK unifies VACUUM FULL and CLUSTER (both remain as compatibility commands). With CONCURRENTLY, most of the work runs under SHARE UPDATE EXCLUSIVE; concurrent changes are captured with logical decoding and replayed, and the exclusive lock is taken only to swap files:

REPACK (CONCURRENTLY, VERBOSE) orders;
REPACK (CONCURRENTLY) orders USING INDEX orders_created_at_idx;  -- also cluster

Read the restrictions before relying on it. The table needs a primary key or index-based replica identity; unlogged, partitioned, system and TOAST tables are not supported; it cannot run inside a transaction block; DDL on the table during the run can make it fail; max_repack_replication_slots must allow another slot; and it fails if more than about 104 million rows change concurrently. The docs also warn it is not MVCC-safe: a transaction whose snapshot predates the repack will see the table as empty afterwards. Progress appears in pg_stat_progress_repack. We could not execute REPACK because the local test cluster was PostgreSQL 18.

pg_repack and pg_squeeze for PostgreSQL 18 and Earlier

pg_repack rebuilds a table online using triggers and a log table, and is the long-standing option on managed services that allow it. It is run from the command line:

pg_repack --dbname=app --table=public.orders --jobs=2
pg_repack --dbname=app --index=public.orders_pkey   # one index only

pg_squeeze does the same job entirely server-side with logical decoding instead of triggers. Its README requires adding it to shared_preload_libraries, one spare replication slot, and wal_level = logical on servers older than PostgreSQL 19, plus an identity index on the table. Then:

SELECT squeeze.squeeze_table('public', 'orders');

Both need free disk at least equal to the table plus its indexes, and both hold a brief exclusive lock, so run them when lock queues are short and set lock_timeout in surrounding scripts.

Rebuild Bloated Indexes Online

If the table is fine but indexes are bloated, rebuild just the index:

REINDEX INDEX CONCURRENTLY orders_pkey;

It builds a new index alongside the old one and swaps them without blocking writes. If it fails partway, it leaves an invalid index named with a _ccnew suffix that you should drop. In our test, the VACUUM FULL had already rebuilt orders_pkey back to 4.3 MB, since rewriting a table rebuilds all its indexes.

When Plain VACUUM Is Enough

If pgstattuple shows high free_percent but the table will fill back up soon (a queue table, a rolling window), do nothing drastic. Reused free space is not a problem; it is the steady state. Rewrite only when free space stays high, scans are measurably slower, or you need the disk back.

A Practical Bloat Runbook

  1. Query pg_stat_user_tables for tables with high n_dead_tup and stale last_autovacuum.
  2. Check pg_stat_activity, pg_replication_slots and pg_prepared_xacts for anything holding back xmin. Fix that first, or nothing else will stick.
  3. Confirm the size of the problem with pgstattuple_approx (or pgstattuple on smaller tables), and pgstatindex for indexes.
  4. Tune per-table autovacuum settings and cost limits for the tables that churn; consider fillfactor for update-heavy tables.
  5. Reclaim space once: REPACK (CONCURRENTLY) on 19, pg_repack or pg_squeeze on earlier versions, REINDEX CONCURRENTLY for indexes.
  6. Re-measure a week later to confirm autovacuum is keeping up.

Schema changes that add indexes or columns to hot tables affect HOT eligibility, so review them like any migration; our comparison of Atlas, Flyway and Liquibase covers tools that make those changes reviewable. If you also run MySQL, its InnoDB purge works differently, and our MySQL 8.0 to 8.4 LTS upgrade guide covers that side. On managed Postgres such as Neon or Supabase, check which extensions (pgstattuple, pg_repack, pg_squeeze) are allowed before planning a rewrite.

Frequently Asked Questions

Does VACUUM reduce table size in PostgreSQL?

Usually not. VACUUM marks dead tuple space as reusable within the table and only truncates empty pages at the end of the file. To shrink the file you need a rewrite: VACUUM FULL, REPACK on PostgreSQL 19, pg_repack or pg_squeeze.

How do I check PostgreSQL table bloat without an extension?

Use pg_stat_user_tables (n_dead_tup, last_autovacuum) for a signal, and the statistics-based queries from the pgsql-bloat-estimation project for size estimates. Both are approximations; pgstattuple gives exact numbers when you can install it.

Is VACUUM FULL safe to run in production?

It is correct but blocks all reads and writes on the table for the whole rewrite, because it takes an ACCESS EXCLUSIVE lock. On large, busy tables use REPACK (CONCURRENTLY) on PostgreSQL 19, or pg_repack/pg_squeeze on earlier versions.

Why is autovacuum running but bloat keeps growing?

Either cleanup is blocked by a long transaction, an inactive replication slot or a prepared transaction (look for "dead but not yet removable" in VACUUM VERBOSE), or autovacuum is too throttled or triggers too late for that table. Fix blockers first, then lower the table's scale factor and raise its cost limit.

What is a healthy amount of free space in a table?

There is no universal number. Update-heavy tables with a lower fillfactor intentionally keep free space for HOT updates. Investigate when free space stays high over time, keeps growing, or correlates with slower sequential scans.

Conclusion

PostgreSQL table bloat is a symptom: dead tuples created faster than they are removed, or cleanup blocked by something holding an old snapshot. Measure it with pg_stat_user_tables and pgstattuple, clear blockers such as idle transactions and abandoned replication slots, tune autovacuum per table using the newer PostgreSQL 18 and 19 controls, and only then rewrite what is left, preferably online with REPACK (CONCURRENTLY), pg_repack or pg_squeeze.