ML
PostgreSQL

Postgres TOAST Table Bloat: Why Deleting Large Columns Never Reclaimed Disk Space

When Postgres stores values exceeding 2KB, it compresses and chunks them into out-of-line TOAST tables. Why mass UPDATEs and DELETEs bloat pg_toast without returning bytes to the OS, and how pg_repack reclaims stranded storage.

November 27, 202612 min readPostgresDatabasePerformanceStorageVACUUM

During a database disk cleanup operation on a production cluster, an engineering team ran a scheduled job to purge six months of legacy raw JSON audit logs from a high-throughput table. The query deleted over 40 million rows. Yet when infrastructure alarms sounded two hours later, the disk usage on the Postgres volume had not budged by a single megabyte. Storage remained pinned at 94 percent capacity.

When the team inspected table sizes using standard pg_relation_size() queries, the main table reported only 4 GB. However, a full relation audit with pg_total_relation_size() revealed that the table was consuming 820 GB. The stranded data resided entirely inside an auxiliary relation prefixed with pg_toast_. Understanding why this happens requires digging into the mechanics of the Postgres TOAST engine.

1. How TOAST Works Under the Hood

Postgres pages are fixed at 8 KB in size. Because rows cannot span across multiple data pages, Postgres enforces that a tuple must fit comfortably within a single page, usually aiming for a maximum tuple size of around 2 KB (one-fourth of a page, determined by TOAST_TUPLE_THRESHOLD).

When a variable-length column (such as TEXT, VARCHAR, BYTEA, or JSONB) exceeds this threshold, the storage manager activates TOAST (The Oversized-Attribute Storage Technique). The engine applies a two-stage strategy:

  1. Inline Compression (pglz or lz4): The engine first attempts to compress the value inline. If compression brings the row below the threshold, the compressed payload remains stored directly inside the main heap tuple.
  2. Out-of-Line Chunking: If compressed data still exceeds the target size, the value is broken into multiple 2 KB chunks and stored as separate physical rows inside an auxiliary TOAST table (e.g. pg_toast.pg_toast_16429). The main table tuple stores only an 18-byte pointer (the toast_pointer), containing the TOAST table OID, chunk count, logical size, and raw chunk identifiers.
Main Heap Table (users)              Auxiliary TOAST Table (pg_toast_16429)
+----+----------------------+        +------------+----------+--------------------+
| id | raw_payload_pointer  | =====> | chunk_id   | chunk_seq| chunk_data (2 KB)  |
+----+----------------------+        +------------+----------+--------------------+
| 1  | [OID 16429, ID 8810] |        | 8810       | 0        | 0xfa39...          |
+----+----------------------+        | 8810       | 1        | 0x9bc2...          |
                                     | 8810       | 2        | 0x110e...          |
                                     +------------+----------+--------------------+

2. The Source of the Bloat: Independent MVCC Cycles

Every TOAST table is physically a standalone Postgres table with its own heap pages and its own B-tree index on (chunk_id, chunk_seq). Because Postgres relies on Multi-Version Concurrency Control (MVCC), deleting a row in the main table does not remove the TOAST chunks from disk; it merely marks the main tuple and all associated TOAST chunk tuples as dead.

When standard autovacuum processes the TOAST table, it scans the dead chunk tuples and marks their page slots in the Free Space Map (FSM). However, autovacuum can only return physical disk space to the operating system if dead chunks happen to reside at the very end of the file (truncation). Because inserts and deletes interleave over time, dead pages are scattered uniformly throughout the TOAST relation file.

Even worse, updating an un-toasted column in the main table can create TOAST overhead if not handled carefully. While Postgres tries to avoid re-writing unchanged TOAST pointers during an UPDATE, any modification to the toasted column itself causes a full set of new chunk insertions before deleting the old ones, doubling disk consumption during bulk migrations.

3. Identifying Stranded TOAST Bloat

To inspect which relations have swollen TOAST tables, query the system catalogs to map main tables to their TOAST counterparts:

SELECT
    relname AS table_name,
    pg_size_pretty(pg_relation_size(c.oid)) AS heap_size,
    pg_size_pretty(pg_relation_size(c.reltoastrelid)) AS toast_size,
    pg_size_pretty(pg_total_relation_size(c.oid)) AS total_size
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE relkind = 'r'
  AND n.nspname = 'public'
  AND c.reltoastrelid != 0
ORDER BY pg_total_relation_size(c.oid) DESC
LIMIT 10;

4. Remediation Strategies

A. Non-Blocking Compaction with pg_repack

Running VACUUM FULL will reclaim all empty space from both the heap and the TOAST table, but it acquires an exclusive AccessExclusiveLock on the table, blocking all concurrent reads and writes for hours. In production environments, use pg_repack instead:

# Repack table and its TOAST table concurrently without exclusive table locks
pg_repack -h localhost -U postgres -d production_db -t audit_logs

pg_repack creates a temporary shadow table with the same schema, builds identical indexes, streams rows from the source table, applies incoming delta changes via a log table and trigger, and finally performs a momentary catalog swap.

B. Configure Column Storage Strategies

Postgres allows developers to fine-tune how individual columns behave when approaching the 2 KB limit using ALTER TABLE ... ALTER COLUMN ... SET STORAGE:

  • EXTENDED (default): Compresses first, moves out-of-line to TOAST if still large.
  • MAIN: Compresses first, but keeps data inline if possible; only moves to TOAST as a last resort. Ideal for columns between 1 KB and 3 KB where inline storage avoids extra pointer lookups.
  • EXTERNAL: Stores out-of-line without compression. Best for already-compressed payloads like images, gzip archives, or parquet files.
  • PLAIN: Disallows TOASTing and compression entirely. Throws an error if the row exceeds page limits.

C. Autovacuum Tuning for TOAST Tables

By default, autovacuum parameters for TOAST tables inherit from server defaults. Because TOAST tables accumulate dead tuples rapidly during large updates, lowering the vacuum scale factor on specific TOAST tables ensures earlier cleanup:

ALTER TABLE audit_logs SET (
    autovacuum_vacuum_scale_factor = 0.05,
    toast.autovacuum_vacuum_scale_factor = 0.02
);

Summary

Postgres TOAST enables rows to hold megabytes of unstructured data without violating 8 KB page constraints. But because TOAST tables are independent physical structures under MVCC, bulk deletes leave empty space stranded in the Free Space Map. Monitoring TOAST size with pg_total_relation_size(), tuning autovacuum thresholds, and employing pg_repack ensures disk space is safely recovered without production downtime.

SharePostLinkedIn

Reader Discussion

1 replies// weighed in

TopNewestAuthor
Add to the thread
Disagree, agree harder, or share your own experience…
Email instead →markdown okbe kind
  1. Isabella Costa· Junior EngineerKind words

    saved this. sharing at standup tomorrow — we've had exactly this problem for 2 sprints and nobody on the team had framed it this way 🙏

    Nov 29, 2026·2 days later

Worked on something similar? Email ducminhldm@gmail.com — I read every one. The good ones become future posts.

Comments seeded · live discussion via email