PostgreSQL REPACK CONCURRENTLY: Shrink Bloated Tables Online
PostgreSQL 19's REPACK (CONCURRENTLY) rewrites a bloated table while reads and writes keep running. Lab-tested steps, the lock and snapshot caveats, and a retry script.

Your orders table has 600,000 live rows and takes 422 MB on disk. Most of that file is empty space. Autovacuum is running, dead tuples are near zero, and the file still won't shrink. The usual fix, VACUUM FULL, locks the table for the whole rewrite, so every checkout, webhook and admin page that touches it waits. The other usual fix, the pg_repack extension, is one more moving part to install and upgrade.
PostgreSQL 19, released on 19 November 2026, adds a built-in answer: PostgreSQL REPACK CONCURRENTLY. It rewrites a bloated table into a compact new file while reads and writes keep running, and only takes an exclusive lock for the final swap. We ran it on PostgreSQL 19.0 under a live read/write workload to see how it behaves, where it can still stall your application, and what to check before you run it in production.
Why VACUUM doesn't give the space back
PostgreSQL never updates a row in place. An UPDATE writes a new row version and leaves the old one behind; a DELETE only marks the row dead. Regular VACUUM later marks that space as reusable, but it almost never returns it to the operating system. The table file stays the same size, full of holes that future inserts may or may not fill.
That is usually fine. It becomes a problem after a backfill that touched every row, a purge of old data, or a status column updated millions of times. Then you have a large file that is mostly empty space, larger backups and slower sequential scans.
In our lab we built exactly that. We loaded 1,000,000 orders, updated 70% of them twice (changing an indexed column, so no HOT updates), deleted the oldest 400,000 and ran VACUUM. The result: 600,000 live rows, a 422 MB heap and 75 MB of indexes, with pgstattuple reporting 72% of the table as free space and zero dead tuples. VACUUM had done its job. The disk usage stayed.
What REPACK is
The PostgreSQL 19 release notes describe REPACK as a new command that replaces VACUUM FULL and CLUSTER. Those two did nearly the same thing under confusing names. Both still work for compatibility, and in our tests they reported progress through the same new view.
REPACK ordersrewrites the table without dead space. This is the oldVACUUM FULL, and it holds anACCESS EXCLUSIVElock the whole time.REPACK orders USING INDEX orders_pkeyalso sorts the rows by that index. This is the oldCLUSTER.REPACK (CONCURRENTLY) ordersdoes the copy under aSHARE UPDATE EXCLUSIVElock, which allows reads and writes. Changes made during the copy are captured through logical decoding and replayed, andACCESS EXCLUSIVEis only needed to swap the old and new files.
The REPACK reference page covers the full syntax. The options are VERBOSE, ANALYZE and CONCURRENTLY, and they can be combined.

