skip to content

one INSERT, all the way down

parse, plan, heap, index, WAL, commit, checkpoint. every step of one row, traced on a real server.

address
everything.deep_dives.one_insert_all_the_way_down
part
part 18, deep dives and interviews
chapter
chapter 1 of 10
reading time
17 min

one INSERT into a table with a primary key touches almost every chapter of this book. it's parsed and planned, the executor writes a tuple into a heap page and an entry into the index, both changes go into the WAL, COMMIT flushes that WAL and flips two bits in the commit log, and a checkpoint finally writes the pages to the file.

here's all of it, captured on a real postgres 18.6 server, one step at a time.

the picture

you know how an INSERT feels like one thing? you send a line of SQL, you get INSERT 0 1 back, done. under that one line, postgres did a dozen separate jobs, and most of them were writing something down somewhere other than your table.

think of posting a letter. a clerk reads the address and checks it's a real place (the parser and analyzer). someone picks the route (the planner). the letter goes into a pigeonhole (the heap page) and a card goes into the index drawer saying which pigeonhole (the index entry). every move is written in the day book first (the WAL). you get your receipt once the day book entry is in ink (COMMIT). the pigeonholes get emptied into the vault at the end of the shift (the checkpoint).

the row is the one every chapter used, more or less: a table with an int key and a text body, two rows already in it, vacuumed, and a checkpoint to start clean.

sql
CREATE TABLE notes (id int PRIMARY KEY, body text NOT NULL);
INSERT INTO notes VALUES (1, 'the first note'), (2, 'the second note');
VACUUM notes;
CHECKPOINT;
 
BEGIN;
INSERT INTO notes VALUES (3, 'hello from the capstone');
COMMIT;

hover a stage.

the whole trip, one stage per box. hover a stage for what it writes and where. everything left of COMMIT happens in memory; only the WAL flush and the checkpoint touch the disk.

the whole trip, step by step

here's the capture. on the left, the one session and what it ran. on the right, the heap page, the index, the WAL and the buffer pool, after every step, with what changed lit up. press play, or step through it.

T1
·
1
obsCHECKPOINT
notes · page 0
byte 0 header line pointerstuples, byte 8,192
lower 32free 8,064 B, unlitupper 8096
lpctidxminxmaxt_ctididbody
(0,1)7580(0,1)1the first note
(0,2)7580(0,2)2the second note
notes_pkey
12root,a leaf
WAL
pagesnotes·0pd_lsn+0x000
shared buffers (pg_buffercache)
+ 788 frames holding other relations, not drawn
page table: page → frame

a checkpoint first, so the story starts clean: every page on disk, and the redo pointer right here.

step 1/8
real output, a postgres 18.6 server · insert-down
one INSERT on a real postgres 18.6 server, eight steps. watch slot 3 appear on notes page 0 at the INSERT, the new WAL records, the flush pointer catch up at COMMIT, the hint bit show up when the row is first read, and the dirty frames (accent corners) go clean at the checkpoint.

and here's where each step is explained properly:

stepwhat happensthe chapter
1CHECKPOINT: dirty pages out, redo pointer setcheckpoints
2BEGIN: no xid, no snapshot work, nothing writtentransaction ids
3INSERT: xid 759, heap tuple, index entry, two WAL recordsthe 8 KB page, a real b-tree, WAL records
4COMMIT: commit record, WAL flush, pg_xactwhat COMMIT waits for
5first read: the clog lookup, then a hint bitthe commit log and hint bits
6CHECKPOINT: 3 buffers and 1 clog page writtenwriting dirty pages back
7the page, read from the file itselfthe files behind a table
8the INSERT's WAL, block by blockWAL records

the rest of the chapter takes the stages one at a time.

parse, analyze, rewrite, plan

before anything is written, the text has to become something the executor can run. the life of a query walks a SELECT through these stages. an INSERT goes the same way, and the server will log every tree it builds:

  1. →
  2. →
  3. →
  4. →
