PostgreSQL dead tuples: verify autovacuum and reusable space

PostgreSQL dead tuples: verify autovacuum and reusable space

PostgreSQL dead tuples: verify autovacuum and reusable space

With ongoing database updates, table files can keep growing even when the number of business records barely changes. Expanding the disk or immediately running VACUUM FULL can turn a version-cleanup issue into a capacity and lock-wait problem. Start by answering three questions: are the old row versions eligible for removal, is automatic vacuuming running, and do subsequent writes reuse the space it frees?

This article covers PostgreSQL on Linux and uses an isolated test table for verification, without modifying application tables. Direct-attached NVMe on AmdByte dedicated servers describes only the storage connection; it does not change the database’s multiversion concurrency control mechanism.

Distinguish dead tuples from file growth

An UPDATE usually creates a new row version. The old version becomes eligible for removal only when no relevant snapshot needs it anymore. A DELETE does not immediately erase disk contents either. Ordinary VACUUM removes eligible versions so their space can be allocated again. ANALYZE updates optimizer statistics; it does not replace vacuuming.

n_dead_tup is an estimate, not an exact measurement of holes in a file. Indexes, TOAST data, and statistics that have not yet been updated also affect how you interpret a table’s size. A single tuple count or file-size reading cannot prove that vacuuming has failed.

The primary purpose of ordinary VACUUM is to make space reusable, not to guarantee a noticeably smaller file. Under suitable conditions, it may truncate empty pages at the end of a table, but that should not be a required success criterion for every vacuum.

First, confirm the current database and user in psql, and save the query results. The account used for subsequent diagnostics needs the appropriate permissions to view statistics. Do not broaden the application account’s permissions merely to make troubleshooting easier.

SELECT current_database(), current_user, version();

SELECT schemaname, relname, n_live_tup, n_dead_tup,
       last_autovacuum, autovacuum_count,
       pg_size_pretty(pg_total_relation_size(relid)) AS total_size
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC
LIMIT 10;

Check what is preventing cleanup

Take repeated samples for the suspected table, recording the sample time, update volume, and vacuum count. Do not reset statistics across the database to create a “clean starting point.” Doing so destroys historical evidence that other investigations may need.

Find old snapshots

A long-running transaction can retain an old snapshot even when it is not currently executing a query. Focus on transaction age, state, and backend_xmin, rather than simply sorting by query runtime.

SELECT pid, usename, state,
       clock_timestamp() - xact_start AS xact_age,
       backend_xmin, wait_event_type, wait_event
FROM pg_stat_activity
WHERE xact_start IS NOT NULL
  AND pid <> pg_backend_pid()
ORDER BY xact_start;

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

When you find an old transaction, first identify the application and business operation it belongs to, then have the application commit or roll it back. A replication slot’s xmin and catalog_xmin can also hold back the cleanup horizon. Do not simply drop slots to free space, as this may break downstream replication. WAL retained by a slot’s restart_lsn is a separate capacity issue and should be assessed separately.

Check pg_stat_progress_vacuum to see whether a vacuum task is currently running. No rows means only that no running task is visible at the time of the query; it does not prove that autovacuum has never run. If a progress entry remains unchanged for a long time, investigate further using wait events and blocking relationships.

Create an isolated test table

First, confirm that the test database has enough free space and that no schema with the same name exists. If it does, choose another name rather than overwriting existing objects. Run the following commands with a test account that has permission to create tables. Keep autocommit enabled in psql, and do not wrap the entire script in BEGIN.

CREATE SCHEMA vacuum_lab;

CREATE TABLE vacuum_lab.churn (
    id bigint PRIMARY KEY,
    payload text NOT NULL
);

ALTER TABLE vacuum_lab.churn SET (
    autovacuum_vacuum_threshold = 50,
    autovacuum_vacuum_scale_factor = 0
);

INSERT INTO vacuum_lab.churn
SELECT g, repeat('a', 128)
FROM generate_series(1, 20000) AS g;

VACUUM (ANALYZE) vacuum_lab.churn;

SELECT pg_total_relation_size('vacuum_lab.churn') AS baseline_bytes;

UPDATE vacuum_lab.churn
SET payload = repeat('b', 128)
WHERE id <= 10000;

