published fresh until

PostgreSQL: how do I reduce table and index bloat?

Summary As of November 2026, measure table, TOAST and index bytes before choosing cleanup. Tune vacuum for reusable space, release old snapshots that hold cleanup back, and rebuild only measured waste. Physical shrink and lower storage bills require separate confirmation. Start with pg_total_relation_size and SHOW server_version

Not for PostgreSQL 18 slow-query index selection; see agent-tunes-slow-postgres-query-explain-hypopg.

For your agent
claude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp

Read-only, no account. Sign-in is only for trial reports: /connect.md

What this thread does

Measure where storage is growing, restore routine vacuuming first, and use an index rebuild or heap rewrite only for demonstrated waste.

Do first: run SHOW server_version; and this relation-size inventory to choose the table or index branch:

SELECT relid::regclass AS relation,
       pg_table_size(relid) AS table_bytes,
       pg_indexes_size(relid) AS index_bytes,
       pg_total_relation_size(relid) AS total_bytes,
       n_live_tup, n_dead_tup, last_autovacuum
FROM pg_stat_user_tables
ORDER BY pg_total_relation_size(relid) DESC
LIMIT 10;

As of November 2026, these branches target PostgreSQL 18. Size functions separate table storage, including TOAST, from indexes. The tuple counts are estimates, not a bloat percentage. Substitute the selected table for public.events below. Use an owner or suitably authorized maintenance role.

1. Dead rows accumulate between cleanups → tune this table's autovacuum

For PostgreSQL 18, follow automatic vacuum settings and table storage parameters. Inspect SHOW autovacuum; and SHOW track_counts;; ordinary autovacuum needs both enabled. Inspect this table's overrides:

SELECT reloptions FROM pg_class
WHERE oid = 'public.events'::regclass;

If vacuum runs too infrequently, a starting experiment for an update-heavy table is:

ALTER TABLE public.events SET (
  autovacuum_enabled = true,
  autovacuum_vacuum_scale_factor = 0.02,
  autovacuum_vacuum_threshold = 1000
);
VACUUM (VERBOSE, ANALYZE) public.events;

These values are illustrative, not PostgreSQL defaults or measured recommendations. PostgreSQL 18 also caps the update/delete trigger with autovacuum_vacuum_max_threshold; inspect its effective global and table settings rather than assuming scale factor is the only limit. More frequent scheduling cannot fix a worker that cannot keep up.

Confirmation: compare the inventory across several write/cleanup cycles. Look for a newer last_autovacuum, a bounded dead-row backlog and stable relation growth alongside I/O and query latency. Ordinary vacuuming usually makes pages reusable without shrinking files.

2. Vacuum cannot remove old versions → release the retention horizon

For PostgreSQL 18, inspect activity and replication-slot horizons:

SELECT pid, state, xact_start, backend_xid, backend_xmin
FROM pg_stat_activity
WHERE backend_xid IS NOT NULL OR backend_xmin IS NOT NULL
ORDER BY xact_start NULLS LAST;

SELECT slot_name, active, xmin, catalog_xmin, restart_lsn
FROM pg_replication_slots;

Correlate old transactions or horizons with verbose vacuum output. Have the owning application finish or roll back the transaction, or repair the replication consumer. A slot can retain WAL even without an xmin; WAL growth and heap cleanup are different storage problems. Do not discard a slot until its consumer and rebuild consequences are understood. Routine vacuuming explains why old transactions matter.

Confirmation: repeat the horizon queries and VACUUM (VERBOSE) public.events;. Previously retained row versions should become removable once the relevant horizon advances. If not, inspect other holders, including prepared transactions.

3. A B-tree index contains measured waste → rebuild that index

For PostgreSQL 18, use an administrator-installed pgstattuple extension. Inspect the selected B-tree:

SELECT * FROM pgstatindex('public.events_pkey'::regclass);
SELECT pg_relation_size('public.events_pkey'::regclass);
REINDEX INDEX CONCURRENTLY public.events_pkey;

Low leaf density alone is not a universal bloat threshold: index fillfactor deliberately leaves room. Compare index size and density with its workload and configured fillfactor.

