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.
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, 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.
| lp | ctid | xmin | xmax | t_ctid | id | body |
|---|---|---|---|---|---|---|
| (0,1) | 758 | 0 | (0,1) | 1 | the first note | |
| (0,2) | 758 | 0 | (0,2) | 2 | the second note |
a checkpoint first, so the story starts clean: every page on disk, and the redo pointer right here.
notes page 0 at the INSERT, the new WAL records, the flush pointer catch up at COMMIT, the 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:
| step | what happens | the chapter |
|---|---|---|
| 1 | CHECKPOINT: dirty pages out, redo pointer set | checkpoints |
| 2 | BEGIN: no xid, no snapshot work, nothing written | transaction ids |
| 3 | INSERT: xid 759, heap tuple, index entry, two WAL records | the 8 KB page, a real b-tree, WAL records |
| 4 | COMMIT: commit record, WAL flush, pg_xact | what COMMIT waits for |
| 5 | first read: the clog lookup, then a hint bit | the commit log and hint bits |
| 6 | CHECKPOINT: 3 buffers and 1 clog page written | writing dirty pages back |
| 7 | the page, read from the file itself | the files behind a table |
| 8 | the INSERT's WAL, block by block | WAL 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:
- →
- →
- →
- →
- 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.
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).
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:
| lp | ctid | xmin | xmax | t_ctid | id | body |
|---|---|---|---|---|---|---|
| (0,1) | 758 | 0 | (0,1) | 1 | the first note | |
| (0,2) | 758 | 0 | (0,2) | 2 | the second note | |
| (0,3) | 759 | 0 | (0,3) | 3 | hello from the capstone |
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 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).
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:
a checkpoint first, so the story starts clean: every page on disk, and the redo pointer right here.
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_typetext | relnamename | forkint2 | blockint8 | fpi_bytesint4 |
|---|---|---|---|---|
| INSERT | notes | 0 | 0 | 188 |
| INSERT | notes | 2 | 0 | 8192 |
| INSERT_LEAF | notes_pkey | 0 | 1 | 100 |
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.
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.
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;| xminxid | statustext | idint4 | bodytext |
|---|---|---|---|
| 754 | committed | 3 | hello from the capstone |
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:
| lpint2 | lp_offint2 | lp_lenint2 | t_xminxid | t_ctidtid | page_lsnpg_lsn |
|---|---|---|---|---|---|
| 1 | 8144 | 43 | 758 | (0,1) | 0/1624598 |
| 2 | 8096 | 44 | 758 | (0,2) | 0/1624598 |
| 3 | 8040 | 52 | 759 | (0,3) | 0/1624598 |
notes, read from the data file after the checkpoint. the new tuple is slot 3, and the page's LSN is : 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:
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;| markedbool |
|---|
| t |
| resource_managertext | record_typetext | record_lengthint4 | fpi_lengthint4 |
|---|---|---|---|
| Heap | INSERT | 242 | 188 |
| Btree | INSERT_LEAF | 153 | 100 |
| Transaction | COMMIT | 34 | 0 |
then the two pages it touched:
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;| lpint2 | lp_offint2 | lp_lenint2 | t_xminxid | t_ctidtid |
|---|---|---|---|---|
| 1 | 8144 | 43 | 754 | (0,1) |
| 2 | 8096 | 44 | 754 | (0,2) |
| 3 | 8040 | 52 | 755 | (0,3) |
| itemoffsetint2 | ctidtid | datatext |
|---|---|---|
| 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 |
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.