The row counts and thresholds here are chosen for the experiment, not recommended as production settings. Vacuuming after the initial insert establishes a clearer baseline. Updating half the data afterward gives autovacuum an opportunity to meet its trigger conditions.

Do not disable autovacuum globally or copy this low threshold to large production tables. For large tables, vacuum frequency must also be evaluated against the update rate, worker resources, and storage load. Running more frequently does not guarantee that the problem will disappear.

Verify autovacuum and space reuse

First, confirm that the global autovacuum and track_counts settings are enabled and that the test table’s options have been saved. Even after the table-level trigger condition is met, the task must still be scheduled. Busy workers, tasks in other databases, and retained snapshots all affect execution, so there is no fixed completion deadline.

SHOW autovacuum;
SHOW track_counts;

SELECT reloptions
FROM pg_class
WHERE oid = 'vacuum_lab.churn'::regclass;

SELECT pg_stat_clear_snapshot();

SELECT n_live_tup, n_dead_tup,
       last_autovacuum, autovacuum_count
FROM pg_stat_user_tables
WHERE relid = 'vacuum_lab.churn'::regclass;

Run the last two queries at intervals. Watch for an increase in autovacuum_count, an updated timestamp, and a drop in the estimated dead-tuple count. Statistics reporting is not synchronous. pg_stat_clear_snapshot() only clears the current session’s cached snapshot; it does not force background processes to report statistics immediately.

If you still do not observe autovacuum, preserve the diagnostic evidence before running the manual check below. This verifies only the manual vacuum path and cannot substitute for verifying autovacuum.

VACUUM (VERBOSE, ANALYZE) vacuum_lab.churn;

Once vacuuming is confirmed complete, insert another batch of rows of the same width and compare the total size before and after the insert:

SELECT pg_total_relation_size('vacuum_lab.churn') AS before_insert;

INSERT INTO vacuum_lab.churn
SELECT g, repeat('c', 128)
FROM generate_series(20001, 25000) AS g;

SELECT pg_total_relation_size('vacuum_lab.churn') AS after_insert;

The file may still grow after new rows are added because index page splits, the distribution of free space, and page overhead all affect allocation. Judge the growth trend across multiple rounds of the same workload rather than requiring the byte count to remain exactly unchanged. Nor should this small table be used to estimate production throughput.

Define the boundaries for production changes

If ordinary vacuuming works but the file does not shrink, an immediate rewrite is usually unnecessary. If the business genuinely needs to return space to the filesystem, assess VACUUM FULL separately: it rewrites the table, requires additional disk space, and acquires an ACCESS EXCLUSIVE lock. Attempting a rewrite without proper assessment when the disk is nearly full can make recovery harder.

Change only one variable at a time in production. Address unnecessary long-running transactions first, then evaluate table-level thresholds. If autovacuum consistently falls behind writes, investigate task duration and resource contention rather than simply lowering the trigger threshold.

When finished, retain records of the following checks:

When the test data is no longer needed, verify object ownership before removing the test schema. Do not use CASCADE; let unexpected dependencies stop the cleanup.

DROP TABLE vacuum_lab.churn;
DROP SCHEMA vacuum_lab;

Record three separate conclusions: “autovacuum verified,” “space is reusable,” and “whether the file shrank.” Keeping these results separate helps prevent the next capacity alert from leading straight to another full-table rewrite.

Frequently asked questions

Why does the table file barely shrink after ordinary VACUUM?

Ordinary VACUUM primarily makes space occupied by removable tuples available for reuse; it does not guarantee a smaller file. It may truncate empty pages at the end of a table when conditions allow. Check dead tuple trends, vacuum records and subsequent writes together.

Should accumulating dead tuples trigger an immediate VACUUM FULL?

No. First inspect long transactions, xmin retained by replication slots, autovacuum thresholds and vacuum progress. VACUUM FULL rewrites the table, requires extra disk space and takes an exclusive lock, so it is not routine online cleanup.

EPYC 7543P Dedicated Server

From $457/mo

Server Specifications and Rental Pricing

Compare ECC memory options and direct-attached NVMe configurations, then choose add-ons and a billing term.