Database tables do not always become smaller when records are deleted or updated. In PostgreSQL, an UPDATE creates a new row version, while the previous version remains in the table until it is no longer needed by active transactions. Similarly, DELETE marks a row as deleted rather than immediately removing its physical storage.
Over time, frequently updated tables can accumulate unused space. This condition is commonly called table bloat. It can increase storage consumption, make maintenance operations more expensive, and affect query performance because PostgreSQL may need to scan more pages than necessary.
PostgreSQL provides VACUUM to clean up obsolete row versions and make their space available for reuse. However, standard VACUUM generally does not return most of that space to the operating system. Previously, administrators often used VACUUM FULL or CLUSTER when they needed to compact a table and reduce its physical size. These operations require an exclusive table lock during the rewrite.
PostgreSQL 19 introduces a new REPACK command that provides another way to reclaim unused table space. Its CONCURRENTLY option allows the main repacking work to happen while other sessions continue reading and writing the table. An exclusive lock is still required briefly when the replacement table and indexes are swapped into place.
This article explains how REPACK works, how to use it safely, how it differs from VACUUM, and how to monitor the operation in PostgreSQL 19.
Understanding Table Bloat in PostgreSQL
PostgreSQL uses Multiversion Concurrency Control (MVCC) to manage concurrent database operations. Instead of immediately overwriting or removing existing row versions, PostgreSQL maintains multiple versions so that transactions can see a consistent view of the data.
Consider an application that regularly updates customer records:
UPDATE customers
SET email = '[email protected]'
WHERE customer_id = 101;
PostgreSQL creates a new row version for the updated record. The previous version becomes obsolete when no active transaction needs it.
The same situation occurs when an application deletes records:
DELETE FROM customers
WHERE last_login < CURRENT_DATE - INTERVAL '2 years';
The deleted rows are not immediately removed from the physical table file. They become dead tuples that can be cleaned up by VACUUM when it is safe to do so.
If a table receives thousands or millions of updates and deletes, the amount of unused space can increase significantly.
For example, consider an order history table that initially occupies 20 GB. After several years of updates and data cleanup, the table might occupy considerably more storage even though the number of active records has decreased.
The actual size depends on row widths, indexes, update patterns, fillfactor, and other storage characteristics. A large table is not automatically a bloated table, so administrators should measure before performing a rewrite.
Understanding REPACK in PostgreSQL 19
PostgreSQL 19 introduces REPACK as a native SQL command for rewriting tables and reclaiming storage occupied by dead tuples.
Unlike standard VACUUM, REPACK creates a new physical copy of the table without the unused space left by obsolete row versions. It also rebuilds the associated indexes and replaces the old files after the operation is ready.
The basic syntax is:
REPACK table_name;
For example:
REPACK public.orders;
This command rewrites the orders table and its indexes. However, without the CONCURRENTLY option, it acquires an ACCESS EXCLUSIVE lock at the beginning and holds that lock during the operation.
For a production table receiving continuous traffic, this can cause application requests to wait.
PostgreSQL 19 provides a concurrent option:
REPACK (CONCURRENTLY) public.orders;
This changes how the operation manages locks.
The database performs most of the copying and rebuilding work while allowing normal transactions to continue using the table. Changes made during the operation are captured and applied before the final file replacement.
During the final phase, PostgreSQL needs an ACCESS EXCLUSIVE lock to swap the old table and index files with the newly created files.
The important difference is that the exclusive lock is generally held only for this final phase rather than throughout the entire rewrite.
Reclaiming Table Space Without Blocking Normal Writes
Let's walk through a practical example using an orders table.
Assume the application regularly updates order status, delivery information, and customer details. After a large data cleanup, the table contains many obsolete row versions.
The first step is to inspect its current size.
Checking Table Size
PostgreSQL provides the pg_total_relation_size function to calculate the total storage used by a table, including its indexes and associated TOAST data.
SELECT
schemaname,
relname AS table_name,
pg_size_pretty(
pg_total_relation_size(
schemaname || '.' || relname
)
) AS total_size
FROM pg_stat_user_tables
WHERE relname = 'orders';
For a more detailed comparison, inspect the table and index sizes separately:
SELECT
pg_size_pretty(
pg_relation_size('public.orders')
) AS table_size,
pg_size_pretty(
pg_indexes_size('public.orders')
) AS index_size,
pg_size_pretty(
pg_total_relation_size('public.orders')
) AS total_size;
This information helps establish a baseline before maintenance.
Checking Dead Tuple Estimates
PostgreSQL maintains statistics about live and dead tuples in pg_stat_user_tables.
SELECT
relname,
n_live_tup,
n_dead_tup,
last_vacuum,
last_autovacuum,
last_analyze,
last_autoanalyze
FROM pg_stat_user_tables
WHERE relname = 'orders';
The n_dead_tup value is an estimate, not an exact count of reclaimable bytes. It helps identify tables that may need additional investigation.
A high dead-tuple estimate does not automatically mean REPACK is necessary. Standard VACUUM may already be sufficient to make the space reusable.
If the table is significantly larger than its expected working size and unused space needs to be returned to the operating system, REPACK may be appropriate.
Running REPACK Concurrently
Once the table has been reviewed, run:
REPACK (CONCURRENTLY) public.orders;
PostgreSQL performs the following operations:
Creates a new physical copy of the table while excluding dead tuples.
Builds replacement indexes for the new table.
Captures concurrent changes made by application transactions.
Applies the captured changes to the replacement data.
Acquires an ACCESS EXCLUSIVE lock for the final replacement.
Swaps the old and new table and index files.
Removes the old files after the replacement is complete.
The main advantage is that application reads and writes can continue during most of the operation.
However, concurrent execution does not mean the operation is completely lock-free. Long-running transactions, DDL operations, and other locking activity can delay the final replacement.
Using REPACK With Additional Options
PostgreSQL 19 supports additional options that help administrators monitor and maintain tables during repacking.
Displaying Progress Information
The VERBOSE option displays informational messages while the operation runs.
REPACK (
CONCURRENTLY,
VERBOSE
) public.orders;
These messages help administrators understand which table is being processed and follow the operation's progress.
PostgreSQL also provides the pg_stat_progress_repack system view for monitoring active repacking operations.
SELECT *
FROM pg_stat_progress_repack;
This view provides progress information for currently running REPACK commands.
It is useful when maintenance is performed on large tables because administrators can inspect the operation instead of relying only on command completion.
Updating Planner Statistics
After rebuilding a table, it is important to make sure PostgreSQL has accurate statistics for query planning.
REPACK supports the ANALYZE option:
REPACK (
CONCURRENTLY,
ANALYZE,
VERBOSE
) public.orders;
This performs ANALYZE after repacking the specified table.
ANALYZE collects statistics that help the PostgreSQL query planner select appropriate execution plans.
The ANALYZE option is currently supported when a single non-partitioned table is specified. It cannot be executed inside a transaction block or from a function, procedure, or DO block.
If ANALYZE is not included, it can be executed separately:
ANALYZE public.orders;
Reordering Table Data With an Index
REPACK can also reorganize the physical order of table rows using an existing index.
This is useful when an application frequently retrieves records in a particular order or accesses related records together.
For example, consider an orders table with an index on customer_id:
CREATE INDEX idx_orders_customer_id
ON public.orders(customer_id);
The table can be repacked using that index:
REPACK public.orders
USING INDEX idx_orders_customer_id;
This operation physically rearranges rows according to the ordering represented by the index.
For workloads that frequently retrieve groups of records belonging to the same customer, this arrangement may improve data locality and reduce disk access.
However, physical ordering is not permanent. New inserts and updates are not automatically placed according to the same ordering. If the application changes the table frequently, the benefit may gradually decrease.
Use this option only when the application's access patterns justify the additional maintenance work.
Important Requirements and Limitations
Before running REPACK CONCURRENTLY on a production table, check the database requirements.
The operation requires the MAINTAIN privilege on the target table.
The table must also meet the requirements for concurrent repacking. In particular:
The target must be a regular table.
The table must have a primary key or an index-based replica identity.
The table cannot be partitioned when using CONCURRENTLY.
The table cannot be UNLOGGED.
The table cannot be a system catalog or TOAST table.
The table must use the heap access method.
The operation cannot run inside a transaction block.
The server must have capacity to create the required additional replication slot.
REPACK also refuses to process a table that has an invalid index. Such indexes must be removed or rebuilt before repacking.
One important limitation is disk capacity. REPACK creates temporary copies of the table and its indexes. Administrators should have enough free space to accommodate the existing files and the replacement files during the operation.
For a large table, insufficient disk space can cause the maintenance operation to fail.
There is also an important MVCC consideration. PostgreSQL documents that REPACK CONCURRENTLY is not MVCC-safe. Transactions using a snapshot taken before repacking started can see the table as empty after the repacking transaction commits. Applications with long-running transactions or snapshot-sensitive workloads must account for this behavior before scheduling the operation.
REPACK vs VACUUM vs VACUUM FULL
These commands solve related but different maintenance problems.
Operation | Reclaims dead tuples | Returns space to operating system | Locking behavior |
|---|
VACUUM | Yes | Usually no | Allows normal reads and writes |
VACUUM FULL | Yes | Yes | Holds ACCESS EXCLUSIVE during rewrite |
REPACK | Yes | Yes | Rewrites table; exclusive lock during operation |
REPACK CONCURRENTLY | Yes | Yes | Allows normal use during most of the operation |
Standard VACUUM should remain part of regular database maintenance. It removes obsolete row versions and makes space available for reuse without rewriting the entire table.
REPACK is useful when a table needs physical compaction and returning unused storage to the operating system is important.
It should not replace routine VACUUM or autovacuum. PostgreSQL specifically recommends VACUUM for regular cleanup and transaction ID wraparound protection.
Best Practices for Production Databases
Running a table rewrite on a production database requires planning, even when the concurrent option is used.
The following practices help reduce operational risk:
Measure table and index sizes before starting maintenance.
Check dead-tuple estimates and review whether standard VACUUM is sufficient.
Verify available disk space for temporary table and index copies.
Confirm that the table satisfies all concurrent repacking requirements.
Check for long-running transactions and DDL operations that could delay the final lock.
Schedule large maintenance operations during periods of lower database activity.
Monitor pg_stat_progress_repack and database resource usage.
Run ANALYZE after repacking when necessary.
Test the operation with representative workloads before using it on critical production tables.
Continue monitoring autovacuum because new dead tuples will accumulate as the application performs updates and deletes.
Administrators should also monitor replication behavior, transaction duration, disk I/O, and application latency during large operations. Concurrent repacking reduces blocking, but it still consumes database resources.
Summary
PostgreSQL 19 introduces REPACK as a native way to reclaim table space and reorganize table data. Its CONCURRENTLY option allows most of the rewrite to happen while application transactions continue reading and writing the table.
This provides an alternative to VACUUM FULL when physical compaction is required but a long exclusive lock is not acceptable.
However, REPACK is not a replacement for standard VACUUM or autovacuum. It requires additional disk space, has table eligibility restrictions, and still needs an exclusive lock during the final replacement. Its concurrent mode also has MVCC considerations that administrators must understand before using it with long-running transactions.
For production systems, the best approach is to use regular VACUUM for routine maintenance and reserve REPACK CONCURRENTLY for tables that genuinely need physical compaction. This helps reclaim storage while minimizing disruption to normal application activity.
Join the conversation! Your thoughts help the community grow.