When pg_repack is the right way to remove PostgreSQL bloat
A table or index has grown far beyond its live data, queries are slowing, disk use keeps climbing, and the application cannot afford a long write outage. In that situation, pg_repack rebuilds bloated tables and indexes online, copying live rows into a new physical structure while the original stays readable and writable for most of the work. It does not fix the cause of bloat, does not prevent it from returning, and does not reduce the need for a correct autovacuum configuration. Before you install anything, confirm that bloat is the real cause of the slowdown or disk growth, since a table can be large for legitimate reasons and a slow query can come from a missing index, a plan change or lock waiting.
Bloat comes from MVCC. When a row is updated or deleted, PostgreSQL keeps the old row version so concurrent transactions can still read it. Plain VACUUM later marks the space of dead versions as reusable inside the table, but it normally does not return that space to the operating system, so the file stays large. Dead tuples, free space in pages, and index entries pointing to removed rows all contribute. Measure before deciding. Compare the table's on-disk size with an estimate of its live data, check n_dead_tup and last vacuum times in pg_stat_user_tables, and look at the pgstattuple extension for an exact picture on suspect tables and indexes. Ask whether autovacuum has been running and whether a long transaction is stopping it from cleaning up at all, because repacking a table that vacuum cannot clean will simply grow again.
Running pg_repack safely in production
This sequence takes one bloated table from measurement to a verified repack, with each gate confirmed before the next step runs. The result is reclaimed space, a documented lock window and a record of size and query behavior before and after.
Confirm the extension version matches the server
The DBA or platform engineer installs the pg_repack package that matches the PostgreSQL major version running on the target server, using the packaging method the team already uses for the database. Check the installed binary version and the server major version side by side, and confirm they agree before going further. Mismatched binaries and server versions are a common cause of failed installs, so treat this as a hard gate. The step is done when both versions are recorded in the change ticket. Confirm the supported pairing with the pg_repack project documentation for your exact release.
Create the extension in the target database
A user with sufficient privileges runs CREATE EXTENSION pg_repack in the specific database that holds the bloated tables, not in the postgres maintenance database by default. The extension creates its own schema and objects, so confirm which schema it lands in and that your monitoring and backup jobs will not be surprised by it. Review who holds the privileges needed to run repacks in that database, because the tool needs to create temporary objects and take locks. The step is done when the extension appears in the pg_extension catalog for that database and the installed version matches the binary from the previous step.
Check keys and unique indexes on each table
Before any repack, list every table you plan to process and confirm each one has a primary key or a non-partial unique index on non-null columns. pg_repack uses that key to replay changes made during the rebuild, and a table without one cannot be repacked online in the normal way. For tables that lack a key, the realistic options are to add one in a separate change, to accept an offline rebuild with VACUUM FULL or CLUSTER during a maintenance window, or to leave the table alone. Record the decision for each table. The step is done when every planned table is marked as eligible or excluded with a reason.
Confirm free disk space and WAL headroom
Measure the table and its indexes with pg_total_relation_size, then confirm the filesystem holding the tablespace has room for a full second copy of the table and all its indexes, plus the WAL generated during the rebuild. Check that the replication standbys and WAL archive have capacity for that extra WAL, since a lagging standby or a full archive volume can stall the job. Confirm the space requirement with the pg_repack documentation for your version, because the rebuild needs temporary space. The step is done when the free space and WAL headroom are written down next to the table sizes and the team has agreed the margin.
Measure bloat and run a dry run on staging
Estimate bloat for the candidate table with a current statistics-based query or a dedicated bloat tool, and record table size, index size and the estimate before any change. Restore a recent copy of the database to a staging server with similar hardware and data volume, then run pg_repack against the same table there. Note the elapsed time, peak disk use, WAL volume, and any errors or waits. Estimates are approximate, so the actual size after the staging run is the number that matters. The step is done when the staging run completes cleanly and the team has compared the expected reclaimed space with the observed result.
Schedule the production lock window
pg_repack takes a short ACCESS EXCLUSIVE lock at the start and end of the rebuild to swap the tables, and it needs its own connection to the database. Set lock_timeout on the session so the repack gives up rather than queueing other traffic behind it, and check for long-running transactions that would block the lock from being granted. Agree the window with the application owners and confirm the time with the team on call. The step is done when the lock timeout, the window and the rollback contact are written into the change record and someone has confirmed no long transactions are open on that table.
Run a single-table repack in production
Run pg_repack against one table, using the table flag and the database connection settings you validated in staging. Watch pg_stat_activity and the pg_repack output for lock waits, replication lag and free disk space, and stop the job if any of these leave the agreed limits. Do not start a batch of tables until the first one has been verified. The step is done when pg_repack reports completion and the table, its indexes and the catalog show the new relation in place with no leftover temporary objects.
Verify size, indexes and query behavior
Compare the table and index sizes against the numbers recorded before the run, and confirm the reclaimed space matches the staging estimate within the margin your team accepts. Check that indexes are valid, run ANALYZE on the table, and compare the plans and timings of your most important queries against the baseline. Confirm that replicas caught up and that backups still run against the table. The step is done when the before and after figures, the query comparison and the list of any anomalies are filed with the change record, and the next table in the plan is approved or held.
Where pg_repack takes locks and where writes still wait
pg_repack rebuilds a table or index without holding the long exclusive lock that VACUUM FULL and CLUSTER need for the whole rebuild, but it is not lock-free. It takes a brief ACCESS EXCLUSIVE lock at the start of a repack, while it sets up its working objects, and another brief one at the end, when it swaps the rebuilt copy in for the original. Writes and reads that need a conflicting lock on the target table wait during those moments. The rest of the time, ordinary reads and writes continue. Before scheduling a run, confirm the exact lock behavior for your pg_repack version in its documentation, and plan for the lock moments to be short only if nothing else is holding the table.
During the rebuild, pg_repack copies the table into a new structure while ordinary INSERT, UPDATE and DELETE statements keep running against the original. It captures those concurrent changes with triggers on the source table and replays them into the new copy before the swap. This is why the process can finish without blocking writes, and it is also why write-heavy tables cost more: each captured change is logged and replayed, and the triggers add work to every affected statement. Ask the team that owns the table to estimate its write rate during the window, and check that the room for the temporary log and the new copy exists on the same tablespace.
The swap at the end needs the ACCESS EXCLUSIVE lock, and that lock cannot be granted while any transaction holds a conflicting lock on the table. A long-running query, an idle-in-transaction session, or a forgotten BEGIN can keep pg_repack waiting indefinitely. While it waits, every new query that needs a conflicting lock queues behind it, so a repack that cannot finish can stall application traffic. Set lock_timeout on the session that runs pg_repack so the swap gives up instead of queuing writes for an unknown time, and combine it with a check of pg_stat_activity for long transactions before the run starts. Decide in advance who stops the job, and what the application does when writes time out.
Requirements and limits to confirm before a repack
pg_repack rebuilds a table or index into a new copy, so its requirements are about keys, space, replication, versions, privileges and table features. Confirm each one against the pg_repack documentation for your PostgreSQL version and the pg_repack release you plan to install before you schedule any work on production tables.
Primary key or unique index
pg_repack needs a primary key or a non-partial unique index on each table it reorganizes, because it uses that key to replay changes made while the copy is built. Tables without one cannot be repacked online by this method. Check every bloated table with a query against the system catalogs before you plan the window, and decide how to handle any table that lacks a suitable key, such as adding one or using a different method for that table.
PostgreSQL upgrade docsFree disk space for the new copy
During a repack the old and new copies of the table and its indexes exist at the same time, and WAL grows as the rebuild writes changes. Estimate the size of the target table and its indexes, add headroom for WAL generation and for replayed changes, and confirm that the volume and any archive destination can absorb it. Running out of space mid-repack is one of the more disruptive ways a repack can fail.
Replication and backup impact
The rebuild generates a large volume of WAL, which standbys must receive and replay and which archiving and backup tools must store. Confirm how replication lag and archive growth will behave during the run, whether any replication slots could hold WAL longer than planned, and whether a backup should be taken just before the repack. Agree these checks with the team that owns replication and recovery.
PostgreSQL and pg_repack version match
pg_repack has to be built for the PostgreSQL major version on the server, and its extension version must match the installed package. Confirm the pg_repack release you plan to use supports your PostgreSQL version, install the matching extension in each database that needs it, and test the same version on a staging copy first. Plan for the version change when you upgrade PostgreSQL, since the extension must be rebuilt or reinstalled.
Privileges needed to run it
The role that runs pg_repack must be able to read and modify the target tables, and the extension itself is created in a schema that the role can use. Confirm which privileges the documentation requires for your version, including ownership of the table, and decide whether a dedicated maintenance role should run the job. Record which role ran each repack so the change is traceable in your audit trail.
Unsupported table features
Some table features complicate or block a repack, including certain column types, triggers, foreign keys, partitioned tables and tables that other sessions lock heavily. Read the current list of limitations in the documentation for your release, test each affected table on a copy, and decide in advance whether to skip it, change the approach or accept a longer maintenance window. Do not assume a table is compatible because a similar one worked.
What the REPACK command in PostgreSQL 19 changes
PostgreSQL 19 is expected to add a REPACK command to core, which would give the server a built-in way to rewrite tables and their indexes to reclaim bloated space. Today, teams that want to rebuild a table without the long exclusive lock that VACUUM FULL takes usually reach for the pg_repack extension, which has to be installed on the server and matched to each PostgreSQL major version. A core command would change that calculation, since it could remove an extension from the list of components to install, track, and re-test after every major upgrade. It could also change which tool a team standardizes on for scheduled maintenance. Until the behavior is confirmed, though, the extension remains the tool you can plan around for PostgreSQL versions where the command is not available.
The details that matter for planning are the ones this section cannot confirm: the final syntax, which options exist (for example, whether it supports an online mode equivalent to pg_repack's), what lock level it takes at each stage, whether it can process a single index or a whole table, and whether it is in the released PostgreSQL 19 build you will run. Check these in the PostgreSQL 19 release notes before writing a runbook, and do not assume that behavior matches pg_repack's documented lock moments. Also confirm the support window for the version you choose, using the versioning policy, since a major release only becomes a production target once its minor releases have settled.
For a team planning a bloat program now, the practical step is to keep the reclaim procedure in a version-controlled runbook with the command, its required privileges, its lock behavior and a rollback check, so the swap to a core command is a small, tested change rather than a redesign. Record which PostgreSQL major versions each cluster runs, and schedule a test of the replacement command in a non-production copy once the release notes are final. Treat any change to the tool as a change to the maintenance window and monitoring alerts, because a different lock profile can affect lock waits and application timeouts even when the space savings are the same.
Security and operational risks of rebuilding live tables
A repack rebuilds tables and indexes while the database keeps serving traffic, so it touches access, auditing, backups, replicas and change management at once. The cards below pair each risk with a control you can verify before the first run and again after each maintenance window.
Privileges required to run repack
The pg_repack extension must be installed in each database you rebuild, and the role that runs it needs enough rights to take the locks and read the catalogs involved. Because the tool rebuilds objects, it can expose data in transit through temporary tables and sort files, so the role should be a dedicated maintenance account rather than a shared superuser login. Check which roles can run the tool, confirm that each one can reach only the databases it is meant to maintain, and review grants against the version of pg_repack you have installed.
Authentication methodsAudit trail of rebuild runs
A repack changes physical storage and can hold locks that block application queries, so an incident review will ask who started it, against which tables and when. Keep a change record that names the role, the target objects, the start and end times and the outcome, and make sure your server logs capture the connection and the statements issued under that role. Confirm that log retention outlasts your review cycle and that nobody can edit these records with the same account that ran the job.
Backup consistency and restore testing
Repacking rewrites table files and changes their physical layout, which means the backups taken before and after a run describe different storage. Take a fresh base backup or confirm your archive is current before the first run, and record the WAL position so you can recover to a known point if the rebuild fails midway. After the work, restore a copy to a separate server, run row counts and checksums on the rebuilt tables, and confirm that the restored data matches the expected state.
Continuous archiving docsReplication lag and standby disk
Every change made by a repack is written to the write-ahead log and shipped to standbys, so a large rebuild can push replication lag up and fill replica disks at the same time. Synchronous standbys can slow commits while they catch up. Measure current replay lag and free space on each standby, set a limit at which you pause the job, and confirm that archived WAL has room for the extra volume. Rebuild the largest objects in the smallest batches your window allows.
High availability docsChange control for maintenance windows
Repacks can take locks briefly at the start and end, and they consume I/O and temporary disk for the whole run, so they belong in a scheduled change, not an ad hoc session. Write down the objects, the order, the expected lock moments, the abort conditions and the rollback path before the window opens. Name the person who may stop the job and the threshold that triggers a stop, such as lock waits on critical tables or replica lag beyond the limit you set.
Rollback and post-run verification
A repack that fails partway leaves the original table in place, but a dropped or renamed object, a failed index swap or a stalled job can leave the database in a state no one planned for. Before the run, record object sizes, index definitions and table statistics so you can compare them afterward. After the run, check for leftover objects created by the tool, confirm that indexes are valid, and confirm that the application queries that depend on those tables still return the expected results.
Questions teams ask before repacking bloated tables
What drives the cost of a bloat cleanup project?
The cost is driven mainly by how many tables and indexes are affected, how large they are, and how much of the environment must be prepared before any repack runs. Work splits into measuring bloat, confirming that bloat is the cause, rehearsing the repack on a copy of production, planning lock windows, and monitoring afterward. Internal staff are paid for their time across all of these, while an outside team is paid under a written scope. One-time work includes the first assessment and runbook. Recurring work appears only if bloat keeps returning and needs scheduled cleanup or a retainer. When requesting a quote, ask for the list of objects in scope, the staging approach, who performs the lock-window changes, and what evidence is delivered at the end.
How long does a repack take, and what sets its duration?
Duration depends mostly on table size, the number and size of indexes, available disk space, I/O capacity, and how much write traffic hits the table during the run. pg_repack builds a new copy of the table and its indexes, replays changes captured during the process, and then swaps the files, so large tables with heavy write activity take longer and need more free space. Index rebuilds often dominate the total time on tables with many indexes. Ask the team doing the work to run a timed test on a copy of the largest affected object, then extrapolate from that measurement rather than from general estimates. The PostgreSQL documentation for the tool is the natural next read for the exact requirements.
What does the work need from our team?
The work needs a database account with the privileges that pg_repack requires, read access to catalog statistics, and a staging environment with a recent copy of production data of similar size. It also needs disk headroom for the new table and indexes, a list of maintenance windows agreed with application owners, and a named contact who can approve the final lock moment. Teams should also provide monitoring access so the repack can be watched for lock waits, replication lag and disk growth. Confirm early whether backups are current and tested, because any schema-level change carries a recovery dependency.
Can our own DBAs run pg_repack without outside help?
Yes, if the team already operates PostgreSQL and can read the requirements, test on staging, and manage the lock moments. Teams usually succeed when they have someone who understands bloat measurements, can read locking behavior in pg_locks and pg_stat_activity, and can roll back a stalled job. The work becomes harder when many databases must be cleaned, when the tables are large relative to free space, or when the same team also owns releases and incidents. Run a small pilot on a non-critical table first, document each step, and decide afterward whether the process should be repeated by staff or handed to a partner.
When should we hire an outside team for bloat cleanup?
Consider outside help when the cleanup touches production systems that cannot tolerate mistakes, when internal staff lack time or experience with online table rewrites, or when the cleanup must be evidenced for an internal audit or a customer security review. An outside team can plan the work as a fixed-scope engagement with written deliverables, rehearse on staging, and produce a runbook and before-and-after measurements. DeployOpen implements and hardens self-hosted open-source platforms in the client's own infrastructure, so the work stays inside your environment. Ask for the scope, the rehearsal plan, the rollback steps and who holds on-call responsibility during the change.
How do we tell if bloat is the real cause of a slowdown?
Bloat is the real cause only when measurements show that dead space is inflating the pages a slow query must read, and when that slowdown tracks the growth of the table. Compare estimated bloat against actual table size, check whether sequential and index scans read far more pages than the live rows need, and review autovacuum history for the affected tables. Then examine other candidates such as missing indexes, lock waits, long transactions, I/O saturation and memory pressure before changing anything. If a slow query improves after a test repack on a copy, that is strong evidence. If it does not, the problem lies elsewhere.
What risks should we plan for during the repack?
The main risks are brief lock contention at the swap, replication lag from the write volume, running out of disk space mid-process, and a stalled job holding resources. Plan a lock timeout so the job gives up rather than queuing behind long transactions, watch standby lag if replication is in use, and confirm free space before starting. Also verify that autovacuum settings and backups are in a known state, and have a documented way to cancel the job cleanly. Ask any team you engage to show how each of these risks is detected and handled in the runbook.
How a pg_repack run moves from measurement to verification
The run starts with measuring bloat on the target table and its indexes, then checks prerequisites such as a primary key or unique index and free disk space for the rebuilt copy. A dry run on staging comes before production, so the team can see how long the rebuild takes and where the brief lock moments fall. Only after the production repack should the team verify table and index size, replication lag and that the next backup completes.
Decision path from bloat measurement through staging, repack and post-run checks.
How DeployOpen scopes and delivers PostgreSQL bloat cleanup
DeployOpen treats bloat cleanup as a planned change to a running database, not a one-off command. We scope the tables and indexes involved, test the reorganization on a copy of your data, and agree the lock moments, rollback and verification steps in writing before anything runs on production.
How we scope
- Inventory bloated tables and indexes with measurements agreed with your team before choosing a method
- Confirm each target has a primary key or unique index, since pg_repack depends on one
- Record disk headroom, replication setup and the write windows your applications can tolerate
How we build
- Install and version-match the pg_repack extension to your PostgreSQL major version on a staging copy first
- Rehearse each repack, timing the brief exclusive lock moments and confirming the disk space it needs
- Schedule production runs table by table, with lock timeouts and monitoring of replication and WAL growth
How we hand over
- Deliver a written runbook covering commands, prerequisites, lock behavior, failure recovery and cleanup of leftover objects
- Document before and after bloat measurements, and the autovacuum or fillfactor settings that slow new bloat
- Train your DBAs to run the process and to plan for the REPACK command once your version supports it
How we support
- Engagements are fixed-scope, with scope, deliverables and timelines agreed in writing before work starts
- Ongoing support, upgrades and periodic bloat review are available as a retainer
- Confirm with us which PostgreSQL versions and repack options apply to your environment before quoting