text → parse tree
query.sql
  1. INSERT INTO notes VALUES (3, 'hello from the capstone')

parserthe parser only checks the grammar: INSERT INTO, a name, VALUES, a list of two expressions. it has no idea yet whether notes exists, or has two columns.

stage 1/5
real output, a postgres 18.6 server · insert-plan
the same INSERT, logged by a real postgres 18.6 with debug_print_parse, debug_print_rewritten and debug_print_plan on. the trees are trimmed to the lines that matter. watch the two constants: 3 becomes the four bytes 3 0 0 0, and the text becomes a varlena whose first byte, 108, is its length (27) shifted left by two.

the same plan, the way EXPLAIN draws it. no scans at all: a VALUES list is a Result node, and the writing is ModifyTable's job (reading EXPLAIN).

show =
estimated rows
real output, a postgres 18.6 server · insert-plan
plain EXPLAIN of the INSERT, captured. ModifyTable expects 0 rows because it returns none (no RETURNING); the Result under it makes 1.

the heap page

ModifyTable calls into the heap. the first thing it needs is a transaction id: BEGIN didn't take one (step 2 shows T1 in a transaction with no xid), because postgres only assigns one when a transaction first writes. this one gets 759.

then it needs a page with room. the table has one page, and page 0 has 8,064 bytes free (bigger tables ask the free space map). the new tuple goes in:

byte 0 header line pointerstuples, byte 8,192
lower 36free 8,004 B, unlitupper 8040
lpctidxminxmaxt_ctididbody
(0,1)7580(0,1)1the first note
(0,2)7580(0,2)2the second note
(0,3)7590(0,3)3hello from the capstone
tuple (0,3) · off 8040 · len 52 B
t_xmin759 in progress
t_xmax0 nobody deleted it
t_ctid(0,3) itself: the newest version
infomaskHASVARWIDTHXMAX_INVALID
t_hoff24 B
dataid 3body hello from the capstone
headerline pointer → tuplefree space, unlitdeadin progresswhat this step changed
real postgres 18.6 output · a native server · traces/insert-down, after the INSERT
page 0 of notes right after the INSERT, from the capture. slot 3 is new: a 4-byte line pointer at the front, a 52-byte tuple at the back, with xmin 759 and HEAP_XMAX_INVALID and nothing else. 759 is still in progress here, so it's drawn dashed.

the page header tells the same story in two numbers. pd_lower went from 32 to 36: one more line pointer. pd_upper went from 8,096 to 8,040: 56 bytes, which is the 52-byte tuple rounded up to the 8-byte alignment (inside a tuple has the arithmetic). the tuple's header says xmin 759, xmax 0, ctid (0,3), its own address. nothing about committed: nobody knows that yet.

one more thing changed, and it's easy to miss. VACUUM had marked page 0 all-visible in the visibility map. a new tuple from an in-progress transaction is not visible to everyone, so the INSERT cleared that bit. from now on an index-only scan has to visit this page again until the next VACUUM (index-only scans).

the index entry

next, the primary key. it's a btree with one leaf (block 1; block 0 is the metapage). before inserting, nbtree checks uniqueness: it searches the leaf for another 3 that a live or in-progress transaction could still own, finds none, and adds the entry (how a unique index says no).

123root,a leafheap 0
real output, a postgres 18.6 server · insert-down
the primary key after the INSERT, captured. one leaf page, three entries. the new one, key 3, points at (0,3), the heap slot from the previous figure. an index entry is a key and a heap address, nothing else: no xmin, no xmax.

that last point matters. the index doesn't know whether 759 committed. a reader that finds key 3 here still has to go to the heap and check the tuple's xmin, unless the visibility map vouches for the whole page (a real b-tree, page by page). every extra index on the table would get one more entry here, and one more WAL record (what indexes cost).

the WAL

neither of those page changes is allowed to reach the disk before the WAL record that describes it. that's the write-ahead rule. the INSERT wrote two records:

