man postgres-internals/toast
lesson 3 of 30 · Storage
TOAST: values too big for a page
A heap tuple has to fit in an 8 KB page, and a text value can be up to
1 GB. The last lesson stopped at values of a few hundred bytes. This one
follows longer ones: when PostgreSQL starts to shrink a row, how it
compresses a value in place, how it moves one out to a second table in
pieces, and what is left in the row when it does. PostgreSQL calls all of
this TOAST, The Oversized-Attribute Storage Technique. At the end tinypg
does the same, compressor included, and writes the same bytes as the
server.
Every psql and shell output below comes from one run of
tools/record_toast.py in the tinypg repository (tag lesson-03) against
PostgreSQL 19.0 on 64-bit ARM macOS, pasted as the script recorded it. The
byte-by-byte readings in the text are decoded by hand from those outputs.
The script copies every page with get_raw_page before anything reads the
tables, so no hint bits have been set yet.
The threshold: 2032 bytes
The toaster does not wait for a tuple to overflow its page. The limit is a
quarter of a page, computed in heaptoast.h:
#define MaximumBytesPerTuple(tuplesPerPage) \
MAXALIGN_DOWN((BLCKSZ - \
MAXALIGN(SizeOfPageHeaderData + (tuplesPerPage) * sizeof(ItemIdData))) \
/ (tuplesPerPage))
src/include/access/heaptoast.h, lines 23–26
#define TOAST_TUPLES_PER_PAGE 4
#define TOAST_TUPLE_THRESHOLD MaximumBytesPerTuple(TOAST_TUPLES_PER_PAGE)
#define TOAST_TUPLE_TARGET TOAST_TUPLE_THRESHOLD
src/include/access/heaptoast.h, lines 46–50
With four tuples a page: 8192 − MAXALIGN(24 + 4 × 4) = 8152, a quarter of
that is 2038, rounded down to a multiple of 8: 2032. heap_insert() checks a
new tuple’s length against it before looking for a page:
else if (HeapTupleHasExternal(tup) || tup->t_len > TOAST_TUPLE_THRESHOLD)
return heap_toast_insert_or_update(relation, tup, NULL, options);
src/backend/access/heap/heapam.c, lines 2268–2269
The test is “longer than”, so a tuple of exactly 2032 bytes is stored as it
is. The recording script makes a table of (id int, body text) and inserts
eight rows:
INSERT INTO docs VALUES (1, 'a short note') RETURNING xmin;
xmin
------
1498
(1 row)
INSERT 0 1
INSERT INTO docs VALUES (2, repeat('pglz compresses repeats. ', 200)) RETURNING xmin;
xmin
------
1499
(1 row)
INSERT 0 1
INSERT INTO docs VALUES (3, (SELECT string_agg(encode(sha256(i::text::bytea), 'base64'), '' ORDER BY i) FROM generate_series(1, 91) AS i)) RETURNING xmin;
xmin
------
1500
(1 row)
INSERT 0 1
INSERT INTO docs VALUES (4, (SELECT string_agg((ARRAY['the', 'page', 'tuple', 'header', 'varlena', 'chunk', 'toast', 'pointer', 'compress', 'value', 'table', 'index', 'heap', 'line', 'offset', 'block', 'free', 'space', 'map', 'log'])[1 + (i * i * 31 + i * 7) % 20], ' ' ORDER BY i) FROM generate_series(1, 2000) AS i)) RETURNING xmin;
xmin
------
1501
(1 row)
INSERT 0 1
INSERT INTO docs VALUES (5, repeat('naïve café ', 300)) RETURNING xmin;
xmin
------
1502
(1 row)
INSERT 0 1
INSERT INTO docs VALUES (6, repeat('x', 2000)) RETURNING xmin;
xmin
------
1503
(1 row)
INSERT 0 1
INSERT INTO docs VALUES (7, repeat('x', 2001)) RETURNING xmin;
xmin
------
1504
(1 row)
INSERT 0 1
INSERT INTO docs VALUES (8, repeat('abc', 100000)) RETURNING xmin;
xmin
------
1505
(1 row)
INSERT 0 1
Rows 6 and 7 are 2000 and 2001 xs. Row 6 is 24 bytes of header, 4 for
id and 2004 for the text with its 4-byte header: 2032, and its lp_len
below is 2032. One more x and the tuple would be 2033 bytes; row 7 is
stored in 63.
A TOAST relation, made in advance
Moving a value out of line needs somewhere to put it, so CREATE TABLE
makes that place at once:
CREATE TABLE docs (id int, body text COMPRESSION pglz) WITH (autovacuum_enabled = off, toast.autovacuum_enabled = off);
CREATE TABLE
SELECT reltoastrelid::regclass FROM pg_class WHERE relname = 'docs';
reltoastrelid
-------------------------
pg_toast.pg_toast_36358
(1 row)
SELECT attname, typname, attstorage FROM pg_attribute
JOIN pg_type ON pg_type.oid = atttypid
WHERE attrelid = 'pg_toast.pg_toast_36358'::regclass AND attnum > 0 ORDER BY attnum;
attname | typname | attstorage
------------+---------+------------
chunk_id | oid | p
chunk_seq | int4 | p
chunk_data | bytea | p
(3 rows)
SELECT indexrelid::regclass, indkey FROM pg_index
WHERE indrelid = 'pg_toast.pg_toast_36358'::regclass;
indexrelid | indkey
-------------------------------+--------
pg_toast.pg_toast_36358_index | 1 2
(1 row)
pg_toast.pg_toast_36358 is an ordinary heap, named after the table’s OID,
with three columns: the value it belongs to (chunk_id), the piece’s number
(chunk_seq) and the bytes (chunk_data). An index on the first two finds
a value’s pieces in order. A table gets one only if one of its rows could
pass the threshold, which a column of unlimited length always can:
if (!has_toastable_attrs)
return false; /* nothing to toast? */
if (maxlength_unknown)
return true; /* any unlimited-length attrs? */
tuple_length = MAXALIGN(SizeofHeapTupleHeader +
BITMAPLEN(tupdesc->natts)) +
MAXALIGN(data_length);
return (tuple_length > TOAST_TUPLE_THRESHOLD);
src/backend/access/heap/heapam_handler.c, lines 2038–2045
All three columns are PLAIN, so the toaster never touches a TOAST
relation’s own rows:
/*
* Ensure that the toast table doesn't itself get toasted, or we'll be
* toast :-(. This is essential for chunk_data because type bytea is
* toastable; hit the other two just to be sure.
*/
TupleDescAttr(tupdesc, 0)->attstorage = TYPSTORAGE_PLAIN;
TupleDescAttr(tupdesc, 1)->attstorage = TYPSTORAGE_PLAIN;
TupleDescAttr(tupdesc, 2)->attstorage = TYPSTORAGE_PLAIN;
src/backend/catalog/toasting.c, lines 219–226
Compressed in place
Here is the start of each of the eight tuples, id first:
SELECT lp, lp_len, t_infomask, substr(t_data, 1, 26) AS first_26_bytes
FROM heap_page_items(get_raw_page('docs', 0));
lp | lp_len | t_infomask | first_26_bytes
----+--------+------------+--------------------------------------------------------
1 | 41 | 2050 | \x010000001b612073686f7274206e6f7465
2 | 124 | 2050 | \x0200000082010000881300000070676c7a20636f6d0070726573
3 | 46 | 2054 | \x030000000112a80f0000a40f00000b8e0000098e0000
4 | 246 | 2050 | \x040000006a030000a72f0000106d617020010474686500207661
5 | 98 | 2050 | \x050000001a0100003c0f0000006e61c3af76652063e06166c3a9
6 | 2032 | 2050 | \x06000000501f0000787878787878787878787878787878787878
7 | 63 | 2050 | \x070000008e000000d1070000fe780f01ff0f01ff0f01ff0f01ff
8 | 46 | 2054 | \x080000000112e4930400720d00000c8e0000098e0000
(8 rows)
SELECT t_data FROM heap_page_items(get_raw_page('docs', 0)) WHERE lp = 7;
t_data
----------------------------------------------------------------------------------
\x070000008e000000d1070000fe780f01ff0f01ff0f01ff0f01ff0f01ff0f01ff0f01ff010f0147
(1 row)
Row 1 is short and has a 1-byte header, 1b = (13 « 1) | 1, as in the last
lesson. Row 2, the sentence pglz compresses repeats. 200 times, is 5000
bytes, yet its whole tuple is 124. After id (02000000) comes a 4-byte header 82010000:
0x182, whose low two bits are 10, the compressed form from the last
lesson’s table of varlena headers. 0x182 » 2 = 96 bytes in all. The next
four bytes are new:
struct /* Compressed-in-line format */
{
uint32 va_header;
uint32 va_tcinfo; /* Original data size (excludes header) and
* compression method; see va_extinfo */
char va_data[FLEXIBLE_ARRAY_MEMBER]; /* Compressed data */
} va_compressed;
src/include/varatt.h, lines 134–140
va_tcinfo is 88130000, 0x1388 = 5000, the size before compression, and
its top two bits hold the method: 0, pglz. Then the compressed bytes.
pglz is PostgreSQL’s own LZ77-style compressor, in
src/common/pg_lzcompress.c. Its output is a control byte, then up to eight
items, then another control byte, and so on. A 0 bit in the control byte
means a literal byte follows; a 1 bit means a tag, which copies earlier
output:
* An unset bit in the control byte means, that one uncompressed
* byte follows, which is copied from input to output.
*
* A set bit in the control byte means, that a tag of 2-3 bytes
* follows. A tag contains information to copy some bytes, that
* are already in the output buffer, to the current location in
* the output. Let's call the three tag bytes T1, T2 and T3. The
* position of the data to copy is coded as an offset from the
* actual output position.
*
* The offset is in the upper nibble of T1 and in T2.
* The length is in the lower nibble of T1.
*
* So the 16 bits of a 2 byte tag are coded as
*
* 7---T1--0 7---T2--0
* OOOO LLLL OOOO OOOO
*
* This limits the offset to 1-4095 (12 bits) and the length
* to 3-18 (4 bits) because 3 is always added to it. To emit
* a tag of 2 bytes with a length of 2 only saves one control
* bit. But we lose one byte in the possible length of a tag.
*
* In the actual implementation, the 2 byte tag's length is
* limited to 3-17, because the value 0xF in the length nibble
* has special meaning. It means, that the next following
* byte (T3) has to be added to the length value of 18. That
* makes total limits of 1-4095 for offset and 3-273 for length.
src/common/pg_lzcompress.c, lines 70–97
Row 2 starts with two literal runs: control byte 00, the eight bytes
pglz com, control byte 00, pres.... Row 7 shows tags; the second query above prints its
whole tuple. After id,
8e000000 is the header (35 bytes), d1070000 the original 2001 bytes.
Control byte fe is 11111110: one literal, 78 (x), then seven tags. Each
tag is 0f 01 ff: length nibble F, so the length is 18 plus the third byte,
255, which makes 273; offset 1, one byte back. A copy that overlaps itself is
how one x becomes 273 of them. Then control byte 01 and one more tag,
0f 01 47: 18 + 71 = 89 bytes. 1 + 7 × 273 + 89 = 2001.
Matches are found through a hash of the next four input bytes, which leads to a chain of earlier positions with the same hash, less than 4 KB back. pglz follows the chain for the longest match, stopping early once a match is long enough. Its defaults:
static const PGLZ_Strategy strategy_default_data = {
32, /* Data chunks less than 32 bytes are not
* compressed */
INT_MAX, /* No upper limit on what we'll try to
* compress */
25, /* Require 25% compression rate, or not worth
* it */
1024, /* Give up if no compression in the first 1KB */
128, /* Stop history lookup if a match of 128 bytes
* is found */
10 /* Lower good match size by 10% at every loop
* iteration */
};
src/common/pg_lzcompress.c, lines 223–235
toast_compress_datum() then asks for a little more:
/*
* We recheck the actual size even if compression reports success, because
* it might be satisfied with having saved as little as one byte in the
* compressed data --- which could turn into a net loss once you consider
* header and alignment padding. Worst case, the compressed format might
* require three padding bytes (plus header, which is included in
* VARSIZE(tmp)), whereas the uncompressed format would take only one
* header byte and no padding if the value is short enough. So we insist
* on a savings of more than 2 bytes to ensure we have a gain.
*/
if (VARSIZE(tmp) < valsize - 2)
{
/* successful compression */
Assert(cmid != TOAST_INVALID_COMPRESSION_ID);
TOAST_COMPRESS_SET_SIZE_AND_COMPRESS_METHOD(tmp, valsize, cmid);
return PointerGetDatum(tmp);
}
src/backend/access/common/toast_internals.c, lines 82–98
The sizes PostgreSQL reports agree with the bytes. pg_column_size() gives
the bytes a value takes where it is stored (inline with its header, or in
the TOAST relation), and pg_column_compression() the method, if any:
SELECT id, length(body), pg_column_size(body), pg_column_compression(body)
FROM docs ORDER BY id;
id | length | pg_column_size | pg_column_compression
----+--------+----------------+-----------------------
1 | 12 | 13 |
2 | 5000 | 96 | pglz
3 | 4004 | 4004 |
4 | 12199 | 218 | pglz
5 | 3300 | 70 | pglz
6 | 2000 | 2004 |
7 | 2001 | 35 | pglz
8 | 300000 | 3442 | pglz
(8 rows)
SELECT id, length(body), pg_column_size(body), pg_column_compression(body)
FROM docs_lz4 ORDER BY id;
id | length | pg_column_size | pg_column_compression
----+--------+----------------+-----------------------
2 | 5000 | 63 | lz4
3 | 4004 | 4004 |
8 | 300000 | 1197 | lz4
(3 rows)
SELECT pg_relation_size('docs') AS docs, pg_relation_size('pg_toast.pg_toast_36358') AS toast;
docs | toast
------+-------
8192 | 8192
(1 row)
Row 3 did not compress. It is the base64 of 91 SHA-256 hashes, 4004 characters with few repeats, and pglz returns nothing for it. The server does not report which of pglz’s rules fired. tinypg’s line-by-line copy of pglz, run on the same bytes, finds no match at all in the first 910 input bytes and gives up when its output reaches 1024 bytes: the “first 1KB” rule, before the 25% rule comes into play. With both give-up rules switched off it writes 4505 bytes, more than the 4004 it was given.
You can run that query yourself. The box below runs in your browser, in
PGlite (PostgreSQL 19.0 compiled to WebAssembly), on the same docs table:
SELECT id, length(body), pg_column_size(body), pg_column_compression(body)
FROM docs ORDER BY id;id | length | pg_column_size | pg_column_compression ----+--------+----------------+----------------------- 1 | 12 | 13 | 2 | 5000 | 96 | pglz 3 | 4004 | 4004 | 4 | 12199 | 218 | pglz 5 | 3300 | 70 | pglz 6 | 2000 | 2004 | 7 | 2001 | 35 | pglz 8 | 300000 | 3442 | pglz (8 rows)
Out of line: a pointer and chunks
Rows 3 and 8 are 46 bytes each: 24 of header, 4 of id, and 18 bytes that
start 01 12. A first byte of 01 is the fourth varlena form, a TOAST
pointer, and the byte after it is a tag saying which kind:
typedef enum vartag_external
{
VARTAG_INDIRECT = 1,
VARTAG_EXPANDED_RO = 2,
VARTAG_EXPANDED_RW = 3,
VARTAG_ONDISK = 18
} vartag_external;
src/include/varatt.h, lines 85–91
VARTAG_ONDISK, 18 (0x12), means the value is in a TOAST relation, and 16
more bytes say where:
typedef struct varatt_external
{
int32 va_rawsize; /* Original data size (includes header) */
uint32 va_extinfo; /* External saved size (without header) and
* compression method */
Oid va_valueid; /* Unique ID of value within TOAST table */
Oid va_toastrelid; /* RelID of TOAST table containing it */
} varatt_external;
src/include/varatt.h, lines 32–39
None of it is aligned: the pointer starts wherever the previous column
ended, and its fields sit at any offset (va_rawsize at byte 6 of the
data). Row 3’s pointer reads:
| bytes | field | value |
|---|---|---|
01 12 | header, tag | TOAST pointer, VARTAG_ONDISK |
a80f0000 | va_rawsize | 4008: 4004 bytes plus a 4-byte header |
a40f0000 | va_extinfo | 4004 bytes stored, method bits 0 |
0b8e0000 | va_valueid | 36363, the chunk_id |
098e0000 | va_toastrelid | 36361, the TOAST relation |
The tuple’s t_infomask is 2054 where its neighbours have 2050: the extra
bit is 0x0004, HEAP_HASEXTERNAL. The TOAST relation holds the chunks:
SELECT b AS blk, lp, lp_len, t_xmin, substr(t_data, 1, 12) AS id_seq_header
FROM generate_series(0, pg_relation_size('pg_toast.pg_toast_36358') / 8192 - 1) AS b,
heap_page_items(get_raw_page('pg_toast.pg_toast_36358', b));
blk | lp | lp_len | t_xmin | id_seq_header
-----+----+--------+--------+----------------------------
0 | 1 | 2032 | 1500 | \x0b8e000000000000401f0000
0 | 2 | 2032 | 1500 | \x0b8e000001000000401f0000
0 | 3 | 48 | 1500 | \x0b8e00000200000040000000
0 | 4 | 2032 | 1505 | \x0c8e000000000000401f0000
0 | 5 | 1482 | 1505 | \x0c8e000001000000a8160000
(5 rows)
Value 36363 is three chunks. Chunks 0 and 1 have lp_len 2032: 24 of
header, 4 of chunk_id, 4 of chunk_seq and 2000 of chunk_data, whose
header 401f0000 is 2000 « 2. Chunk 2 holds the last 12 bytes (1996 + 1996
- 12 = 4004), and its header is
40000000, 16 « 2: four bytes, where a user table would have used one. This is the case the last lesson promised. The TOAST relation’s columns arePLAIN, andtoast_save_datum()forms its rows with the TOAST relation’s own descriptor, sofill_val()does not pack them. Each chunk carries the xmin of the INSERT that wrote it, 1500, the same as row 3’s. The chunk size is a quarter page again, less a chunk row’s own overhead:
#define EXTERN_TUPLES_PER_PAGE 4 /* tweak only this */
#define EXTERN_TUPLE_MAX_SIZE MaximumBytesPerTuple(EXTERN_TUPLES_PER_PAGE)
#define TOAST_MAX_CHUNK_SIZE \
(EXTERN_TUPLE_MAX_SIZE - \
MAXALIGN(SizeofHeapTupleHeader) - \
sizeof(Oid) - \
sizeof(int32) - \
VARHDRSZ)
src/include/access/heaptoast.h, lines 80–89
toast_save_datum() cuts the value up and inserts one row per chunk, each
followed by its index entry:
chunk_size = Min(TOAST_MAX_CHUNK_SIZE, data_todo);
/*
* Build a tuple and store it
*/
t_values[0] = ObjectIdGetDatum(toast_pointer.va_valueid);
t_values[1] = Int32GetDatum(chunk_seq++);
SET_VARSIZE(&chunk_data, chunk_size + VARHDRSZ);
memcpy(VARDATA(&chunk_data), data_p, chunk_size);
t_values[2] = PointerGetDatum(&chunk_data);
toasttup = heap_form_tuple(toasttupDesc, t_values, t_isnull);
heap_insert(toastrel, toasttup, mycid, options, NULL);
src/backend/access/common/toast_internals.c, lines 304–317
Row 8, abc 100,000 times, went through both steps. Its pointer says
va_rawsize 300004 and va_extinfo 3442: the chunks (1996 and 1446 bytes)
hold the pglz output, whose first four bytes are va_tcinfo. A reader tells
a compressed external value from a plain one by comparing the two sizes,
since PostgreSQL never keeps a compressed copy that is not smaller:
/*
* Testing whether an externally-stored value is compressed now requires
* comparing size stored in va_extinfo (the actual length of the external data)
* to rawsize (the original uncompressed datum's size). The latter includes
* VARHDRSZ overhead, the former doesn't. We never use compression unless it
* actually saves space, so we expect either equality or less-than.
*/
static inline bool
VARATT_EXTERNAL_IS_COMPRESSED(varatt_external toast_pointer)
{
return VARATT_EXTERNAL_GET_EXTSIZE(toast_pointer) <
(Size) (toast_pointer.va_rawsize - VARHDRSZ);
}
src/include/varatt.h, lines 529–541
The order: compress first, then move out
Why was row 8 compressed and then moved, and row 3 moved without being
compressed? heap_toast_insert_or_update() works in rounds, and in each one
it takes the biggest value that qualifies. The target for the tuple’s data
is 2032 less the header, 2008 bytes here. The first round:
/*
* Look for attributes with attstorage EXTENDED to compress. Also find
* large attributes with attstorage EXTENDED or EXTERNAL, and store them
* external.
*/
while (heap_compute_data_size_ext(tupleDesc,
toast_values, toast_isnull,
true) > maxDataLen)
{
int biggest_attno;
biggest_attno = toast_tuple_find_biggest_attribute(&ttc, true, false);
if (biggest_attno < 0)
break;
/*
* Attempt to compress it inline, if it has attstorage EXTENDED
*/
if (TupleDescAttr(tupleDesc, biggest_attno)->attstorage == TYPSTORAGE_EXTENDED)
toast_tuple_try_compression(&ttc, biggest_attno);
else
{
/*
* has attstorage EXTERNAL, ignore on subsequent compression
* passes
*/
toast_attr[biggest_attno].tai_colflags |= TOASTCOL_INCOMPRESSIBLE;
}
/*
* If this value is by itself more than maxDataLen (after compression
* if any), push it out to the toast table immediately, if possible.
* This avoids uselessly compressing other fields in the common case
* where we have one long field and several short ones.
*
* XXX maybe the threshold should be less than maxDataLen?
*/
if (toast_attr[biggest_attno].tai_size > maxDataLen &&
rel->rd_rel->reltoastrelid != InvalidOid)
toast_tuple_externalize(&ttc, biggest_attno, options);
}
src/backend/access/heap/heaptoast.c, lines 179–219
Row 8 compressed to 3446 bytes, still more than 2008 on its own, so it went out at once. Row 3 could not be compressed and was too big alone, so it went out too. Row 7 compressed to 35 bytes, the loop condition was false, and nothing else happened.
When no single value is big enough to leave at once, the later rounds
decide. Round 2 moves values out of line, biggest first, until the tuple
fits. Round 3 compresses STORAGE MAIN values. Round 4 moves MAIN values
out of line too, but against a target of a whole page (8160 bytes), since
MAIN asks to stay inline if at all possible. The recording has one row
where round 2 decides: two incompressible values of 1540 bytes each.
CREATE TABLE pair (a text COMPRESSION pglz, b text COMPRESSION pglz) WITH (autovacuum_enabled = off, toast.autovacuum_enabled = off);
CREATE TABLE
INSERT INTO pair VALUES ((SELECT string_agg(encode(sha256(i::text::bytea), 'base64'), '' ORDER BY i) FROM generate_series(1, 35) AS i), (SELECT string_agg(encode(sha256(i::text::bytea), 'base64'), '' ORDER BY i) FROM generate_series(36, 70) AS i)) RETURNING xmin;
xmin
------
1507
(1 row)
INSERT 0 1
SELECT lp_len, t_infomask, substr(t_data, 1, 26) AS first_26_bytes
FROM heap_page_items(get_raw_page('pair', 0));
lp_len | t_infomask | first_26_bytes
--------+------------+--------------------------------------------------------
1588 | 2054 | \x01120806000004060000128e0000108e00000000201800006471
(1 row)
SELECT b AS blk, lp, lp_len, t_xmin, substr(t_data, 1, 12) AS id_seq_header
FROM generate_series(0, pg_relation_size('pg_toast.pg_toast_36365') / 8192 - 1) AS b,
heap_page_items(get_raw_page('pg_toast.pg_toast_36365', b));
blk | lp | lp_len | t_xmin | id_seq_header
-----+----+--------+--------+----------------------------
0 | 1 | 1576 | 1507 | \x128e00000000000020180000
(1 row)
Round 1 tries to compress a, then b; neither shrinks and neither is
bigger than 2008, so both stay. Round 2 moves the biggest, and with two of
the same size the first one wins: a became a pointer (va_rawsize 1544,
va_extinfo 1540) and b stayed inline, after two bytes of padding that
align its 4-byte header: 24 + 18 + 2 + 1544 = 1588. The tuple fits, and the
toaster stops.
The default is LZ4
The tables so far ask for COMPRESSION pglz. Without it, the column uses
default_toast_compression:
#ifdef USE_LZ4
#define DEFAULT_TOAST_COMPRESSION TOAST_LZ4_COMPRESSION
#else
#define DEFAULT_TOAST_COMPRESSION TOAST_PGLZ_COMPRESSION
#endif
src/include/access/toast_compression.h, lines 59–63
This server was built with LZ4, so the default is lz4. The same values in
a table with no COMPRESSION clause:
SHOW default_toast_compression;
default_toast_compression
---------------------------
lz4
(1 row)
CREATE TABLE docs_lz4 (id int, body text) WITH (autovacuum_enabled = off, toast.autovacuum_enabled = off);
CREATE TABLE
INSERT INTO docs_lz4 VALUES (2, repeat('pglz compresses repeats. ', 200)) RETURNING xmin;
xmin
------
1509
(1 row)
INSERT 0 1
INSERT INTO docs_lz4 VALUES (3, (SELECT string_agg(encode(sha256(i::text::bytea), 'base64'), '' ORDER BY i) FROM generate_series(1, 91) AS i)) RETURNING xmin;
xmin
------
1510
(1 row)
INSERT 0 1
INSERT INTO docs_lz4 VALUES (8, repeat('abc', 100000)) RETURNING xmin;
xmin
------
1511
(1 row)
INSERT 0 1
SELECT lp, lp_len, substr(t_data, 1, 26) AS first_26_bytes
FROM heap_page_items(get_raw_page('docs_lz4', 0));
lp | lp_len | first_26_bytes
----+--------+--------------------------------------------------------
1 | 91 | \x02000000fe00000088130040ff0a70676c7a20636f6d70726573
2 | 46 | \x030000000112a80f0000a40f0000188e0000168e0000
3 | 1225 | \x08000000b6120000e09304403f6162630300ffffffffffffffff
(3 rows)
Row 2’s va_tcinfo is now 88130040: 5000 again, with the top two bits
01, LZ4. The interesting row is the 300,000-byte one: LZ4 keeps it inline
in 1197 bytes, where pglz needed 3442 and had to move it out. That is a
property of pglz’s format rather than of this data: a tag covers at most 273
bytes and costs 3 bytes plus a control bit. Row 8 is three literals (abc)
and 1099 tags of up to 273 bytes, 3 + 3297 bytes, plus 138 control bytes,
one per eight items: 3438, and with va_tcinfo the 3442 in the pointer.
(That count is my arithmetic from the format above; the total matches the
recorded size.) No input of 300,000 bytes can come out much smaller. An LZ4
match length grows by one byte for every 255, so long runs cost far less.
tinypg: pglz, chunks and the toaster
tinypg’s state at tag lesson-03 adds three modules. pglz.py is a
line-by-line port of pglz_compress() and pglz_decompress(), the history
table, hash and give-up rules included, so that its output can be compared
byte for byte. The main loop emits a tag or a literal at each position:
found_match = False
dp = 0
while dp < slen:
if len(out) >= result_max:
return None
if not found_match and len(out) >= strategy.first_success_by:
return None
m = find_match(dp)
if m:
length, off = m
out_ctrl() # pglz_out_tag()
ctrlb |= ctrl
ctrl = (ctrl << 1) & 0xFF
if length > 17:
out += bytes([((off & 0xF00) >> 4) | 0x0F, off & 0xFF, length - 18])
else:
out += bytes([((off & 0xF00) >> 4) | (length - 3), off & 0xFF])
for _ in range(length):
hist_add(dp)
dp += 1
found_match = True
else:
out_ctrl() # pglz_out_literal()
out.append(source[dp])
ctrl = (ctrl << 1) & 0xFF
hist_add(dp)
dp += 1
if ctrlp >= 0:
out[ctrlp] = ctrlb
if len(out) >= result_max:
return None
return bytes(out)
lz4.py only decompresses. Its compressor would have to reproduce liblz4’s
match choices to give the same bytes, which is a library to port, not a few
lines, so tinypg writes pglz and reads both.
toast.py has the rest. save_datum() is toast_save_datum(): the size
rules for the pointer and the chunk loop. The TOAST relation is a tinypg
heap file like any other:
def save_datum(self, datum, xid, cid=0):
"""toast_save_datum(): store the value's bytes as chunks, return the
TOAST pointer that replaces it in the tuple."""
if varatt.is_short(datum):
data = bytes(varatt.vardata_any(datum))
rawsize, extinfo = len(data) + varatt.VARHDRSZ, len(data) # as if not short
elif varatt.is_4b_c(datum):
data = bytes(datum[varatt.VARHDRSZ:varatt.varsize_4b(datum)]) # va_tcinfo too
size, method, _ = varatt.compressed_parts(datum)
rawsize = size + varatt.VARHDRSZ
extinfo = len(data) | method << varatt.VARLENA_EXTSIZE_BITS
else:
data = bytes(varatt.vardata_any(datum))
rawsize, extinfo = len(data) + varatt.VARHDRSZ, len(data)
valueid = self.new_oid()
for seq, at in enumerate(range(0, len(data), TOAST_MAX_CHUNK_SIZE)):
chunk = data[at:at + TOAST_MAX_CHUNK_SIZE]
tup = form_tuple_datums([valueid.to_bytes(4, "little"), seq.to_bytes(4, "little"),
varatt.make_4b(chunk)], TOAST_DESC, xmin=xid, cid=cid)
self.heap.put_tuple(tup, xid)
return varatt.make_toast_pointer(rawsize, extinfo, valueid, self.relid)
and toast_insert() the toaster’s rounds, of which this is the first:
# 1: compress EXTENDED values, biggest first; one still bigger than the
# target on its own goes out of line at once
while data_size() > max_data:
i = biggest(True, False)
if i < 0:
break
if desc[i].storage == "x":
try_compression(i)
else:
incompressible.add(i)
if varatt.varsize_any(datums[i]) > max_data and toastrel is not None:
externalize(i, "external-at-once")
tinypg/toast.py, lines 185–196
A tuple drawn to scale as a bar against a dashed line at 2032 bytes, shrinking as the toaster compresses its biggest value or replaces it with an 18-byte TOAST pointer; below it, the chunks written to the TOAST relation. Four recorded rows: 2001 x's, an incompressible 4004-byte value, 300,000 bytes of abc, and a row of two 1540-byte values. (This figure steps through a recorded run; it needs JavaScript.)
The toaster’s steps for four recorded rows, from python3 -m tinypg trace-toast tests/fixtures/pg19_toast.json docs:7 docs:3 docs:8 pair:1 (tag
lesson-03). The tuple is drawn to scale up to 4200 bytes; a longer value is
cut. The last frame of each row compares tinypg’s stored length with the
lp_len PostgreSQL recorded.
The comparison replays the recorded INSERTs with the server’s xids. Value
OIDs come from the recording too: the server picks each one with
GetNewOidWithIndex(), and tinypg has no OID counter to pick the same.
$ python3 -m tinypg compare tests/fixtures/pg19_toast.json
docs (id int4, body text): 8 INSERTs, 8 rows; PostgreSQL wrote 1 pages, tinypg 1
block 0: 8 tuples, 8188 of 8192 bytes identical
pd_lsn (bytes 0-7): postgres 0000000008fc0106, tinypg 0000000000000000; 4 bytes differ
its TOAST relation: PostgreSQL wrote 1 pages, tinypg 1
toast block 0: 5 tuples, 8188 of 8192 bytes identical
pd_lsn (bytes 0-7): postgres 0000000078fb0106, tinypg 0000000000000000; 4 bytes differ
pair (a text, b text): 1 INSERTs, 1 rows; PostgreSQL wrote 1 pages, tinypg 1
block 0: 1 tuples, 8188 of 8192 bytes identical
pd_lsn (bytes 0-7): postgres 0000000078350206, tinypg 0000000000000000; 4 bytes differ
its TOAST relation: PostgreSQL wrote 1 pages, tinypg 1
toast block 0: 1 tuples, 8188 of 8192 bytes identical
pd_lsn (bytes 0-7): postgres 00000000802e0206, tinypg 0000000000000000; 4 bytes differ
docs_lz4 (id int4, body text): 3 INSERTs, 3 rows; tinypg cannot write them (tinypg compresses with pglz only), so it reads PostgreSQL's pages instead
(0, 1): (2, 'pglz compresses ...' (5000 chars)); body is lz4-compressed inline (55 bytes)
(0, 2): (3, 'a4ayc/80/OGda4BO...' (4004 chars)); body is a TOAST pointer to value 36376 (uncompressed)
(0, 3): (8, 'abcabcabcabcabca...' (300000 chars)); body is lz4-compressed inline (1189 bytes)
3 of 3 rows read back equal to the values inserted
The table pages and the TOAST pages are identical except pd_lsn, which
still needs a write-ahead log. That covers pglz’s output for five different
values, the compressed and external headers, all three TOAST pointers (two
in docs, one in pair), and all six chunk rows. For the LZ4 table tinypg checks reading instead: it decodes
the server’s pages, decompresses LZ4 and fetches the external chunks, and
gets back every value that was inserted. It reads the server’s own files
too, following pointers into the TOAST relation’s file:
$ python3 -m tinypg inspect "$PGDATA/base/16420/36358" --types int,text --toast "$PGDATA/base/16420/36361"
block 0: lsn 0/0601FC08 checksum 11583 flags 0 lower 56 upper 5472 special 8192 pagesize_version 8196 prune_xid 1498
lp off len xmin xmax ctid infomask2 infomask hoff row
1 8144 41 1498 0 (0,1) 2 2306 24 (1, 'a short note')
2 8016 124 1499 0 (0,2) 2 2306 24 (2, 'pglz compresses ...' (5000 chars))
3 7968 46 1500 0 (0,3) 2 2310 24 (3, 'a4ayc/80/OGda4BO...' (4004 chars))
4 7720 246 1501 0 (0,4) 2 2306 24 (4, 'map map the varl...' (12199 chars))
5 7616 98 1502 0 (0,5) 2 2306 24 (5, 'naïve café naïve...' (3300 chars))
6 5584 2032 1503 0 (0,6) 2 2306 24 (6, 'xxxxxxxxxxxxxxxx...' (2000 chars))
7 5520 63 1504 0 (0,7) 2 2306 24 (7, 'xxxxxxxxxxxxxxxx...' (2001 chars))
8 5472 46 1505 0 (0,8) 2 2310 24 (8, 'abcabcabcabcabca...' (300000 chars))
What tinypg leaves out: the TOAST relation’s index (reading a value scans
the TOAST heap), choosing value OIDs, LZ4 compression, the toast_tuple_target
storage parameter (which sets a table’s own target, from 128 to 8160 bytes), and UPDATE, which
can keep an unchanged out-of-line value without copying it. Reading slices
of a value without fetching all of it (substr() on an uncompressed
external value) is also left out.
Try it yourself
With a PostgreSQL 19 server, pageinspect, and tables created WITH (autovacuum_enabled = off) and with COMPRESSION pglz on their text
columns:
A table
(id bigint, body text). What is the longestrepeat('x', n)stored without the toaster, and what doesn + 1become?Answer
24 + 8 + (n + 4) must be at most 2032, so n = 1996, with
lp_len2032. At 1997 the tuple would be 2033 bytes and the value is compressed:lp_len67.ALTER TABLE ... ALTER COLUMN body SET STORAGE EXTERNAL, then insertrepeat('abc', 100000). What does the pointer say, and how big is the TOAST relation?Answer
With
EXTERNALthe toaster may move a value out of line but never compresses it, so all 300,000 bytes go out:va_rawsize300004 andva_extinfo300000 (equal sizes, so uncompressed). That is 151 chunks (150 of 1996 bytes and one of 600), four to a page, so 38 pages. tinypg, given storagee, writes the same pointer, 151 chunks and 38 pages.SET STORAGE MAINinstead, and insert the incompressible 4004-byte value of row 3. Where does it go?Answer
It stays inline:
lp_len4036 (24 + 4 + 4008), and the TOAST relation stays empty. Compression fails in round 3, and round 4 moves aMAINvalue out only if the data is over 8160 − 24 = 8136 bytes.How many chunks and TOAST pages does an incompressible value of 10,032 bytes need? (The base64 of the SHA-256 of 1 to 228, as in row 3, is one.)
Answer
Six chunks: five of 1996 bytes (9980) and one of 52. Four 2032-byte chunk rows fill a page, so two pages.
pg_column_compressionis empty andpg_column_size10032.
The tinypg side, once the repository is public:
git clone https://github.com/toothywalrus/tinypg && cd tinypg
git checkout lesson-03
python3 -m unittest
python3 -m tinypg compare tests/fixtures/pg19_toast.json
python3 -m tinypg trace-toast tests/fixtures/pg19_toast.json docs:7 docs:3 docs:8 pair:1
To record your own: tools/record_toast.py --out DIR with the usual
PGHOST, PGPORT, PGUSER and PGDATABASE. It drops and recreates the
tables docs, pair and docs_lz4.
Sources
All PostgreSQL code is quoted from tag
REL_19_0 (commit
5c839a2a08b9), with tabs expanded to four spaces and the common indentation
removed.
src/include/access/heaptoast.h:TOAST_TUPLE_THRESHOLD,TOAST_TUPLE_TARGET_MAIN,TOAST_MAX_CHUNK_SIZEsrc/backend/access/heap/heaptoast.c:heap_toast_insert_or_update(),heap_fetch_toast_slice()src/backend/access/table/toast_helper.c:toast_tuple_find_biggest_attribute(),toast_tuple_try_compression(),toast_tuple_externalize()src/backend/access/common/toast_internals.c:toast_compress_datum(),toast_save_datum()src/backend/access/common/toast_compression.c,src/include/access/toast_compression.h:pglz_compress_datum(),lz4_compress_datum(),DEFAULT_TOAST_COMPRESSIONsrc/common/pg_lzcompress.c: the pglz format,pglz_compress(),pglz_decompress()src/include/varatt.h:varatt_external,vartag_external, the compressed headersrc/backend/catalog/toasting.c,src/backend/access/heap/heapam_handler.c: creating the TOAST relation,heapam_relation_needs_toast_table()doc/src/sgml/storage.sgml: the manual’s chapter on TOAST- The LZ4 block format,
which
lz4.pydecodes - tinypg at
lesson-03: the code, the fixturetests/fixtures/pg19_toast.json, andtools/record_toast.py, which recorded every psql and shell output on this page
ls postgres-internals/
Storage
- 01 A table is a file of 8 KB pages draftWhere a table lives on disk, the page header, line pointers, tuples filling from the end, and what a ctid is.
- 02 Inside a tuple: alignment, nulls and varlena draftHow column values are laid out after the header, why column order changes a row's size, and the 1-byte and 4-byte length headers.
- 03 TOAST: values too big for a page draftCompression, out-of-line storage in a TOAST table, and the 2 KB threshold that triggers them.
- 04 The free space map draftThe _fsm fork: a tree of one-byte free-space categories that tells an INSERT which page has room.
Buffers and durability
- 05 Shared buffers: a page cache with pins and locks plannedThe buffer table, buffer descriptors, pins, content locks, and clock-sweep eviction.
- 06 The write-ahead log: records and LSNs plannedWAL record layout, pd_lsn, and the rule that a page may not reach disk before its log does.
- 07 Checkpoints, full-page writes and checksums plannedWhat a checkpoint guarantees, why the first change after one logs the whole page, and how pd_checksum is computed.
- 08 Crash recovery: replaying the log plannedStarting from the last checkpoint's redo point and replaying records whose LSN is newer than the page's.
MVCC
- 09 Transaction IDs and the commit log plannedAssigning xids, and pg_xact: two bits of commit status per transaction.
- 10 xmin, xmax and the life of a row version plannedWhat UPDATE and DELETE really write, and following ctid chains to the newest version.
- 11 Snapshots: what a transaction can see plannedxmin, xmax and the in-progress list, and when READ COMMITTED and REPEATABLE READ take them.
- 12 Visibility rules and hint bits plannedHeapTupleSatisfiesMVCC case by case, and why reading a row can write to its page.
- 13 HOT updates and page pruning plannedHeap-only tuples, redirect line pointers, and cleaning a page while reading it.
- 14 VACUUM: removing dead tuples plannedScanning the heap, cleaning indexes, and marking line pointers unused.
- 15 The visibility map plannedThe _vm fork's all-visible and all-frozen bits, and what index-only scans and VACUUM get from them.
- 16 Freezing and transaction ID wraparound plannedWhy 32-bit xids wrap around, what freezing writes, and multixacts.
Indexes
- 17 B-tree pages and the Lehman–Yao tree plannedSpecial space, high keys and right links: a B-tree you can search while it changes.
- 18 B-tree insertion and page splits plannedDescending the tree, choosing a split point, and finishing a split in the parent.
- 19 Deduplication and bottom-up deletion plannedPosting lists for duplicate keys, and deleting old versions before a page has to split.
- 20 Hash indexes plannedBuckets, overflow pages and linear-hashing splits.
- 21 GIN and GiST, briefly plannedAn inverted index and a balanced tree of predicates: what each stores and when each fits.
Queries
- 22 From text to parse tree plannedThe grammar, the raw parse tree, and why parsing needs no catalog.
- 23 Analysis and rewriting plannedResolving names against the catalog, the Query tree, and the rewriter's views and rules.
- 24 The planner: paths and the cost model plannedseq_page_cost, random_page_cost and cpu_tuple_cost, and how the cheapest path wins.
- 25 Statistics and selectivity plannedWhat ANALYZE samples, most common values, histograms, and estimating a WHERE clause.
- 26 Join algorithms and join order plannedNested loop, hash and merge joins, and searching the join orders.
- 27 The executor: Volcano-style iterators plannedPlan nodes that each return one row per call, from a sequential scan up to a sort.
Concurrency and the server
- 28 Locks: heavyweight, row-level and lightweight plannedThe lock manager, row locks stored in xmax, LWLocks and spinlocks, and deadlock detection.
- 29 Processes and shared memory plannedThe postmaster, one backend per connection, the background workers, and what they share.
- 30 Streaming replication plannedShipping WAL to a standby, replaying it there, and replication slots.