pg_stat_progress_repack. Only the swap needs ACCESS EXCLUSIVE, but phases 1 and 3 can wait on other sessions.Step 1: Find the tables that are actually bloated
Don't repack a table because it is big. Repack it because a large share of it is empty. The pgstattuple extension ships with PostgreSQL as a contrib module, and its pgstattuple_approx() function estimates free space without reading every tuple:
CREATE EXTENSION IF NOT EXISTS pgstattuple;
SELECT c.oid::regclass AS table_name,
pg_size_pretty(pg_table_size(c.oid)) AS heap_size,
round(s.approx_free_percent::numeric, 1) AS free_pct,
round(s.dead_tuple_percent::numeric, 1) AS dead_pct
FROM pg_class c
CROSS JOIN LATERAL pgstattuple_approx(c.oid) s
WHERE c.relkind = 'r'
AND c.relnamespace = 'public'::regnamespace
AND pg_table_size(c.oid) > 100 * 1024 * 1024
ORDER BY s.approx_free_space DESC
LIMIT 10;
On our lab table this returned 422 MB heap and 71.8 percent free. As a rule of thumb, 10โ20% free space is normal and VACUUM will keep reusing it. Above 50%, and especially when the table no longer grows, a rewrite is worth it. On very large databases run it in a quiet period: pgstattuple_approx skips all-visible pages but still reads the rest.
Step 2: Check the table can be repacked concurrently
The concurrent mode has more restrictions than the plain command. We tried each one on PostgreSQL 19.0. These are the actual errors:
- No primary key or replica identity index:
Relation "no_pk" has no identity index.Adding a unique index on aNOT NULLcolumn and setting it asREPLICA IDENTITY USING INDEXmade the same table work. REPLICA IDENTITY FULL:This operation does not support tables with REPLICA IDENTITY FULL.This failed even with a primary key, which the docs don't spell out. Some change-data-capture setups useFULL, so check before you plan.- Partitioned parent:
REPACK (CONCURRENTLY) is not supported for partitioned tables, with the hint to run it on individual partitions. Repacking a single partition worked. - Unlogged tables and materialized views: refused. Plain
REPACKstill works on a materialized view. - Inside a transaction block: refused. Some migration tools wrap every statement in a transaction, so run it from
psqlor a script with autocommit on. - No table name:
REPACK (CONCURRENTLY)on its own is rejected. You repack one table at a time. - An invalid index (left over from a failed
CREATE INDEX CONCURRENTLY):An invalid index cannot be processed correctly. Drop or rebuild it first.
This query checks all of those for one table:
SELECT c.oid::regclass AS table_name,
c.relkind = 'p' AS partitioned_parent,
c.relpersistence = 'u' AS unlogged,
c.relreplident = 'f' AS replica_identity_full,
EXISTS (SELECT 1 FROM pg_index i
WHERE i.indrelid = c.oid
AND (i.indisprimary OR i.indisreplident)) AS has_identity_index,
EXISTS (SELECT 1 FROM pg_index i
WHERE i.indrelid = c.oid AND NOT i.indisvalid) AS has_invalid_index
FROM pg_class c
WHERE c.oid = 'orders'::regclass;
Step 3: Check disk space and long transactions
REPACK builds a full copy of the table and every index before it drops the old files. The docs ask for free disk space at least equal to the table plus its indexes. In our concurrent run the database grew by 139 MB at its peak, roughly the size of the new compact table and indexes. On a nearly full volume, a failed repack is worse than no repack. Changes made during the copy are also written to disk until they are replayed.
The second check is long transactions. The first phase, initializing, waits for every transaction that already has a transaction ID (any transaction that has written something) to finish. That includes transactions on completely unrelated tables. In our lab, one open INSERT into a different table kept REPACK in initializing until our 5-second statement_timeout cancelled it. Look before you start:
SELECT pid, usename, state, backend_xid,
now() - xact_start AS xact_age,
left(query, 60) AS last_query
FROM pg_stat_activity
WHERE xact_start IS NOT NULL
AND pid <> pg_backend_pid()
ORDER BY xact_start
LIMIT 10;
Rows with a non-null backend_xid and a large xact_age will hold REPACK up. An idle in transaction session from a forgotten console or a leaky connection pool is the usual culprit. idle_in_transaction_session_timeout on application roles prevents most of them.
Step 4: Run it with a lock timeout
SET lock_timeout = '5s';
SET maintenance_work_mem = '256MB';
REPACK (CONCURRENTLY, ANALYZE, VERBOSE) orders;
ANALYZE refreshes planner statistics for the new file, and VERBOSE prints what was removed. maintenance_work_mem speeds up the index rebuilds. lock_timeout matters most, and the next sections explain why. On the bloated lab table this took about a second and brought the table from 422 MB to 116 MB and the indexes from 75 MB to 22 MB.
The concurrent mode uses a temporary logical replication slot. You don't need to change wal_level: our server ran with the default replica, and PostgreSQL 19 raised the effective level to logical by itself while the slot existed. It went back to replica after a later checkpoint. The number of repacks that can run at once is capped by max_repack_replication_slots (default 5, restart required to change). After every run in our lab, including the cancelled ones, pg_replication_slots was empty again.
Step 5: Watch progress
Every REPACK, VACUUM FULL and CLUSTER reports progress in the new pg_stat_progress_repack view (see progress reporting). Adding pg_blocking_pids() shows straight away whether it is stuck behind another session:
SELECT p.pid, p.relid::regclass AS table_name, p.phase,
p.heap_blks_scanned, p.heap_blks_total,
p.heap_tuples_inserted, p.heap_tuples_updated, p.heap_tuples_deleted,
pg_blocking_pids(p.pid) AS blocked_by
FROM pg_stat_progress_repack p;
During the catch-up phase of our concurrent run, the view showed REPACK applying 420 updates and 58 deletes made by the workload while the copy was being built. If phase stays at initializing or catch-up and blocked_by is not empty, go to the next section.
What we measured
We ran three rewrites of the same bloated table while four writer threads (updates, inserts, deletes) and two reader threads (primary-key lookups) ran against it. A trigger kept a shadow copy of every change, so afterwards we could check that nothing was lost. Each scenario started from a freshly rebuilt table.
REPACK orders(plain): 1.00 s rewrite. Every statement that hit the table waited for it; the slowest took 917 ms against a normal p99 of a few milliseconds.VACUUM FULL orders: 0.95 s, same pattern, slowest statement 945 ms.REPACK (CONCURRENTLY) orders: 1.35 s. 1,142 statements started during the rewrite, compared with 91 for plain REPACK, and the slowest took 33 ms. Writes slowed down while the copy ran (update p99 about 20 ms), but nothing stopped.
All three produced the same result: a 116 MB heap and 22 MB of indexes. In every run, zero rows differed between the table and its shadow copy, and amcheck's bt_index_check passed on all three indexes.