obsCHECKPOINT
pagesnotes·0pd_lsn+0x000

a checkpoint first, so the story starts clean: every page on disk, and the redo pointer right here.

flush line: durable from here backin wal_buffers, not on diskredo pointer, record headerjust appended, being replayeddirty page
step 1/8
real output, a postgres 18.6 server · insert-down
the WAL across the whole capture. step through: the checkpoint's records, then the INSERT's Heap INSERT and Btree INSERT_LEAF (past the flush pointer, dashed: only in wal_buffers), then the 34-byte commit that drags the flush pointer past all three.

look at the sizes. the Heap INSERT record is 8,447 bytes, and 8,380 of them are page images. the btree record is 153 bytes, 100 of them a copy of the leaf. these are the first changes to those pages since the checkpoint, so postgres logs each whole page once, in case the next write of it is torn (torn pages and full-page writes). the last step of the capture asks pg_get_wal_block_info which image is which:

record_typetextrelnamenameforkint2blockint8fpi_bytesint4
INSERTnotes00188
INSERTnotes208192
INSERT_LEAFnotes_pkey01100
(3 rows)
real output, a postgres 18.6 server · insert-down
the INSERT's WAL records, block by block. fork 0 is the main fork, fork 2 the visibility map. the heap page's image is small because postgres skips the empty hole between pd_lower and pd_upper; the visibility map page is logged whole.

so the expensive part of this INSERT wasn't the row, or even the heap page: it was the 8,192-byte image of the visibility map page whose bit it cleared. a second INSERT before the next checkpoint would carry no images at all, just the new tuple.

and notice what the flush pointer did at the INSERT: nothing. it stayed at 23,209,088 while the insert pointer moved to 23,217,720. the records are in memory. if the server died right now, they'd be gone, and that's fine, because nobody was told the row exists.

predict the output
COMMIT has returned. which of these is on disk now?
sql
BEGIN;
INSERT INTO notes VALUES (3, 'hello from the capstone');
COMMIT;   -- returned. what is durable?

commit and the commit log

COMMIT does three things, in this order: write a Transaction COMMIT record (34 bytes), flush the WAL up to its end (the flush pointer jumps to 23,217,760), and set xid 759's two bits in pg_xact, the commit log, to committed. then it tells the client.

that's the whole commit. the tuple on the page didn't change: its header still has no idea. so step 5, the first reader, does the work. it finds xmin 759, sees no hint, asks pg_xact, hears "committed", and writes that down on the tuple as HEAP_XMIN_COMMITTED (infomask 2,050 → 2,306), so nobody has to ask again. a SELECT that writes to a page: that's hint bits. whether the reader then sees the row at all is the visibility rules applied to its snapshot.

sqldb=lab · session clog
CREATE TABLE inbox (id int PRIMARY KEY, body text NOT NULL);
INSERT INTO inbox VALUES (3, 'hello from the capstone');
SELECT xmin, pg_xact_status(xmin::text::xid8) AS status, id, body FROM inbox;
output, from postgres 18.6
#1 · CREATE TABLE
#2 · INSERT 0 1
#3 · SELECT 1
xminxidstatustextidint4bodytext
754committed3hello from the capstone
(1 row)

the checkpoint, and the page on disk

at step 6 an explicit CHECKPOINT runs. the log says it wrote 3 buffers and 1 SLRU buffer: the heap page, the index leaf, the visibility map page, and the pg_xact page holding 759's bits. each file is fsynced, then a checkpoint record goes into the WAL and the redo pointer moves from 23,208,880 to 23,217,760, past everything this INSERT wrote. from now on, crash recovery never needs those records again (checkpoints, crash recovery).

and the page is on disk. step 7 reads it from the file, with pg_read_binary_file on pg_relation_filepath('notes'), not through shared buffers, and hands the bytes to pageinspect:

