When a PostgreSQL table experiences many UPDATE and DELETE operations, deleted row space stays inside table files as bloat. In older versions, reclaiming that disk space with VACUUM FULL locked the entire table and blocked all application queries. Starting in PostgreSQL 19, the native REPACK command with CONCURRENTLY lets you rebuild a bloated table online while reads and writes keep running.
Copy Active Rows → Track Live Changes (Replication Slot) → Brief Swap + Fresh Stats (ANALYZE)
Why Table Bloat Happens
PostgreSQL uses Multi-Version Concurrency Control (MVCC), which marks old row versions as dead rather than overwriting them immediately. Normal AUTOVACUUM lets PostgreSQL reuse space inside the table, but when a huge batch of rows is deleted or updated, disk space is not returned to the operating system until the table is rewritten.
1. Basic Concurrent Repack with Statistics Refresh
Run REPACK outside any BEGIN ... COMMIT transaction block. Passing both CONCURRENTLY and ANALYZE cleans up the table online and refreshes planner statistics right afterward:
-- Check current size first
SELECT pg_size_pretty(pg_total_relation_size('student_logs')) AS before_size;
-- Set a short lock timeout for the final table swap step
SET lock_timeout = '5s';
-- Repack online and refresh query planner statistics
REPACK (CONCURRENTLY, ANALYZE) student_logs;
-- Compare size after repacking
SELECT pg_size_pretty(pg_total_relation_size('student_logs')) AS after_size;
2. Optional: Reorder Rows Using an Index
If queries frequently scan rows in order of a specific index (replacing legacy CLUSTER workflows), pass USING INDEX:
REPACK (CONCURRENTLY, VERBOSE) student_logs USING INDEX student_logs_pkey;
Three Important Rules to Remember
- Cannot run inside a transaction block: Always execute
REPACK (CONCURRENTLY)as a standalone command because it manages an internal logical replication slot. - Always use
lock_timeoutin busy apps: Although the data copy runs online, the final table swap briefly needs an exclusive lock—a5stimeout stops it from blocking a busy queue. - Ensure free disk space: Repacking builds a fresh copy alongside the original table before swapping, so your server needs room for the compacted copy.
Practice
- Create a test table with 50,000 rows, delete 40,000 rows, and measure
pg_total_relation_size(...)before and afterREPACK (CONCURRENTLY, ANALYZE). - Run
REPACKwith theVERBOSEoption to inspect progress output inpsql. - Compare
VACUUM FULLlocking behavior withREPACK (CONCURRENTLY)in two separatepsqlsessions.
Continue learning: SQL Learning for Beginners: Complete Tutorial Path.
References: PostgreSQL Official Documentation.
No comments:
Post a Comment
Please do not enter any spam link in the comment box.