Sub topic 10
Rewriting with minimal locking: pg_repack and REPACK
This chapter assumes you know what table bloat is and how to measure it with pg_stat_user_tables and pgstattuple. It also assumes you know that plain VACUUM only marks space reusable inside the table file, and that VACUUM FULL rewrites the table under an ACCESS EXCLUSIVE lock. You should be comfortable running SQL in psql and basic shell commands.
Why a lower-locking rewrite exists
VACUUM FULL solves heavy bloat by building a compact copy of the table. The cost is that every read and write on the table waits until the rewrite finishes. On a large table that can mean minutes or hours of downtime, which is why many teams cannot use it on a live system.
Online repacking tools do the same rewrite but let normal traffic continue while the copy is built. They take an exclusive lock only briefly, at the start and at the end. This chapter covers two of them:
pg_repack, an extension plus a command-line client that works on many PostgreSQL versions.REPACK, a built-in SQL command that exists only in PostgreSQL versions that ship it.
How pg_repack works
pg_repack never modifies your table in place. It builds a new copy next to it and swaps the two at the end.
- It takes a short lock, creates a log table, and adds a trigger on your table. The trigger records every
INSERT,UPDATE, andDELETEmade while the copy is being built. - It copies all live rows into a new table, so dead tuples are left behind. If you ask for an ordering, the copy is written in that order.
- It builds every index on the new table.
- It replays the rows from the log table into the new table, repeating until the backlog is small.
- It takes a short
ACCESS EXCLUSIVElock, replays the last changes, and swaps the old and new files. - It drops the old table and the log table.
During steps 2 to 4 the table stays fully readable and writable. Only steps 1 and 5 block other sessions.
Running pg_repack
Install the extension package for your server version, then create the extension in each database you want to repack. Then run the client from a shell.
pg_repack --dbname=mydb --table=public.ordersThe command-line client and the extension version must match. If they do not, pg_repack stops with a version error.
Before the first run, create the extension from SQL:
CREATE EXTENSION IF NOT EXISTS pg_repack;Requirements to check first
The table needs a primary key, or at least a unique index on NOT NULL columns. The tool uses that key to match rows when it replays logged changes. You can check what a table has with this query:
SELECT indexrelid::regclass AS index_name,
indisprimary,
indisunique
FROM pg_index
WHERE indrelid = 'public.orders'::regclass
AND indisunique;If the query returns no rows, pg_repack refuses to repack the table. Add a key first, or use another method.
You also need enough free disk space. During the run the old table, the new table, all their indexes, and the log table exist at the same time. Plan for roughly the table's total size again.
SELECT pg_size_pretty(pg_total_relation_size('public.orders')) AS total_size;Other requirements: the role running the tool normally needs to be a superuser, though some managed services provide a restricted setup, so check your provider's documentation.
Useful options
| Option | Effect |
|---|---|
| `--table`, `-t` | Repack one table. Can be given more than once. |
| `--index`, `-i` | Rebuild a single index online. |
| `--only-indexes` | Rebuild all indexes of the named table, not the table itself. |
| `--order-by`, `-o` | Write the new copy in the given column order. |
| `--no-order`, `-n` | Skip ordering, as `VACUUM FULL` does. |
| `--wait-timeout` | How long to wait for the final lock before acting on conflicting sessions. |
| `--no-kill-backend` | Give up instead of cancelling sessions that block the final lock. |
| `--dry-run` | Check that the run would be possible, without changing anything. |
| `--jobs`, `-j` | Build indexes in parallel with more connections. |
Run pg_repack --help on your installation to see the exact list for your version.
The final lock and long transactions
The final swap needs ACCESS EXCLUSIVE. If a long transaction still holds any lock on the table, pg_repack has to wait. After --wait-timeout expires, the default behavior is to cancel the conflicting queries so the swap can proceed. If you would rather not interrupt anyone, pass --no-kill-backend, and the run is skipped when it cannot get the lock.
The same long transactions that block VACUUM also hurt here. Check for them before you start, using the pg_stat_activity query from the previous chapters.
Costs and risks
- Write amplification. The copy, the index builds, and the replay all produce WAL. Expect replicas to lag and archive volume to grow.
- Extra load. The trigger adds work to every write on the table while the run is active.
- Disk. A failed run can leave behind a partial new table and a log table. If a run is interrupted, check for leftovers before retrying, and consult the
pg_repackdocumentation for cleanup. - A busy table takes longer. The replay loop has to keep up with incoming writes. A table with heavy write traffic and little time between swaps may need a quieter period.
The built-in REPACK command
PostgreSQL has historically offered VACUUM FULL and CLUSTER as the built-in ways to rewrite a table. Newer versions add a single command, REPACK, that covers table rewrites:
REPACK public.orders;Two cautions apply.
- It exists only in versions that ship it. It was added in recent development of PostgreSQL, so on older releases the statement is a syntax error. Look at the SQL command reference for your exact server version before you rely on it.
- The plain form locks like VACUUM FULL. It holds an
ACCESS EXCLUSIVElock for the whole rewrite, so reads and writes on the table wait. Check your version's documentation for whether it also offers a lower-locking variant, and for its exact requirements and options. Do not assume it behaves likepg_repackjust because the names are similar.
Confirm what your server supports before planning around it:
SELECT version();Choosing a method
| Method | Lock during rewrite | Needs extra install | Needs unique key | Typical use |
|---|---|---|---|---|
| `VACUUM` | None that blocks reads or writes | No | No | Routine cleanup, no space returned to the OS |
| `VACUUM FULL` | `ACCESS EXCLUSIVE` for the whole run | No | No | Maintenance window, small or idle tables |
| `pg_repack` | Short exclusive locks at start and end | Yes | Yes | Large live tables on many versions |
| `REPACK` (plain) | `ACCESS EXCLUSIVE` for the whole run (as `VACUUM FULL`) | No, but version-dependent | No | Version-supported built-in rewrite in a window |
A workable decision path:
- If the table is only mildly bloated and autovacuum is healthy, do nothing. Reused space inside the file is not a problem.
- If space is wasted and you can take the table offline briefly, use
VACUUM FULLor plainREPACK. - If the table is large and must stay available, use
pg_repack, assuming it has a usable key and you have free disk. - If only an index is bloated, rebuild just the index with
REINDEX INDEX CONCURRENTLY, which is covered in a later chapter.
A practical workflow
- Measure with
pgstattupleand confirm the wasted space is large enough to matter. - Check for blockers in
pg_stat_activity. End or fix long transactions first. - Check the table has a unique key and that free disk is at least the table's total size.
- Run
pg_repack --dry-runto confirm the run is possible. - Run the real command during a quiet period, watching replication lag and disk.
- Re-measure afterwards, and then fix the cause of the bloat so it does not return.
Exercise
A 200 GB table named events has no primary key and no unique index. It is badly bloated and cannot go offline. Can you run pg_repack on it as it is, and what are your options?
Show answer
No. pg_repack needs a primary key or a unique index on NOT NULL columns to match rows when it replays logged changes, so it refuses to repack this table. Options: add a primary key or a suitable unique index first (building it concurrently with CREATE UNIQUE INDEX CONCURRENTLY avoids blocking writes) and then run pg_repack. Or, if the table can be offline for a while, use VACUUM FULL, or plain REPACK where available, accepting the ACCESS EXCLUSIVE lock.
Exercise
During a pg_repack run, the tool seems stuck near the end. What is the most likely cause, and how can you choose between waiting and cancelling the blockers?
Show answer
It is most likely waiting for the final ACCESS EXCLUSIVE lock because a long transaction still holds a lock on the table. By default, after --wait-timeout it cancels the conflicting queries. If you do not want to interrupt anyone, pass --no-kill-backend so the run is skipped when the lock cannot be taken. You can find the blocking session in pg_stat_activity and deal with it yourself.