Skip to content

Use pg_repack to Remove Table Bloat

Rebuild a bloated table or index with the pg_repack extension and its client program, without holding an exclusive lock for the whole operation.

Before You Start

  • Open a psql session against your service as avnadmin. See Connect with psql.

  • Read the extension version offered on your service. The client program you install later must have exactly this version:

    SELECT name, default_version
    FROM pg_available_extensions
    WHERE name = 'pg_repack';
  • The table must have a PRIMARY KEY, or a UNIQUE index on NOT NULL columns. Otherwise the client skips it with WARNING: relation "public.TABLE" must have a primary key or not-null unique keys.

  • The service needs free disk space, see Disk Headroom.

Find the Bloated Tables

Rank candidates by dead tuples with the statistics views, which need no extension:

SELECT
    schemaname,
    relname,
    n_live_tup,
    n_dead_tup,
    round(100.0 * n_dead_tup / NULLIF(n_live_tup + n_dead_tup, 0), 1) AS dead_pct,
    pg_size_pretty(pg_total_relation_size(relid)) AS total_size,
    last_autovacuum
FROM pg_stat_user_tables
WHERE n_dead_tup > 0
ORDER BY n_dead_tup DESC
LIMIT 20;

For an exact figure on one table, use pgstattuple. It reads every page of the table, so run it on large tables only when the extra I/O is acceptable:

CREATE EXTENSION IF NOT EXISTS pgstattuple;
SELECT table_len, tuple_count, dead_tuple_count, free_percent
FROM pgstattuple('public.orders');

Note

If autovacuum visits a table regularly and dead tuples still pile up, a long-running transaction or an unused replication slot is usually holding back cleanup. Repacking does not fix that. Check pg_stat_activity and pg_replication_slots first.

Enable the Extension

Connected as avnadmin, in the database that holds the table:

CREATE EXTENSION pg_repack;

The extension creates a repack schema, used by the client program to plan and track its work.

Install the Client Program

The work is driven by the pg_repack command-line program, which you run from your own machine. Install it in the same version as the extension, for example from your operating system’s PostgreSQL packages or by building the matching release from the pg_repack source. Check the version:

pg_repack --version

A client of another version stops immediately with an error such as program 'pg_repack 1.5.1' does not match database library 'pg_repack 1.5.2'.

Repack a Table

Read the connection details of the service:

exo dbaas show SERVICE_NAME -z ZONE --uri

Then run the client:

PGPASSWORD=PASSWORD PGSSLMODE=require \
  pg_repack -k -h HOSTNAME -p PORT -U avnadmin -d DATABASE_NAME -t TABLE_NAME

Parameters:

  • SERVICE_NAME: name of the service.
  • ZONE: zone of the service, for example ch-gva-2.
  • PASSWORD, HOSTNAME, PORT: values from the connection URI.
  • DATABASE_NAME: database that holds the table, for example defaultdb.
  • TABLE_NAME: schema-qualified table name, for example public.orders.

-k (--no-superuser-check) is required. Without it, the client stops with You must be a superuser to use pg_repack, because avnadmin is not a superuser.

Other useful options:

  • --dry-run: print what would be repacked, and change nothing.
  • -j N: build indexes with N parallel connections.
  • -i INDEX_NAME: repack one index only.
  • -x: repack all indexes of the table, without rewriting the table.
  • -T SECONDS: when conflicting transactions block the client for longer than this, cancel them.

Disk Headroom

pg_repack builds a complete copy of the table and its indexes, and drops the old copy only at the end. The service needs free space at least equal to the current size of the table and its indexes, plus the changes written during the run:

SELECT pg_size_pretty(pg_total_relation_size('public.orders')) AS needed_at_least;

Compare this with the free disk of your service. The disk size of each plan is shown by exo dbaas type show pg --plans. If the margin is thin, move to a larger plan first, see Scale a service and Prevent a full disk. Repack large tables one at a time.

Locks

pg_repack takes an ACCESS EXCLUSIVE lock twice, briefly: once at the start, to install the trigger that records concurrent changes, and once at the end, to swap the new table in. Between the two, reads and writes continue.

Each lock waits for transactions that already use the table. While it waits, new queries on the table queue behind it, so an idle open transaction can stall the application. With -T, the client cancels the blocking sessions after the timeout and prints WARNING: canceling conflicted backends; the canceled sessions receive canceling statement due to user request:

PGPASSWORD=PASSWORD PGSSLMODE=require \
  pg_repack -k -T 60 -h HOSTNAME -p PORT -U avnadmin -d DATABASE_NAME -t TABLE_NAME

Run repacks during a quiet period.

Clean Up After an Interrupted Run

A client stopped with Ctrl+C cleans up after itself. A client that is killed, or loses its connection, can leave a repack_trigger on the table and log_* tables in the repack schema. The next run then refuses to start with WARNING: the table "public.orders" already has a trigger called "repack_trigger".

Drop the extension with CASCADE, which removes the leftover objects and the trigger, then create it again:

DROP EXTENSION pg_repack CASCADE;
CREATE EXTENSION pg_repack;

A plain DROP EXTENSION pg_repack fails while leftovers exist, and lists them.

When to Use VACUUM FULL Instead

VACUUM FULL also rewrites the table, but holds an ACCESS EXCLUSIVE lock until it finishes, so nothing can read or write the table meanwhile. It is the simpler choice when the table is small, has no primary key or suitable unique index, or is no longer written to.

If the same table needs repacking again and again, tune autovacuum for it instead, for example:

ALTER TABLE public.orders SET (
    autovacuum_vacuum_scale_factor = 0.02,
    autovacuum_vacuum_cost_limit = 1000
);

Related Pages

Last updated on