The symptom#
A list page shows, for each investigation, its onset time, its conclusion, the number of leads and the gaps. The query selects them from a result jsonb column:
SELECT id,
r.result->>'onset' AS onset,
r.result->>'conclusion' AS conclusion,
jsonb_array_length(r.result->'leads') AS lead_count,
r.result->'gaps' AS gaps
FROM results r ORDER BY id DESC LIMIT 101;
The fields are small. The documents are not: each also holds hundreds of evidence items. EXPLAIN (ANALYZE, BUFFERS) shows every scan node fast, yet the top node takes most of the time, and most of the buffers it reads belong to a table the query never names.
Where the time goes#
When a row is wider than about 2 kB, PostgreSQL compresses its large values and moves them out of line until the row fits. The TOAST documentation describes the mechanism: an out-of-line value is split into chunks in a separate TOAST table, and the row keeps a pointer. Reading the value means fetching its chunks and decompressing them.
The jsonb operators each take the whole jsonb value as input. result->'onset' detoasts result, finds the key and returns it. result->'conclusion' in the same select list detoasts it again; PostgreSQL does not keep the decompressed value between the two expressions. Four fields mean four fetches and four decompressions per row. That work happens in the projection, which is why the plan's scan nodes look cheap and the time appears in the node above them.
The lab#
The lab needs Docker and builds 2,000 documents of about 175 KB of JSON text each, which compress to about 26 KB.
docker run -d --rm --name pl-a-toast-jsonb -e POSTGRES_PASSWORD=x postgres:18
docker exec -it pl-a-toast-jsonb psql -U postgres
CREATE TABLE results (id bigserial PRIMARY KEY, result jsonb NOT NULL);
INSERT INTO results (result)
SELECT jsonb_build_object(
'onset', '2026-11-21T04:15:38Z',
'conclusion', 'Connection pool exhausted after deploy ' || g,
'leads', (SELECT jsonb_agg(jsonb_build_object('rank', i, 'text', md5((g * 1000 + i)::text)))
FROM generate_series(1, 12) i),
'gaps', jsonb_build_array('logs not read'),
'evidence', (SELECT jsonb_agg(jsonb_build_object('n', i, 'window', '15m',
'text', repeat('timeout talking to upstream ', 8) || md5((g * 1000 + i)::text)))
FROM generate_series(1, 600) i))
FROM generate_series(1, 2000) g;
VACUUM ANALYZE results;
SELECT pg_size_pretty(avg(pg_column_size(result))) AS stored_avg,
pg_size_pretty(pg_relation_size('results')) AS heap,
pg_size_pretty(pg_relation_size(reltoastrelid)) AS toast
FROM results, pg_class WHERE pg_class.oid = 'results'::regclass
GROUP BY reltoastrelid;
stored_avg | heap | toast
------------+--------+-------
26 kB | 120 kB | 55 MB
The table itself is 120 kB; the documents live in the 55 MB TOAST table. Now run the list query above, a version that reads only the conclusion, and a version that reads the value once:
SELECT id, x.onset, x.conclusion, jsonb_array_length(x.leads) AS lead_count, x.gaps
FROM results r
CROSS JOIN LATERAL jsonb_to_record(r.result)
AS x(onset text, conclusion text, leads jsonb, gaps jsonb)
ORDER BY id DESC LIMIT 101;
On PostgreSQL 18.7 with a warm cache, two runs each:
| Query, 101 rows | Buffers | Execution time |
|---|---|---|
One field with -> | 638 | 10.6 and 27.6 ms |
Four fields with -> and ->> | 2,428 | 94.0 and 98.2 ms |
Four fields from one jsonb_to_record | 610 | 14.7 and 9.5 ms |
Four extractions read almost exactly four times the buffers of one, because each reads the full document's chunks. The lateral version reads each document once and costs about the same as a single field. The lateral join runs jsonb_to_record once per row and exposes the keys you declare as typed columns.
Keep indexed predicates as expressions#
The rewrite has a trap. If the table has an expression index such as CREATE INDEX ON results ((result->>'conclusion')), a filter must still say r.result->>'conclusion' = ... for the planner to match the index. Moving the filter to the lateral column loses it. In the lab:
-- WHERE r.result->>'conclusion' = 'Connection pool exhausted after deploy 7'
Index Scan using results_conclusion_idx on results r
Execution Time: 0.283 ms
-- WHERE x.conclusion = 'Connection pool exhausted after deploy 7'
Seq Scan on results r
-> Function Scan on jsonb_to_record x (loops=2000)
Rows Removed by Filter: 1
Execution Time: 208.095 ms
The second form decompresses all 2,000 documents to find one. Take the projected fields from the lateral record and leave indexed filters on the expression they were indexed by. A filter with no index can move, and then it shares the single read.
Check that the results did not change#
jsonb_to_record and -> differ in one case: a key holding JSON null. -> returns a jsonb null, while a jsonb column of jsonb_to_record returns SQL NULL. In the lab, SELECT x.gaps IS NULL, '{"gaps": null}'::jsonb -> 'gaps' over that document returns t and null. Code that treats the two differently will see a change. x.conclusion #>> '{}' gives the same text as result->>'conclusion' when you declare a field as jsonb but need its string.
Before shipping, compare old and new over the whole table in one REPEATABLE READ transaction, for example with an md5 of the aggregated rows from each query, and compare the IDs each filter selects.
The production case#
An environment's investigation list in one production application read each row's stored result four times: onset, conclusion, lead count and gaps. Results averaged 37 KB compressed, 169 KB as text and 2.2 MB at most. A direct test over 101 rows took 0.2 ms selecting only the IDs, 52 ms with one -> field and 210 to 240 ms with all four. In the slowest plan, at the default page of 25 rows on a cold cache, 475 of 505 buffer reads were in the TOAST table.
The fix rewrote the select list to one LEFT JOIN LATERAL jsonb_to_record(r.result), with the state filters reading the same columns. At the API's maximum of 101 rows with a custom plan, the query went from 660.6 ms cold and 265.5 ms warm to 121.1 ms warm. The remaining cost was about 0.76 ms per row in jsonb_to_record, one decompression per row, which is the floor while the list reads these fields from the stored document. A comparison in one transaction over all 1,287 results found the same rows, and the same IDs for every state filter. No stored result held a JSON null in the four keys.
If one decompression per row is still too much, store the fields the list needs in their own columns at write time. That moves the cost from every read to one write. For reading plans like these, see handing over a plan someone else can reason about.
Where this came from#
Proofline found this in its own investigation list and shipped the rewrite in its production release of 22 November 2026. The sizes and timings in The production case are that database's readings before and after the change. Proofline reviews GitHub pull requests; new organizations get one calendar month of hosted code review without a cloud connection. Start a free GitHub review ยท Eligibility and fair-use terms
Questions#
Does PostgreSQL decompress a jsonb value once per query or once per operator?
Once per operator call in the select list. Each -> or ->> detoasts its input again, so reading several keys from one large value multiplies the work.
Is jsonb_to_record faster than several -> operators?
For a value stored out of line, yes, when you read more than one key: it detoasts the value once and returns all declared keys. A small value stored in the row has no chunks to fetch, so there is little to save.
Can I filter on a jsonb_to_record column and keep my expression index?
No. The planner matches an expression index only against the same expression. Keep indexed filters as result->>'key' and use the lateral columns for output.