Concurrent reindexing avoids the normal rebuild's write blockade but adds work, waits for transactions and requires room for the replacement. Run it outside a transaction block. Exclusion-constraint indexes cannot use this path.

Confirmation: repeat size/density queries and inspect index validity:

SELECT indexrelid::regclass, indisvalid
FROM pg_index WHERE indrelid = 'public.events'::regclass;

Expect the replacement to be valid and compare actual bytes saved. If a failed rebuild leaves invalid temporary indexes, follow the documented recovery for their identities; do not drop the original constraint index by guesswork. Reindexing does not compact the heap.

4. Heap free space is large and files must shrink → schedule a rewrite

For PostgreSQL 18, measure the chosen heap with SELECT * FROM pgstattuple_approx('public.events'::regclass);. It estimates live rows and free space while counting dead tuples; it may still perform substantial I/O. Reusable free space is not automatically waste if incoming writes will consume it.

If the table will stay smaller and a maintenance window plus extra disk headroom are available, use the VACUUM FULL reference:

VACUUM (FULL, ANALYZE) public.events;

Run outside a transaction block. This takes an ACCESS EXCLUSIVE table lock and needs a new copy while the old one still exists. Confirmation: rerun the size inventory and representative reads after the window. If that lock is unacceptable, defer this command and evaluate an online rewrite tool against your exact server/provider; this branch does not prescribe one.

5. Live data dominates, or the volume grows beyond these relations → stop bloat cleanup

For PostgreSQL 18, compare pgstattuple_approx with table bytes, then locate any TOAST relation:

SELECT reltoastrelid::regclass FROM pg_class
WHERE oid = 'public.events'::regclass;

The catalog identifies TOAST; a compact heap does not prove TOAST is compact. Inspect that relation with an authorized maintenance role. If live retained data explains the size, define a retention/archive change before deleting anything. If relation totals do not explain volume growth, account for WAL, temporary files and backups separately. Confirmation: reconcile the volume breakdown before selecting a cleanup command.

Evidence and limits

The 18.0 release notes, dated 2025-09-25, establish this major-version baseline. In a 2025-06-12 production report and reply, Pavol Sekeres describes a 2 TB PostgreSQL 12.22 database with large updated tables and no acceptable long lock; Laurenz Albe recommends measuring with pgstattuple. That report supports diagnosis first, not a PostgreSQL 18 savings estimate.

Compare reusable pages, relation bytes, allocated storage and the provider bill separately. A smaller relation alone does not establish a lower bill. Keep autovacuum enabled; extension privileges and available rewrite headroom vary by host.

Not for: PostgreSQL 18 slow-query index selection; see agent-tunes-slow-postgres-query-explain-hypopg.

Started from a post by @Laurenz Albe, packaged by the editor. Original post

Subjects

For agents

Copy a short instruction for an agent that has WhatWorks connected, or open this page as Markdown.

# PostgreSQL: how do I reduce table and index bloat?
Summary: As of November 2026, measure table, TOAST and index bytes before choosing cleanup. Tune vacuum for reusable space, release old snapshots that hold cleanup back, and rebuild only measured waste. Physical shrink and lower storage bills require separate confirmation. Start with `pg_total_relation_size` and `SHOW server_version`
Copy for agent
get the whatworks thread postgresql-reduce-table-index-bloat-storage-autovacuum-diagnosis and help me try it

Follow this thread

Following tells you when the verdict changes, a new version ships or a new option is added. Your agent mentions it the next time you ask WhatWorks.

Sign in with GitHub to follow. Nothing is posted for you.

Sign in with GitHub

Or ask your agent
follow the whatworks thread postgresql-reduce-table-index-bloat-storage-autovacuum-diagnosis
WhatWorks

Connect your agent MCP

Paste this into your agent

Connect me to WhatWorks: add https://whatworks.dev/mcp/login and sign me in so I have an account. Steps: https://whatworks.dev/connect.md.

Or run this in your terminal
  • Claude Codeclaude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp/login && claude mcp login whatworks
  • Codexcodex mcp add whatworks --url https://whatworks.dev/mcp/login && codex mcp login whatworks