Sub topic 12
How out-of-line values are chunked and fetched
This chapter assumes you know the heap page and tuple layout from the earlier chapters, and that you have read the TOAST overview chapter. That chapter covered why TOAST exists and when a row becomes "too wide". Here we follow what happens after PostgreSQL decides to move a value out of line: where the bytes go, how they are split, and how a query gets them back.
The pointer left behind in the main row
When a value is moved out of line, the main heap tuple keeps a small stand-in called a TOAST pointer. It is 18 bytes long, whatever the size of the original value:
- A 1-byte header that marks the datum as external.
- A 1-byte tag that says "on-disk TOAST pointer".
- The raw (uncompressed) size of the value.
- The stored size, plus a code for the compression method used.
- The value ID, an OID that identifies this value in the TOAST table.
- The OID of the TOAST table that holds it.
The pointer does not hold the data. It holds enough information to find the data and to know how large it is before reading anything. That second property matters later.
You can see the effect on the main row with pageinspect. A row with an int and a 640 KB out-of-line text column has a lp_len of well under 100 bytes. The row is the 24-byte tuple header, the 4-byte integer and the 18-byte pointer.
The TOAST table
Each table with at least one TOAST-able column (text, bytea, jsonb, numeric, arrays and so on) gets a companion table in the pg_toast schema. It is named pg_toast.pg_toast_<oid of the main table>. It is an ordinary heap with its own pages, visibility information, free space map and VACUUM. Its structure is fixed:
| Column | Type | Meaning |
|---|---|---|
| `chunk_id` | `oid` | The value ID stored in the TOAST pointer |
| `chunk_seq` | `int4` | Position of this chunk within the value, starting at 0 |
| `chunk_data` | `bytea` | Up to one chunk's worth of bytes |
A unique index on (chunk_id, chunk_seq) is created with the table. Every fetch goes through this index.
With the default 8 KB page size, a chunk holds at most 1996 bytes. That limit is chosen so that exactly four chunk rows fill a page, after counting the page header, line pointers and tuple headers. The last chunk of a value is usually shorter. The chunk size is a compile-time constant. The per-table toast_tuple_target storage parameter changes when a row is considered too large, but it does not change the chunk size.
Seeing the chunks
The following script uses psql meta-commands (\gset and :toast_name). It stores a 640,000-byte value of hex text. The column is set to EXTERNAL first so that no compression happens and the chunk arithmetic is predictable.
CREATE TABLE docs2 (id int PRIMARY KEY, body text);
ALTER TABLE docs2 ALTER COLUMN body SET STORAGE EXTERNAL;
INSERT INTO docs2
SELECT 1, string_agg(md5(g::text), '')
FROM generate_series(1, 20000) AS g;
SELECT reltoastrelid::regclass AS toast_name
FROM pg_class
WHERE oid = 'docs2'::regclass
\gset
SELECT chunk_id,
count(*) AS chunks,
sum(length(chunk_data)) AS total_bytes,
max(length(chunk_data)) AS biggest_chunk
FROM :toast_name
GROUP BY chunk_id;The output is one row, because there is one out-of-line value. It shows about 321 chunks, a biggest_chunk of 1996, and a total_bytes of 639,996. The 4 bytes missing from 640,000 are the length header of the value, which is stored in the pointer and not in the chunks.
To look at individual chunks in order:
SELECT chunk_seq, length(chunk_data) AS bytes
FROM :toast_name
ORDER BY chunk_seq
LIMIT 3;Every chunk except the last is 1996 bytes.
How a value is fetched
A query that needs the whole value performs the following steps, called detoasting:
- Read the main heap tuple and find the TOAST pointer in the column.
- Open the TOAST table named in the pointer.
- Scan the TOAST index for
chunk_id = <value id>, inchunk_seqorder. - Copy each chunk's
chunk_datainto one buffer. The pointer's stored size lets PostgreSQL allocate the whole buffer up front and check that the chunk count and sizes match. - If the value was compressed, decompress the buffer to get the original bytes.
Detoasting is lazy. PostgreSQL only does it when some expression needs the actual bytes. Compare these queries on docs2:
EXPLAIN (ANALYZE, BUFFERS) SELECT id FROM docs2;
EXPLAIN (ANALYZE, BUFFERS) SELECT octet_length(body) FROM docs2;
EXPLAIN (ANALYZE, BUFFERS) SELECT length(body) FROM docs2;SELECT idnever touches the TOAST table. Wide columns that you do not select cost nothing beyond the larger main table scan.octet_length(body)is also answered from the pointer's size field, without reading any chunk.length(body)counts characters, so it must read all the chunks. Theshared hitandreadcounts in the plan jump by several hundred buffers.
This is why SELECT * on a table with large values is expensive even when the application ignores those columns. It also explains why a table can appear small by pg_relation_size and still be slow, because most of its bytes are in the TOAST relation.
Fetching only part of a value
For an uncompressed external value, PostgreSQL can read a slice. A call such as substr(body, 1, 100) computes which chunks cover that byte range and asks the TOAST index only for those chunk_seq values. Reading the first 100 bytes of the 640 KB value touches one chunk, not 321.
EXPLAIN (ANALYZE, BUFFERS) SELECT substr(body, 1, 100) FROM docs2;Slicing has some limits:
- It works for functions that know how to ask for a slice, such as
substrontextandbytea. Many other functions detoast the whole value. - Compressed values can only be sliced from the start. Decompression runs from the beginning of the stream, so PostgreSQL reads the chunks for the prefix and decompresses just that part. A slice from the middle of a compressed value needs everything before it.
- This is the main reason to choose
EXTERNALfor large values that you read by range, such as bigbyteablobs or long text where you often take a prefix. You save CPU and I/O at the cost of more disk space.
Updates and deletes
The chunks belong to a value ID, and the main row only holds the pointer. This decides what happens on write.
An UPDATE that does not change the large column copies the pointer into the new row version. The TOAST rows are not rewritten. Check this yourself:
SELECT DISTINCT chunk_id FROM :toast_name;
UPDATE docs2 SET id = 2 WHERE id = 1;
SELECT DISTINCT chunk_id FROM :toast_name;Both queries return the same chunk_id. Two row versions in the main heap now point at one set of chunks, so a wide row can be updated cheaply as long as the wide column is untouched.
An UPDATE that changes the large column creates a new value: new chunks, with a new chunk_id. The old chunks stay until the old row version is dead and vacuumed.
UPDATE docs2 SET body = body || 'x' WHERE id = 2;
SELECT chunk_id, count(*) FROM :toast_name GROUP BY chunk_id;You now see two chunk_id values. The old one belongs to the dead row version and the new one to the live row. The old chunks are marked dead by the same transaction rules as any other row and are reclaimed when VACUUM processes the TOAST table. Autovacuum treats the TOAST table as a separate relation with its own thresholds. A heavily updated table with large values can have a bloated TOAST table while the main table looks fine.
Value IDs come from a counter, so they are not unique across tables. Uniqueness is only needed inside one TOAST table. PostgreSQL checks the TOAST index to make sure a new ID is not already in use, so lookups are always unambiguous.
Checking sizes
Use the size functions to see where space goes:
SELECT pg_relation_size('docs2') AS main_heap,
pg_table_size('docs2') AS heap_plus_toast,
pg_total_relation_size('docs2') AS with_indexes;
SELECT pg_relation_size(reltoastrelid) AS toast_heap,
pg_relation_size(reltoastrelid::regclass::text::regclass) AS same_thing
FROM pg_class
WHERE oid = 'docs2'::regclass;pg_relation_size on the main table does not include TOAST, while pg_table_size does. A table with a large main_heap and a small TOAST relation has mostly inline data. The reverse means queries that touch the wide column pay for extra reads.
Common mistakes
- Assuming
pg_relation_sizeis the total size of a table. For tables with wide columns it can be a small fraction of the real size. - Selecting wide columns that are not needed, which forces detoasting.
- Expecting
SET STORAGEorSET COMPRESSIONto rewrite existing rows. They only affect values stored afterwards. Existing values keep their old form until the row is rewritten. - Using
length()to test whether a large text value is empty. Useoctet_length()or compare the column to an empty string only when you really need it, sincelength()reads every chunk. - Ignoring autovacuum on the TOAST table when the main table sees many updates to large columns.
Exercise
A table has columns (id int, payload text). Each payload is 50 KB of incompressible data stored out of line. You run UPDATE t SET id = id + 1000000 for every row. Do the TOAST chunks get rewritten? What would change if you updated payload instead, and which query on the TOAST table would show it?
Show answer
The chunks are not rewritten. Each new row version copies the 18-byte TOAST pointer, so it refers to the same chunkid, and the TOAST table stays the same size. If you updated payload, each row would get a new value and a new chunkid, with about 26 chunks of 1996 bytes (50 KB / 1996). The old chunks stay until the old row versions are vacuumed. SELECT chunkid, count(*) FROM pgtoast.pgtoast<oid> GROUP BY chunkid shows both the old and new IDs, so the count of distinct chunkid values grows.
Exercise
Why is SELECT octet_length(body) cheap on an out-of-line value while SELECT length(body) is expensive?
Show answer
The TOAST pointer in the main tuple records the raw size of the value, so octet_length can answer from the pointer without reading any chunks. length counts characters, which depends on the actual bytes (they may be multibyte), so PostgreSQL must fetch all the chunks through the TOAST index, decompress them if needed, and then count.