REPACK stops all traffic on the table for the rewrite; REPACK (CONCURRENTLY) keeps it flowing.Keep the scale in mind. This is a 600,000-row table on one machine, so the plain rewrite only blocked for about a second. On a 200 GB table the same blocking rewrite can take many minutes, which is the reason the concurrent mode exists.
Caveat 1: The final lock can still queue your traffic
"Concurrently" covers the copy, not the swap. At the end, REPACK needs ACCESS EXCLUSIVE. If any session holds even a plain read lock on the table, for example a transaction that ran a SELECT and is now idle, REPACK waits in the catch-up phase. PostgreSQL lock requests queue in order, so while REPACK waits, every new query on that table waits behind it.
We reproduced it: with one session idle inside a transaction after a SELECT, REPACK stopped in catch-up, and a new primary-key lookup from a third session hit its 1-second statement_timeout while "waiting for AccessShareLock".
That is why the run script sets lock_timeout. With lock_timeout = '3s', REPACK gave up with canceling statement due to lock timeout and released the queue. The cost: all the copy work was thrown away, and a retry starts from the beginning. The same advice applies to any DDL, as in our guide to zero-downtime migrations on Django and PostgreSQL: always bound lock waits and retry, never wait forever.
Caveat 2: Old snapshots see an empty table
The docs warn that REPACK (CONCURRENTLY) is not MVCC-safe, and the concurrency caveats page now lists it next to TRUNCATE. We confirmed it:
-- session 1
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT 1; -- snapshot taken; orders not touched yet
-- session 2 runs: REPACK (CONCURRENTLY) orders;
SELECT count(*) FROM orders; -- returns 0 in our test
COMMIT;
The real table had 600,000 rows. The repeatable-read transaction, whose snapshot was taken before the repack but which had not touched orders yet, counted 0. The same test with plain REPACK returned the full count. This only affects transactions that hold an older snapshot and touch the table for the first time after the swap: long reporting queries at REPEATABLE READ, pg_dump runs, and export jobs. Don't schedule a concurrent repack on top of your backup or ETL window.
A small wrapper you can reuse
We wrapped the checks into one Python script (psycopg 3). It refuses ineligible tables, refuses to start while old write transactions are open, sets lock_timeout and retries with backoff:
"""Run REPACK (CONCURRENTLY) on one table with pre-flight checks and bounded lock waits.
usage: python repack_table.py <table> [--attempts 3] [--lock-timeout 5s] [--retry-wait 30]
Requires PostgreSQL 19+ and psycopg 3. Connection settings come from the usual
PG* environment variables (PGHOST, PGPORT, PGUSER, PGDATABASE, PGPASSWORD).
"""
import argparse, sys, time
import psycopg
from psycopg import errors, sql
PREFLIGHT = """
SELECT c.relkind = 'p', c.relpersistence = 'u', c.relreplident = 'f',
EXISTS (SELECT 1 FROM pg_index i WHERE i.indrelid = c.oid
AND (i.indisprimary OR i.indisreplident)),
EXISTS (SELECT 1 FROM pg_index i WHERE i.indrelid = c.oid AND NOT i.indisvalid),
pg_total_relation_size(c.oid)
FROM pg_class c WHERE c.oid = %s::regclass
"""
OLD_XACTS = """
SELECT count(*) FROM pg_stat_activity
WHERE backend_xid IS NOT NULL AND pid <> pg_backend_pid()
AND now() - xact_start > %s::interval
"""
def main():
ap = argparse.ArgumentParser()
ap.add_argument("table")
ap.add_argument("--attempts", type=int, default=3)
ap.add_argument("--lock-timeout", default="5s")
ap.add_argument("--max-xact-age", default="1 minute")
ap.add_argument("--retry-wait", type=int, default=30, help="seconds, multiplied by attempt")
a = ap.parse_args()
with psycopg.connect(autocommit=True) as conn:
if conn.info.server_version < 190000:
sys.exit("REPACK needs PostgreSQL 19 or later")
parted, unlogged, ri_full, has_ident, invalid, size = conn.execute(PREFLIGHT, (a.table,)).fetchone()
problems = [msg for bad, msg in [
(parted, "partitioned parent: repack each partition instead"),
(unlogged, "unlogged table"),
(ri_full, "REPLICA IDENTITY FULL"),
(not has_ident, "no primary key or replica identity index"),
(invalid, "has an invalid index: drop or REINDEX it first")] if bad]
if problems:
sys.exit(f"{a.table} can't be repacked concurrently: " + "; ".join(problems))
print(f"{a.table}: {size / 1024**2:.0f} MB incl. indexes; need about that much free disk")
old = conn.execute(OLD_XACTS, (a.max_xact_age,)).fetchone()[0]
if old:
sys.exit(f"{old} write transaction(s) older than {a.max_xact_age}; "
"REPACK would wait for them. Try again later.")
conn.execute(sql.SQL("SET lock_timeout = {}").format(sql.Literal(a.lock_timeout)))
stmt = sql.SQL("REPACK (CONCURRENTLY, ANALYZE) {}").format(
sql.Identifier(*a.table.split(".")))
for attempt in range(1, a.attempts + 1):
started = time.monotonic()
try:
conn.execute(stmt)
print(f"done in {time.monotonic() - started:.1f}s (attempt {attempt})")
return
except errors.LockNotAvailable:
print(f"attempt {attempt}: could not get the swap lock within "
f"{a.lock_timeout} after {time.monotonic() - started:.1f}s")
time.sleep(a.retry_wait * attempt)
sys.exit("gave up; the copy work of each attempt was thrown away")
if __name__ == "__main__":
main()
In the lab it repacked the bloated table in 1.3 s, refused the table without a primary key and the partitioned parent with clear messages, refused to start while a write transaction was older than the limit, and when another session held a lock it timed out twice and gave up instead of blocking traffic.
REPACK or pg_repack?
If you are on PostgreSQL 19 and the table meets the requirements above, the built-in command removes the need for an extension, its matching client binary and its upgrade cycle. Keep pg_repack where the built-in mode doesn't fit: tables with REPLICA IDENTITY FULL, rebuilding only indexes, or moving tables between tablespaces. At the time of writing, the pg_repack project page lists support up to PostgreSQL 18, so check your package source before you count on it for 19. We did not benchmark pg_repack in this lab.
The partitioned table limitation matters less than it sounds. If your large table is partitioned, you can repack partitions one by one, and for old data it is often cheaper to detach and drop whole partitions, as we showed in our PostgreSQL table partitioning guide.
Common mistakes
- Running it without
lock_timeout. One idle transaction turns an online operation into an outage. - Repacking instead of fixing the cause. If autovacuum can't keep up, or an update loop rewrites rows that didn't change, the table will bloat again. Tune autovacuum and fix the writes first.
- Repacking every big table on a schedule. A rewrite produces I/O and WAL that replicas must replay.
- Ignoring disk headroom. You need room for a second copy of the table and its indexes.
- Starting during backups or long reports. They hold old snapshots and long transactions, which can stall REPACK or see an empty table.
- Forgetting the planner. Use the
ANALYZEoption or runANALYZEafterwards. If query plans changed after the rewrite, our PostgreSQL slow query guide covers how to read them.
Recommendations
- Measure free space with
pgstattuple_approxand pick the worst one or two tables. - Check eligibility, disk space and long transactions before every run.
- Run
REPACK (CONCURRENTLY, ANALYZE)with alock_timeoutof a few seconds, in a low-traffic window, away from backups and ETL. - Watch
pg_stat_progress_repackandpg_blocking_pids()while it runs. - Afterwards, compare table size and check that replicas have caught up.
What we tested and what we didn't
Everything in this article ran on PostgreSQL 19.0 (conda-forge build) on a single Linux server on 3 December 2026, against a 600,000-row table of about 500 MB. Every SQL block and the Python script above were run against that server. We did not test streaming replicas or replication lag, logical replication subscribers, managed services such as Amazon RDS or Cloud SQL (check whether your provider offers 19 yet), tables in the hundreds of gigabytes, TOAST-heavy tables, or pg_repack side by side. Timings from a table this small don't predict how long a large production table will take.
FAQ
Does REPACK CONCURRENTLY block writes?
Not during the copy. It holds SHARE UPDATE EXCLUSIVE, which allows SELECT, INSERT, UPDATE and DELETE. It blocks other maintenance and DDL on the table, and it needs a short ACCESS EXCLUSIVE lock at the end.
Is VACUUM FULL deprecated?
The release notes say REPACK replaces VACUUM FULL and CLUSTER, and that the old commands are kept for compatibility. They still worked in our tests. For new scripts on 19, use REPACK.
Can I repack a partitioned table?
Plain REPACK processes every partition. The concurrent mode must be run on each partition separately.
Conclusion
REPACK (CONCURRENTLY) finally makes "shrink this table" a built-in, online operation in PostgreSQL. In our tests it kept a live workload running and lost no changes. It isn't fire-and-forget: it waits for old transactions at the start, its final lock can queue traffic, and old snapshots can see an empty table. Check before you run it, bound the lock wait, and watch the progress view, and it is a practical tool for production databases.
If your PostgreSQL database is growing faster than your data, or you are planning a PostgreSQL 19 upgrade for a SaaS or eCommerce backend, CodeSapient can help with the audit, the upgrade and the maintenance plan. See our development services or get in touch.
