Sub topic 11
TOAST: handling values too large for a page
This chapter assumes you know that a table is stored as 8 KB pages and that each row is a tuple with a header (see the earlier chapters). It also assumes you can run queries in psql. Here you will see what happens when a value is too large for that layout, and how to observe and control it.
Why TOAST exists
A heap tuple must fit inside one page. It cannot span two pages. With the default 8 KB page, the usable space for a single tuple is a little under 8 KB after the page header and line pointer. A text value of 300,000 bytes obviously cannot fit.
PostgreSQL solves this with TOAST, short for The Oversized-Attribute Storage Technique. When a row grows too large, PostgreSQL shrinks it in two ways:
- Compression: the value is compressed and stored inside the row.
- Out-of-line storage: the value is cut into chunks and stored in a separate table, the TOAST table. The main row keeps only a small pointer to it.
Both steps are automatic and invisible to SQL. A single value can be up to 1 GB.
TOAST also keeps the main table compact. Pages of the main table hold more rows when the wide values live elsewhere. A scan that does not need those values reads fewer pages.
When TOAST applies
Two conditions must hold.
The column type must be TOAST-able. Variable-length types (called varlena types) can be TOASTed. These include text, varchar, bytea, jsonb, json, numeric, arrays, and xml. Fixed-width types such as integer, bigint, boolean, timestamp, and uuid never are.
The row must be larger than the threshold. TOAST is considered when the whole tuple exceeds TOAST_TUPLE_THRESHOLD. With 8 KB pages this is about 2 KB (2032 bytes). The check is on the total row, not on each column. A row with several 700-byte text columns is over the limit even though no single value is large.
Once triggered, PostgreSQL tries to bring the row down to the target size, which is also about 2 KB by default. It works through the columns roughly like this:
- Take the largest TOAST-able column whose strategy allows compression or out-of-line storage. Compress it. If the row is still too large, move it out of line.
- Repeat with the next largest column, until the row fits or no candidates remain.
- As a last resort, columns using the
mainstrategy (compress, but avoid out-of-line storage) may also be moved out of line.
Two details matter in practice:
- Values shorter than 32 bytes are never compressed.
- Compression is kept only if it saves at least 25%. Otherwise the value is stored as it was. Already-compressed data such as JPEG images or random strings usually stays uncompressed.
Observing TOAST
Every table with at least one TOAST-able column gets a TOAST table, created automatically. It lives in the pg_toast schema and is named pg_toast.pg_toast_<oid of the table>. The table's pg_class row points to it through reltoastrelid.
Create a table and three rows that behave differently:
CREATE TABLE toast_demo (id int PRIMARY KEY, label text, payload text);
INSERT INTO toast_demo VALUES
(1, 'small', 'hello'),
(2, 'compressible', repeat('abc', 100000)),
(3, 'incompressible',
(SELECT string_agg(md5(g::text), '') FROM generate_series(1, 10000) g));Compare the logical size of each value with the bytes actually stored:
SELECT id,
octet_length(payload) AS raw_bytes,
pg_column_size(payload) AS stored_bytes
FROM toast_demo
ORDER BY id;- Row 1 (5 bytes) is stored as is, plus a 1-byte header.
- Row 2 has 300,000 raw bytes. Its stored size is a few KB at most, because the repeated pattern compresses extremely well.
- Row 3 has 320,000 raw bytes. A string of random hex digits has no repeats for the compressor to find, so the stored size stays close to the raw size.
pg_column_size reports the size of the value as stored, so it shows the effect of compression. octet_length reports the uncompressed length.
Next, find the TOAST table and see where the bytes live:
SELECT c.reltoastrelid::regclass AS toast_table,
pg_relation_size(c.oid) AS heap_bytes,
pg_relation_size(c.reltoastrelid) AS toast_bytes
FROM pg_class c
WHERE c.oid = 'toast_demo'::regclass;heap_bytes is small, probably a single 8 KB page, even though the table holds hundreds of kilobytes of data. Nearly all of it is in the TOAST table. Row 3, being incompressible and large, accounts for most of it.
You can also query the TOAST table directly (as a superuser, or a role with sufficient privileges). Its columns are chunk_id, chunk_seq, and chunk_data. The next chapter covers how those chunks are built and read.
What the main row stores
For a value moved out of line, the main tuple contains a small TOAST pointer of about 18 bytes. The pointer records the TOAST table's identity, a value ID, the raw size, the stored size, and the compression method. The row's own size stays small no matter how large the value is.
This has three consequences you can rely on:
- Unused wide columns cost almost nothing to read.
SELECT id, label FROM toast_demonever touches the TOAST table. PostgreSQL fetches and decompresses a value only when the query needs it (a step called detoasting). SELECT *can be expensive. It forces detoasting of every wide column of every returned row. This is a common reason a query on a "small" table is slow.- Updates that skip the wide column are cheap. An
UPDATEthat does not changepayloadcreates a new row version in the main heap, but the new version reuses the existing TOAST pointer. The large value is not copied. Only when the wide column itself changes are new chunks written, and the old ones become dead rows in the TOAST table, to be reclaimed by VACUUM like any other dead tuples.
Tuning the threshold
The 2 KB target can be changed per table with the toast_tuple_target storage parameter (PostgreSQL 11 and later). It accepts values between 128 and 8160 bytes.
-- Move values out of line sooner, keeping the main rows narrower
ALTER TABLE toast_demo SET (toast_tuple_target = 256);Lowering it makes the main table narrower and speeds up scans that ignore the wide columns, at the price of more TOAST lookups when you do read them. Raising it keeps medium-sized values inline, which is better if you nearly always read them. Like most storage settings, it applies only to rows written after the change. Existing rows are not rewritten.
Edge cases and limits
- Rows made of non-TOAST-able columns can still be too big. If you have many fixed-width columns that together exceed the page, PostgreSQL has nothing to compress or move and fails with an error such as
row is too big. - Indexes do not use out-of-line storage. A B-tree index entry may be compressed, but it cannot be moved to a TOAST table. An entry larger than about one third of a page (roughly 2.7 KB) is rejected with an error. Indexing a long
textcolumn directly can therefore fail on long values. Indexing a hash of the value is a common workaround. - Compression costs CPU. Writes of large compressible values spend time compressing. Reads spend time decompressing. For data that will not compress, such as images, this is wasted work, and a different storage strategy avoids it (covered in a later chapter).
- TOASTed data is vacuumed with its table. Autovacuum processes the TOAST table as part of the parent. A table with large, frequently changed values can accumulate bloat in its TOAST table even when the main heap looks healthy.
jsonband arrays follow the same rules. The wholejsonbvalue is one datum. Reading a single key from a large TOASTed document still means detoasting the entire document, so very large documents that you query by key are costly.
Summary of the model
| Situation | What happens |
|---|---|
| Row is under about 2 KB | Stored inline, untouched |
| Row is over about 2 KB, value compresses well | Compressed, stored inline if it then fits |
| Row is over about 2 KB, value does not compress | Stored out of line, uncompressed, in the TOAST table |
| Column is fixed-width (`int`, `uuid`) | Never TOASTed |
| Query does not reference the wide column | TOAST table is not read |
| `UPDATE` leaves the wide column unchanged | Old TOAST pointer is reused |
Exercise
A table has columns (id int, a text, b text, c text). Each of a, b, and c holds a 900-byte string of random characters, so none of them compresses. Does a row get TOASTed even though no single value is large? Which column is moved out of line first, and why would a query that selects only id be fast?
Show answer
Yes. The threshold applies to the whole row, which is about 2.7 KB here, over the roughly 2 KB limit. PostgreSQL works from the largest TOAST-able column down, so it moves one of the three values out of line (they are the same size, so any of them can be first) and rechecks. It stops when the row fits, which may take one or two of the columns. A query selecting only id does not need those values, so PostgreSQL reads just the main heap rows and never touches the TOAST table.
Exercise
You run ALTER TABLE toastdemo SET (toasttupletarget = 256) and then check pgcolumn_size and the TOAST table for rows inserted before the change. Do you see any difference, and what must you do to apply the new setting to old rows?
Show answer
No difference. The storage parameter affects only rows written after the change, and existing rows keep their old layout. To apply it to old rows, rewrite them, for example by updating the rows so they are written again, or by rewriting the table with a command such as VACUUM FULL or CLUSTER, while keeping in mind that these take locks and require extra disk space.