NEW RasterizedDB 1.1.0 is out: sharding and the gateway, the message broker, roles and row-level security, compression, .NET on NuGet, and the enterprise edition. What's new ›
DOCS / RASTERIZEDDB SERVER / MAINTENANCE: VACUUM, COMPACTION AND DISK SPACE

Maintenance: VACUUM, compaction and disk space

RasterizedDB reclaims the space that deleted and updated rows leave behind on its own, in the background. This page explains what runs automatically, when to run VACUUM or VACUUM FULL yourself, how to tune automatic compaction, and how to read a table's disk usage.

What happens on its own

Two background tasks keep tables from growing without bound. Neither needs any setup.

Background reclamation. About every 30 seconds, each table is checked for row bytes that no query can see any more: rows removed by a committed DELETE, old versions left by an UPDATE, and rows written by a transaction that rolled back. That space goes on the table's free list, and new inserts and relocating updates write into it before the file grows. A table with no DELETE or UPDATE since its last check is skipped, so read-only and insert-only tables cost nothing.

Reclamation never frees a row version that an open transaction can still see. A long-running transaction or snapshot therefore holds space back until it ends.

Automatic compaction. Background reclamation reuses row bytes but never gives back pointer slots (one per row version, in the table's pointer file), and it never makes a file shorter. Only a compaction, the same work as VACUUM FULL, does that. Once a minute the server looks at every table and every open partition and compacts the ones whose slots are mostly dead (see Tuning automatic compaction). A table that is in use at that moment is skipped, never waited for, and tried again on the next pass.

Running VACUUM yourself

sql
VACUUM;                 -- every table in the current database
VACUUM orders;          -- one table
VACUUM FULL;            -- compact every table
VACUUM FULL orders;     -- compact one table

PostgreSQL's option forms are accepted and the options ignored, so tools that send them still work:

sql
VACUUM (VERBOSE, ANALYZE) orders;
VACUUM VERBOSE ANALYZE orders;
VACUUM FULL VERBOSE;

A quoted name (VACUUM "orders") works too. On a partitioned table, VACUUM and VACUUM FULL act on each of its partitions.

VACUUM and VACUUM FULL run on their own, outside any transaction: in a multi-statement batch they are not wrapped in the implicit transaction the rest of the batch shares.

VACUUM

Plain VACUUM runs the background reclamation now, for the named table or all of them, without waiting for the next tick and without the size thresholds the background task applies. It does not block reads or writes.

It cannot free what an older running query or transaction might still read. If such queries do not finish within 30 seconds, the run is put off and nothing is freed; the next run tries again.

Use it after a large DELETE when you want the space reused straight away rather than within the next half minute.

VACUUM FULL

VACUUM FULL compacts the table in place: it moves live rows down to close the holes, renumbers pointer slots so there is about one per live row, rebuilds the table's filter index, and then truncates both files so the space goes back to the filesystem.

  • It takes an exclusive lock on the table. Every other read and write of that table waits until it finishes.
  • Its cost grows with the number of live rows. Run it on a large table in a quiet period.
  • It is safe to interrupt. Each move is its own small transaction, so a crash or restart leaves a table that is partly compacted and fully correct; the next run carries on.
  • The truncation waits for a checkpoint of the write-ahead log, and a checkpoint cannot run while any transaction is open. If the log is busy, the rows are compacted but the files keep their length; SHOW TABLE STATS counts this in vacuum_full_untruncated. Run VACUUM FULL again once long transactions have finished.

When do you need it? Mostly you don't: automatic compaction covers update-heavy tables and tables that churn through their rows. Run it yourself after deleting most of a large table (above the size automatic compaction will stop a table for, --auto-compact-dead-fraction-max-slots), or when you need the disk space back now.

Checking a table's space

SHOW TABLE STATS returns one row per metric for one table. The rows that matter for maintenance:

sql
SHOW TABLE STATS orders;
MetricWhat it tells you
data_bytesRow data on disk.
pointer_bytesThe pointer file, one record per row slot.
total_bytesEvery file the table owns.
row_slotsPointer records. An upper bound on live rows, not a row count.
live_rowsLive rows as the last reclamation pass counted them, adjusted for inserts and deletes since. not measured until a pass has run.
slots_per_live_rowSlots per live row. Near 1 is healthy; a large number means VACUUM FULL (or automatic compaction) would shrink the pointer file.
reclaimable_bytesDead row bytes on the free list right now.
dead_ratioreclaimable_bytes as a share of row data.
vacuum_enabledWhether background reclamation runs for this table.
vacuum_runs, vacuum_compactionsReclamation runs, and runs that actually reclaimed something.
vacuum_deferralsRuns held off by an open snapshot or long query. A count that keeps rising while the table grows points at a transaction that never ends.
vacuum_full_untruncatedVACUUM FULL runs that compacted but could not shorten the files because the log was busy.
vacuum_last_reclaimed_bytes, vacuum_total_reclaimed_bytesWhat the last run returned, and the total since the table opened.

SHOW TABLES lists every table with its sizes, and SHOW STATS (or SHOW DATABASE STATS) gives database-wide figures, including:

MetricWhat it tells you
auto_compactionsTables and partitions compacted automatically.
auto_compactions_skipped_busyCompactions that were due but put off because the table was in use.

SELECT COUNT(*) is the exact live row count; it scans the table. See Monitoring for the rest of the statistics.

Tuning automatic compaction

A table or partition is due for automatic compaction when it has at least min_slots pointer slots and either rule holds:

  • Amplification: its slots are at least ratio times its live rows. This is the shape of an update-heavy table (a heartbeat, a lease, a counter), where every update leaves a slot behind. Applies at any size.
  • Dead fraction: at least dead_fraction of its slots are dead, and it has at most dead_fraction_max_slots slots. This is the shape of a retention table or a partition that rows pass through. The size cap keeps it from stopping a large table for seconds because a quarter of it turned over.

No table or partition is compacted more often than once per cooldown_secs. A compaction waits at most 100 ms for the table's lock; if the table is busy, it is skipped until the next pass.

Each setting has a start-up flag and a SET CONFIG key of the same name:

FlagSET CONFIG keyDefaultWhat it does
--auto-compact on|offauto_compact.enabledonTurns automatic compaction on or off.
--auto-compact-interval-secs <SECS>auto_compact.interval_secs60Seconds between two looks at every table and open partition.
--auto-compact-min-slots <N>auto_compact.min_slots2048Slots a table or partition needs before it can be due at all.
--auto-compact-ratio <N>auto_compact.ratio8The amplification rule's slots-per-live-row threshold. 0 turns the rule off.
--auto-compact-dead-fraction <0..1>auto_compact.dead_fraction0.25The dead-fraction rule's threshold. 0 turns the rule off.
--auto-compact-dead-fraction-max-slots <N>auto_compact.dead_fraction_max_slots131072The dead-fraction rule applies only up to this many slots (about 2 seconds of compaction). 0 is no limit.
--auto-compact-cooldown-secs <SECS>auto_compact.cooldown_secs600Least seconds between two automatic compactions of the same table or partition.

Change a setting on a running server (superuser only):

sql
SET CONFIG auto_compact.dead_fraction = 0.2;
SET CONFIG auto_compact.dead_fraction_max_slots = 262144;
SET CONFIG auto_compact.enabled = off;
SHOW CONFIG;

A change takes effect on the next pass (a new interval within about 5 seconds). The server also saves it and applies it at the next start, unless that start gives the matching flag, which wins over a saved value. See Configuration for how saved settings work.

Or set them at start-up:

sh
rasterizeddb --location /var/lib/rasterizeddb \
  --auto-compact-dead-fraction 0.2 \
  --auto-compact-cooldown-secs 300

Partitioned tables

A partitioned table is measured and compacted partition by partition. Each open partition is checked with the same rules as a plain table, a due one is compacted on its own (under the partitioned table's exclusive lock, with the same 100 ms wait), and each partition has its own cooldown. A closed partition is not opened just to be measured; it is considered again once it is open and a reclamation pass has counted its rows.

A hash-partitioned table whose rows expire on a schedule is the case the dead-fraction rule exists for. With the defaults, a partition of a few thousand to about 130,000 slots that is a quarter dead is compacted on its own, in a fraction of a second, instead of needing a nightly VACUUM FULL of every partition at once. To cover larger partitions, raise auto_compact.dead_fraction_max_slots; to compact sooner, lower auto_compact.dead_fraction.

See Partitioning for creating and reshaping partitioned tables.

Turning background reclamation off

Background reclamation can be switched off for every table in the current database:

sql
SET CONFIG vacuum.enabled = off;
text
background reclamation disabled for 12 tables (64 partitions)

With it off, deleted and updated rows' space is not reused and tables only grow; switching it off also drops each table's current free list. SET CONFIG vacuum.enabled = on starts it again from an empty list, which the next pass fills. This setting acts on one database and is not saved: a restart turns reclamation back on. SHOW CONFIG reports it as per table; check vacuum_enabled in SHOW TABLE STATS for a given table.

There is rarely a reason to turn it off. It does not stop automatic compaction, which has its own switch.

Checkpoints and the write-ahead log

Every write goes to the write-ahead log first. A checkpoint flushes every data file and discards the log, and runs on its own each time the log reaches a size threshold.

FlagDefaultWhat it does
--wal-checkpoint-bytes <N>67108864 (64 MiB)Log bytes between checkpoints. Larger means fewer checkpoints and a longer replay after a crash. Takes a restart.
--wal-prealloc-kb <KB>1024KiB of zeros the log is extended by ahead of its appends, so a commit syncs blocks the log already owns. Costs up to this much disk per log. 0 turns it off.

A checkpoint never runs while a transaction is open. A session left idle inside a transaction therefore makes the log grow until it ends, and also holds back reclamation and the truncation step of VACUUM FULL. To close such sessions automatically, start the server with --idle-in-transaction-session-timeout (see Configuration).

With S3 backup on, checkpoints stage the log for upload instead of discarding it; see Backup and restore.

Disk space checklist

  • A table keeps growing although its row count is steady. Check vacuum_deferrals, and look for an application that leaves sessions inside an open transaction. Reclamation cannot free versions an open snapshot still sees.
  • slots_per_live_row is high. Automatic compaction should catch it; if the table is over --auto-compact-dead-fraction-max-slots, or always busy (auto_compactions_skipped_busy rising), run VACUUM FULL in a quiet period.
  • VACUUM FULL did not shrink the files. vacuum_full_untruncated went up: a transaction was open. Run it again when none is.
  • The disk is filling. Free space first with VACUUM FULL on the tables with the largest reclaimable_bytes or slots_per_live_row. To spread a database over more disks, see Storage pools.

Limits

  • Background reclamation reuses row space but never shortens a file or gives back pointer slots; only VACUUM FULL (run by hand or automatically) does.
  • VACUUM FULL blocks every read and write of the table while it runs.
  • VACUUM's ANALYZE, VERBOSE and FREEZE options are accepted and do nothing.
  • SET CONFIG vacuum.enabled is per database and lasts until restart.
✓ page rendered in 215 µs axum + tera + htmx · no other javascript