TOAST — Where Postgres Hides Your Big Columns
Where Postgres Hides Your Big Columns
Databasesdatabases / storage & performance
The mental model
Every Postgres row must fit in one 8KB page. So picture a row as a small locker. Anything too bulky doesn't go in the locker — it goes to a warehouse out back, and the locker keeps a claim ticket (18 bytes) instead.
That warehouse is a hidden side table: pg_toast.pg_toast_<oid>. Oversized values get compressed, sliced into ~2KB chunks, and stored there with their own index.
When it triggers
Postgres aims to keep each row under ~2KB (TOAST_TUPLE_TARGET). If it's over, it takes the widest varlena column (text, jsonb, bytea, varchar), compresses it, moves it out of line, and repeats until the row fits. The threshold is per-row, not per-column.
See the split:
SELECT pg_size_pretty(pg_relation_size('events')) AS heap,
pg_size_pretty(pg_total_relation_size('events')
- pg_relation_size('events')) AS toast_plus_idx;
Why the analogy is good news
A ~400-byte tuple + ticket means many more rows per page. Your "WHERE status='open' ORDER BY created_at" scan reads far fewer pages than the raw data size suggests. TOAST is a feature, not a tax.
Where the analogy breaks — the intermediate part
- Holding the ticket is free; redeeming it isn't.
SELECT id, status FROM events never touches TOAST. SELECT * does a chunk-index lookup + decompress per row. Identical plan shape, 10x the wall time. That — not bandwidth — is the real cost of SELECT * on wide tables.
- There is no partial update.
Change one key in a 60KB jsonb and Postgres rewrites every chunk, and WALs all of it. A "tiny" UPDATE becomes ~60KB+ of WAL → replication lag you can't explain from reading the SQL.
- Compression is sometimes pure waste.
lz4/pglz won't shrink already-compressed bytes (JPEGs, gzipped blobs) — you pay the CPU to learn that. For those columns:
ALTER TABLE t ALTER COLUMN blob SET STORAGE EXTERNAL;
Out-of-line, no compression attempt.
- It hides from your capacity math.
2M rows x 50KB jsonb = ~100GB that pg_relation_size() does not report. The toast table is its own relation, with its own bloat and its own autovacuum schedule.
One number to keep
18 bytes — the pointer left behind in the row. A 50KB value and a 500KB value cost the heap exactly the same.
Your exercise
On your widest table:
EXPLAIN (ANALYZE, BUFFERS) SELECT id FROM t LIMIT 1000;
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM t LIMIT 1000;
Compare execution time and the shared hit/read lines. If the second is several times slower while buffer counts stay similar, you just measured detoasting.
Then answer two things: which column caused it, and does any query in your codebase actually need that column in a list view?