DISKsurvives a crashMEMORYlost in a crashpage 0Dune 3lsn 0page 1Holes 5lsn 0CHECKPOINTlsn 1T1 page 0lsn 2T1 COMMITlsn 3T2 page 1lsn 4page 0slot 0emptypage 1slot 1emptyT1 page 0lsn 2T1 COMMITlsn 3T2 page 1lsn 41BEGIN; -- T12UPDATE books SET stock = 23 WHERE id = 1;4COMMIT;5BEGIN; -- T26UPDATE books SET stock = 97 WHERE id = 3;8-- power cut: no COMMITname stockDune 2Holes 5234
Back tray, on disk: the data file pages and the WAL fileMiddle tray, in memory: shared buffers and WAL buffers (lost in a crash)Tiles: WAL records, numbered by LSN; page tokens: pages moving between disk and memoryAt the back, on disk: the data file (pages 0 and 1) and the WAL file. In the middle, in memory: shared buffers and the WAL buffers. In front: the SQL that runs, and what readers see after recovery. Every change is logged before its page may reach disk; COMMIT waits only for the log. After the power cut, replay from the checkpoint brings back T1's committed change, and T2, which never committed, stays invisible. Real LSNs are byte positions in the WAL, printed like 0/16B3748, and a page stores the position just past its last record. The figure numbers the records 1, 2, 3, 4 to keep them readable.

Why a log

  1. PostgreSQL does not change rows on disk directly. It copies each 8 kB page it needs from the data file into shared buffers, in memory, and changes it there. Memory is fast, but a power cut wipes it.

Commit and the WAL rule

Crash and recovery

What happens

;; step 1/10 · memory
data file (disk)  ->  shared buffers (memory)
  page 0  Dune 3   lsn 0
  page 1  Holes 5  lsn 0
a page is 8192 bytes; reads and writes move whole pages
changed pages are written back later, not at once
power cut?  everything in memory is lost

Real LSNs are byte positions in the WAL, printed like 0/16B3748, and a page stores the position just past its last record. The figure numbers the records 1, 2, 3, 4 to keep them readable. In a table this small, both rows would share page 0. The figure puts Holes on page 1 so each transaction changes its own page.