As PostgreSQL applications grow, their tables continuously receive INSERT, UPDATE, and DELETE operations. Over time, these operations can leave behind dead tuples and unused space. This can increase table size, consume additional storage, and affect query performance.
For a small table, maintenance is usually straightforward. However, the situation becomes more challenging when a table contains millions of records and supports continuous application traffic. Taking the table offline for maintenance may not be acceptable because users and background services depend on it throughout the day.
PostgreSQL provides several maintenance options, including VACUUM, VACUUM FULL, CLUSTER, and concurrent index operations. Tools such as pg_repack also allow developers and database administrators to reorganize tables while normal reads and writes continue.
PostgreSQL 19 introduces a built-in REPACK command with a CONCURRENTLY option, providing another way to reclaim unused storage while reducing the time an exclusive lock is required.
This article explains why PostgreSQL tables become bloated, how online table repacking works, and how to plan a production maintenance operation without unnecessarily interrupting application traffic.
Understanding PostgreSQL Table Bloat
PostgreSQL uses a concurrency mechanism called Multi-Version Concurrency Control (MVCC). Instead of immediately overwriting an existing row whenever an UPDATE occurs, PostgreSQL creates a new row version.
The previous version becomes obsolete when no active transaction needs it. Similarly, DELETE operations mark rows as deleted rather than immediately removing their physical storage.
Consider a customer table containing one million records. If an application repeatedly updates customer addresses, PostgreSQL may create many old row versions.
UPDATE customers
SET email = '[email protected]'
WHERE id = 1001;
When the update occurs, PostgreSQL creates a new row version. The previous version becomes eligible for cleanup after transactions that might still need it have finished.
If cleanup cannot keep up with database activity, dead tuples accumulate. This can increase the physical size of the table and its indexes.
Table bloat does not necessarily mean that every unused byte can be returned to the operating system. Ordinary VACUUM makes space available for reuse inside the relation, while a full table rewrite can return unused storage to the filesystem.
Before planning a repack operation, developers should understand the difference between internal reusable space and storage that can actually be reclaimed.
Understanding PostgreSQL Table Maintenance Options
PostgreSQL provides several ways to manage table and index storage. They have different locking requirements and operational costs.
Operation | Reclaims dead tuple space | Returns space to the operating system | Locking consideration |
|---|
VACUUM | Makes dead tuple space reusable | Usually no | Allows ordinary reads and writes |
VACUUM FULL | Rewrites the table | Yes | Requires ACCESS EXCLUSIVE lock |
CLUSTER | Rewrites the table in index order | Yes | Requires ACCESS EXCLUSIVE lock |
pg_repack | Reorganizes table and indexes | Yes | Uses short exclusive-lock phases |
REPACK (CONCURRENTLY) | Rewrites the table | Yes | Uses a shorter exclusive-lock phase, with important concurrency caveats |
The correct option depends on the maintenance requirement.
For example, if the main problem is dead tuples that can be reused by future inserts, ordinary VACUUM may be sufficient. A full repack is more appropriate when the objective is to reduce the physical size of a heavily bloated table.
Why VACUUM FULL Can Be a Problem for Busy Applications
VACUUM FULL rewrites a table into a new physical file and removes unused space.
The command is straightforward:
VACUUM FULL customers;
However, it requires an ACCESS EXCLUSIVE lock on the table for the operation.
An ACCESS EXCLUSIVE lock conflicts with normal table access, including SELECT, INSERT, UPDATE, and DELETE operations. Consequently, application requests that need the table may wait until the operation completes.
For a small table, this interruption may be acceptable. For a large table used by an active application, the maintenance operation can create a significant availability problem.
Consider an API that receives hundreds of customer requests every second. If VACUUM FULL holds an exclusive lock for an extended period, requests may accumulate, connection pools may become exhausted, and application response times may increase.
This is why online table-reorganization techniques are important for production databases.
Using pg_repack for Online Table Reorganization
pg_repack is a PostgreSQL extension designed to reorganize tables and indexes while allowing normal application operations to continue during most of the maintenance process.
It does not simply execute VACUUM FULL in the background. It uses a different approach involving a temporary copy of the table and a mechanism for capturing changes made while that copy is being prepared.
A typical full-table repack follows these steps:
Create a log table to record changes made to the original table.
Add triggers to capture INSERT, UPDATE, and DELETE operations.
Create a new table and copy the existing live rows into it.
Build indexes on the new table.
Apply changes accumulated in the log table.
Acquire an exclusive lock for the final synchronization and table swap.
Replace the original table and remove the old physical objects.
The most important advantage is that the bulk of the work happens while normal application traffic continues.
<text color="secondary" size="sm">Conceptual pg_repack workflow</text>
Original PostgreSQL Table
|
v
Capture Concurrent Changes
|
v
Copy Existing Rows
|
v
Build New Indexes
|
v
Apply Captured Changes
|
v
Acquire Final Exclusive Lock
|
v
Swap Table and Index Files
|
v
Remove Old Objects
The final swap still requires an exclusive lock. Therefore, pg_repack reduces the maintenance interruption but does not guarantee that no request will ever wait.
Installing pg_repack
The extension must be installed on the PostgreSQL server using a package compatible with the server version and operating system.
After installation, enable it in the target database:
CREATE EXTENSION pg_repack;
The database user also needs the permissions required by the extension and its operational setup. The exact requirements depend on the installation and PostgreSQL environment.
Running pg_repack on a Specific Table
The following command reorganizes a particular table:
pg_repack \
--table=public.customers \
--dbname=application_db \
--username=maintenance_user
For production use, connection details should be supplied through an approved secure configuration method rather than placing passwords directly in shell history or scripts.
To preview which objects would be processed, use the dry-run option:
pg_repack \
--table=public.customers \
--dry-run \
--dbname=application_db
The dry run helps verify the selected target before starting a resource-intensive operation.
Managing Lock Wait Time
pg_repack needs exclusive locks during its initial setup and final swap.
The --wait-timeout option controls how long the tool waits to acquire the required lock.
pg_repack \
--table=public.customers \
--wait-timeout=30 \
--no-kill-backend \
--dbname=application_db
With --no-kill-backend, the tool skips the operation if it cannot acquire the required lock within the configured waiting period rather than terminating conflicting sessions.
This is particularly useful in production environments where cancelling customer queries automatically would be undesirable.
Using PostgreSQL 19 REPACK CONCURRENTLY
PostgreSQL 19 introduces a built-in REPACK command for reclaiming storage occupied by dead tuples.
A basic operation looks like this:
REPACK customers;
The default operation requires an ACCESS EXCLUSIVE lock. For a busy application, the concurrent option is more relevant.
REPACK (CONCURRENTLY) customers;
With CONCURRENTLY, PostgreSQL performs most of the table-copying and index-building work while using a SHARE UPDATE EXCLUSIVE lock. This allows ordinary SELECT, INSERT, UPDATE, and DELETE operations to continue during the main part of the operation.
PostgreSQL captures concurrent changes through logical decoding and applies them to the replacement table before the final swap.
During the final phase, PostgreSQL requests an ACCESS EXCLUSIVE lock to complete the replacement of the old table and indexes.
The duration of this final lock depends on how many concurrent changes remain to be applied and how quickly conflicting transactions allow the lock to be acquired.
Important Limitations of REPACK CONCURRENTLY
Although the concurrent option reduces locking time, it has important restrictions that must be considered before using it.
The operation requires a suitable primary key or index-based replica identity.
Partitioned tables are not supported by the concurrent option.
Unlogged tables are not supported.
The operation cannot run inside a transaction block.
The table must use the supported heap access method.
Additional replication-slot capacity may be required.
Concurrent DDL operations can cause the repack operation to fail.
An invalid index can prevent the operation from starting.
There is also an important MVCC limitation: PostgreSQL documents that REPACK CONCURRENTLY is not MVCC-safe. After the repacking transaction commits, transactions using snapshots taken before the operation began may see the table as empty.
This is particularly important for applications that maintain long-running transactions or use old snapshots. Before using this feature, review the PostgreSQL version-specific documentation and test the behavior with the application's transaction patterns.
The concurrent option should not be interpreted as a guarantee that every transaction can continue without interruption.
Preparing a Busy Table Before Repacking
Running a repack command without checking the database can create avoidable problems.
A production maintenance operation should begin with an assessment of the target table.
Check Table Size
Use the following query to understand the current table and index sizes:
SELECT
schemaname,
relname,
pg_size_pretty(
pg_total_relation_size(
schemaname || '.' || relname
)
) AS total_size,
pg_size_pretty(
pg_relation_size(
schemaname || '.' || relname
)
) AS table_size,
pg_size_pretty(
pg_indexes_size(
schemaname || '.' || relname
)
) AS index_size
FROM pg_stat_user_tables
WHERE relname = 'customers';
This provides a starting point for understanding the amount of storage associated with the table.
Check Dead Tuple Estimates
PostgreSQL exposes useful statistics through 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 = 'customers';
The n_dead_tup value is an estimate, not an exact count of every physically reclaimable tuple. It should be considered alongside table size, update frequency, vacuum activity, and application workload.
Check Long-Running Transactions
Long-running transactions can prevent PostgreSQL from cleaning up old row versions.
SELECT
pid,
usename,
state,
now() - xact_start AS transaction_duration,
wait_event_type,
wait_event,
query
FROM pg_stat_activity
WHERE xact_start IS NOT NULL
ORDER BY xact_start;
A transaction that remains open for a long time can retain an old snapshot and delay cleanup. Investigate such transactions before beginning a large maintenance operation.
Planning Disk Space and Resource Usage
Online repacking requires additional storage because PostgreSQL or the repacking tool must create replacement table and index files while the original objects still exist.
For example, a table may occupy 100 GB and its indexes may occupy another 40 GB. A repack operation needs sufficient temporary capacity for the replacement objects, in addition to the storage already consumed by the original objects.
The exact requirement depends on the table structure, index definitions, temporary sorting requirements, and concurrent changes.
Before starting the operation, check:
Available disk space on the database volume.
Available space in relevant tablespaces.
Expected temporary storage requirements.
Database I/O capacity.
Replication lag on downstream standbys.
Available memory for maintenance operations.
Current application write volume.
A repack that begins successfully can still fail if the disk fills during the operation. Storage monitoring is therefore essential.
For PostgreSQL's built-in REPACK, maintenance_work_mem can also influence the resources available for index-building work. Set it according to the available memory and the database's overall workload rather than increasing it without limits.
Monitoring a Repack Operation
A long-running maintenance operation should be monitored throughout its execution.
PostgreSQL provides the pg_stat_progress_repack view for monitoring built-in REPACK operations.
SELECT
pid,
relid::regclass AS table_name,
command,
phase,
lockers_total,
lockers_done,
current_locker_pid
FROM pg_stat_progress_repack;
The view provides information about the current operation and its progress.
For lock monitoring, use pg_locks together with pg_stat_activity.
SELECT
activity.pid,
activity.usename,
activity.state,
activity.wait_event_type,
activity.wait_event,
locks.mode,
locks.granted,
activity.query
FROM pg_locks AS locks
JOIN pg_stat_activity AS activity
ON activity.pid = locks.pid
WHERE activity.datname = current_database()
ORDER BY locks.granted, activity.pid;
For pg_repack, monitor the command output, the log table, disk consumption, and database activity. Do not assume that its progress can be monitored through the built-in pg_stat_progress_repack view, which is specifically associated with PostgreSQL's native REPACK command.
Also monitor application-level indicators such as API latency, request timeouts, connection-pool usage, and database CPU and I/O.
Common Production Mistakes
One common mistake is running VACUUM FULL on a heavily used table without understanding its locking requirements. The operation may block application traffic for longer than expected.
Another mistake is assuming that an online repack requires no additional disk space. Both native concurrent repacking and pg_repack need room for replacement data and indexes.
Developers should also avoid running multiple large repack operations simultaneously without understanding their combined resource consumption. Several operations competing for disk I/O, CPU, memory, and storage can slow down the entire database.
Long-running transactions should not be ignored. They can interfere with cleanup and increase the amount of work required by the maintenance operation.
Finally, do not schedule DDL changes against a table while it is being repacked. Schema changes can conflict with the maintenance process and cause it to fail.
Choosing Between pg_repack and PostgreSQL 19 REPACK
Both approaches can help reorganize a busy table, but they have different operational characteristics.
Consideration | pg_repack | PostgreSQL 19 REPACK |
|---|
Installation | Requires an extension and compatible client tool | Built into PostgreSQL 19 |
Concurrent processing | Yes | Yes, with CONCURRENTLY |
Change capture | Uses triggers and a log table | Uses logical decoding |
Final table swap | Requires a short exclusive-lock phase | Requires a final exclusive-lock phase |
Partitioned tables | Supports applicable partition workflows | Concurrent mode does not support partitioned tables |
Monitoring | Tool output and extension-related monitoring | pg_stat_progress_repack |
Operational considerations | Extension compatibility and permissions | Native command restrictions and MVCC limitations |
The choice should be based on the PostgreSQL version, table characteristics, operational requirements, and compatibility constraints.
Neither option should be considered a replacement for regular VACUUM and autovacuum maintenance. Repacking is a more expensive physical reorganization operation and should be used when there is a clear reason to reclaim storage or reorganize data.
Summary
Repacking a busy PostgreSQL table does not have to require a long application outage. Tools such as pg_repack and PostgreSQL 19's built-in REPACK CONCURRENTLY allow most of the maintenance work to happen while normal database operations continue.
The key is understanding how the replacement table is created, how concurrent changes are captured, and why a short exclusive-lock phase is still required during the final swap.
Before starting a production operation, examine table size, dead tuple estimates, long-running transactions, available disk space, and current database workload. Monitor the maintenance process and application performance throughout the operation.
Most importantly, choose the maintenance method according to the application's consistency requirements and table characteristics. Online repacking can reduce operational disruption, but it does not eliminate every locking, storage, or concurrency consideration. A carefully planned maintenance process is still essential for keeping a busy PostgreSQL database reliable.
Join the conversation! Your thoughts help the community grow.