lpint2lp_offint2lp_lenint2t_xminxidt_ctidtidpage_lsnpg_lsn
1814443758(0,1)0/1624598
2809644758(0,2)0/1624598
3804052759(0,3)0/1624598
(3 rows)
real output, a postgres 18.6 server · insert-down
page 0 of notes, read from the data file after the checkpoint. the new tuple is slot 3, and the page's LSN is 0/1624598: the end of the Heap INSERT record, the last WAL record that changed this page.

that LSN is the last link. 0/1624598 is 23,217,560, exactly where the Heap INSERT record ends. redo uses it to decide whether a WAL record still has to be applied to this page: anything at or before the page's LSN is already in it. and the hint bit from step 5 made it to disk too, without a WAL record of its own, because checksums are off on this server (with checksums on it would have cost a FPI_FOR_HINT, see data checksums).

your turn

the browser runs the same INSERT on its own postgres. it's a lab engine (one session, checksums on, nobody else writing), so the LSNs differ, but the records are the same kinds:

sqldb=lab · session mine
CREATE TABLE inbox (id int PRIMARY KEY, body text NOT NULL);
INSERT INTO inbox VALUES (1, 'the first note'), (2, 'the second note');
CHECKPOINT;
SELECT set_config('my.lsn', pg_current_wal_insert_lsn()::text, false) IS NOT NULL AS marked;
INSERT INTO inbox VALUES (3, 'hello from the capstone');
SELECT resource_manager, record_type, record_length, fpi_length
FROM pg_get_wal_records_info(current_setting('my.lsn')::pg_lsn, pg_current_wal_insert_lsn())
ORDER BY start_lsn;
output, from postgres 18.6
#1 · CREATE TABLE
#2 · INSERT 0 2
#3 · CHECKPOINT
#4 · SELECT 1
markedbool
t
(1 row)
#5 · INSERT 0 1
#6 · SELECT 3
resource_managertextrecord_typetextrecord_lengthint4fpi_lengthint4
HeapINSERT242188
BtreeINSERT_LEAF153100
TransactionCOMMIT340
(3 rows)

then the two pages it touched:

sqldb=lab · session mine
continues session mine (1 earlier block run first)
SELECT lp, lp_off, lp_len, t_xmin, t_ctid FROM heap_page_items(get_raw_page('inbox', 0)) ORDER BY lp;
SELECT itemoffset, ctid, data FROM bt_page_items('inbox_pkey', 1) ORDER BY itemoffset;
output, from postgres 18.6
#1 · SELECT 3
lpint2lp_offint2lp_lenint2t_xminxidt_ctidtid
1814443754(0,1)
2809644754(0,2)
3804052755(0,3)
(3 rows)
#2 · SELECT 3
itemoffsetint2ctidtiddatatext
1(0,1)01 00 00 00 00 00 00 00
2(0,2)02 00 00 00 00 00 00 00
3(0,3)03 00 00 00 00 00 00 00
(3 rows)
one level deeperwhat didn't happen

no data file was written during the transaction. not at INSERT, not at COMMIT. the only fsync before the checkpoint was the WAL's.

no index entry carries visibility. the heap tuple is the only place that knows about 759, which is why a reader can't trust an index alone.

the free space map wasn't touched: the buffer pool shows its three pages clean the whole time. postgres updates it lazily, mostly from VACUUM.

nothing was locked that a reader would notice: an INSERT takes a RowExclusiveLock on the table, which conflicts with no other INSERT, UPDATE, DELETE or SELECT, and is released at COMMIT (table lock modes). a second session inserting key 4 at the same time wouldn't wait for anything. one inserting key 3 would wait on 759 at the unique check.

keylines

  • an INSERT is parse → plan → heap tuple → index entries → WAL records, all in memory.
  • COMMIT's only disk wait is flushing the WAL up to the commit record. then pg_xact says committed.
  • the tuple learns it committed later, from the first reader, as a hint bit.
  • the first change to a page after a checkpoint logs the whole page.
  • the checkpoint writes the dirty pages to the data files, and the redo pointer moves past them.
  • the page's LSN on disk is the end of the last WAL record that changed it.