Home›Learn›PostgreSQL 3: what happens on every write
PostgreSQL · Chapter 3

What happens on every write

Why does a commit only write the log, and where do old row versions go?

Four ideas explain almost every PostgreSQL behavior you will see in production. Each one exists to solve a problem the one before it created: the WAL makes commits fast and safe, checkpoints keep the WAL bounded, MVCC lets readers and writers stop waiting, and vacuum cleans up after MVCC.

Explained clearly

The WAL: why PostgreSQL writes everything twice

Listen, 2 min 55 s

Watch it first, then read the details:

1

The problem

A committed change has to survive a crash. Writing every changed 8 KB page to its place in the table file at COMMIT would mean several random writes per transaction. That is slow, and a crash halfway through leaves a half-written page.

2

What it is

The write-ahead log is an append-only log in pg_wal/. Every change is described there before the data page counts. At COMMIT, PostgreSQL flushes only the WAL. The data pages are written later by the checkpointer. After a crash, PostgreSQL replays the WAL from the last checkpoint.

3

Follow one request

  1. UPDATE changes the page in shared buffers and adds a WAL record to the WAL buffers.
  2. COMMIT flushes the WAL to pg_wal/, records the commit in pg_xact/, and only then answers the app.
  3. The WAL sender streams the same records to the standby.
  4. Later, the checkpointer writes the dirty page to the table file.
  5. Old WAL files are recycled once a checkpoint has passed them, unless a replication slot or the archiver still needs them.

For your app: every write transaction waits for one WAL flush. On network storage that flush is the floor for commit latency. Putting many rows in one transaction pays for the flush once.

4

What to watch in production

  • Disk filling in pg_wal. An inactive replication slot or a failing archive_command holds WAL forever. max_slot_wal_keep_size caps what a slot can hold.
  • Too many checkpoints. If requested checkpoints outnumber timed ones, max_wal_size is too small (pg_stat_checkpointer on 17+, pg_stat_bgwriter before).
  • WAL volume. The first change to a page after a checkpoint writes the whole page to the WAL (full_page_writes), so frequent checkpoints make more WAL.
SELECT wal_records, wal_fpi, pg_size_pretty(wal_bytes) FROM pg_stat_wal;   -- 14+
SELECT slot_name, active,
       pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS held
FROM pg_replication_slots;

The same idea elsewhere: MySQL calls it the redo log. MongoDB calls it the journal.

Explained clearly

Checkpoints: when changed pages finally reach the disk

Listen, 2 min 54 s

Watch it first, then read the details:

1

The problem

COMMIT writes only the WAL, so changed pages pile up in shared buffers. The WAL cannot grow forever, and after a crash PostgreSQL has to replay all of it. Something has to write the pages out and say where recovery may start.

2

What it is

A checkpoint writes every dirty page in shared buffers to its table file, flushes them to disk, and then writes a checkpoint record to the WAL. Recovery starts from that record, and older WAL files can be recycled. It starts every checkpoint_timeout (5 min by default) or when the WAL passes max_wal_size (1 GB by default).

3

Follow one request

  1. An UPDATE changes a page in shared buffers. The page is now dirty.
  2. COMMIT flushes only the WAL.
  3. The timer fires. The checkpointer writes dirty pages, spread over 90% of the interval (checkpoint_completion_target), so the disk sees a trickle, not a spike.
  4. It writes the checkpoint record. WAL before that point is no longer needed for crash recovery.
  5. The next change to that page writes the whole page into the WAL once (full_page_writes), to guard against torn pages.

For your app: checkpoints are why commits can be fast and the WAL still stays bounded.

4

What to watch in production

  • Checkpoints too often. If WAL volume triggers most of them, the same hot pages are written again and again, and each one adds full-page images to the WAL. Raise max_wal_size.
  • I/O spikes. Usually a small checkpoint_completion_target or a disk near its limit.
  • Long recovery. A very large max_wal_size means more WAL to replay after a crash. That is the trade.
SELECT num_timed, num_requested, write_time, sync_time
FROM pg_stat_checkpointer;          -- 17+
SELECT checkpoints_timed, checkpoints_req
FROM pg_stat_bgwriter;              -- 16 and older

The same idea elsewhere: InnoDB flushes dirty pages in the background and checkpoints against its redo log size. MongoDB's WiredTiger takes a checkpoint every 60 seconds.

Explained clearly

MVCC: how readers and writers avoid waiting for each other

Listen, 2 min 56 s

Watch it first, then read the details:

1

The problem

A report reads every order while someone updates one of them. If reads and writes had to lock the same row, one of them would wait. On a busy system that is a lot of waiting.

2

What it is

PostgreSQL keeps more than one version of a row. Each version carries xmin, the transaction that created it, and xmax, the one that replaced or deleted it. Each query takes a snapshot when it starts and sees only versions committed before that snapshot. Readers do not block writers, and writers do not block readers.

3

Follow one request

  1. The row exists as version 1, created by transaction 100.
  2. Transaction 200 runs UPDATE: version 1 gets xmax = 200, and a new version 2 is written with xmin = 200.
  3. A report that started before 200 committed still sees version 1. A query that starts after sees version 2.
  4. Once no snapshot can see version 1, it is dead. Vacuum removes it later.

For your app: reads never wait for writes, and a long report sees one consistent picture.

4

What to watch in production

  • Long open transactions. One session left in a transaction for hours keeps every dead row created since it began. Tables and indexes bloat, and vacuum reclaims nothing.
  • HOT updates. If an update changes no indexed column and the page has room, the new version stays on the same page and the indexes are not touched. A lower fillfactor leaves that room.
SELECT pid, state, xact_start, now() - xact_start AS open_for, left(query, 60)
FROM pg_stat_activity
WHERE xact_start IS NOT NULL
ORDER BY xact_start LIMIT 5;

The same idea elsewhere: InnoDB updates the row in place and keeps old versions in the undo log. MongoDB's WiredTiger keeps a chain of updates in memory.

Explained clearly

Vacuum: cleaning up after every update

Listen, 2 min 56 s

Watch it first, then read the details:

1

The problem

Every update and delete leaves a dead row version in the table. Left alone, tables and indexes grow and scans step over more and more garbage. Transaction IDs are 32 bits and wrap around, so old rows also need marking before that happens.

2

What it is

VACUUM removes row versions no transaction can see, removes their index entries, and records the free space so new rows can reuse it. It also updates the visibility map, which index-only scans rely on, and freezes old rows so wraparound never confuses them. It does not shrink the file. VACUUM FULL does, under a lock that blocks all reads and writes.

3

Follow one request

  1. Updates leave dead versions behind.
  2. Autovacuum wakes a table when dead rows pass 50 + 20% of the table (autovacuum_vacuum_threshold, autovacuum_vacuum_scale_factor).
  3. It removes dead versions older than the oldest running snapshot.
  4. The space goes into the free space map. The next insert reuses it.

For your app: vacuum keeps tables from growing on every update, but only removes what no one can still see.

4

What to watch in production

  • Dead rows that never go down. Something holds the horizon back: a long transaction, a replication slot, or a standby with hot_standby_feedback running a long query.
  • Big tables vacuumed too late. 20% of a billion rows is 200 million dead rows. Give large, busy tables their own lower scale factor.
  • Wraparound age. Watch age(datfrozenxid). If freezing falls far behind, PostgreSQL stops accepting new transactions to protect the data.
  • Shrinking a bloated table. Use pg_repack online, not VACUUM FULL on a live table.
SELECT relname, n_live_tup, n_dead_tup, last_autovacuum
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC LIMIT 10;
SELECT datname, age(datfrozenxid) FROM pg_database ORDER BY 2 DESC;

The same idea elsewhere: InnoDB's purge threads clear old versions from the undo log. MongoDB's WiredTiger reuses space inside its files.

Next · chapter 4High availabilityReplication, failover and Patroni← Chapter 2: How it stores your data
Part 1 of 4 · Learn · 56 pagesAll pages

How do databases actually work? From one row on disk to transactions: the words you need, PostgreSQL, MySQL and MongoDB from the files up, then Redis, Cassandra and vector search, side by side, and the query and concurrency traps.

Start 1: the basicsStart 2: ten conceptsStart 3: how a query travelsStart 4: napkin mathThe courseShort videosPostgreSQL 1: why PostgreSQLPostgreSQL 2: how it stores your dataPostgreSQL 3: what happens on every writePostgreSQL 4: high availability with PatroniPostgreSQL 5: running it as a DBREPostgreSQL 6: when it breaksPostgreSQL on Kubernetes: CloudNativePGMySQL 1: why MySQLMySQL 2: how it stores your dataMySQL 3: what happens on every writeMySQL 4: high availability with InnoDB ClusterMySQL 5: running it as a DBREMySQL 6: when it breaksMySQL failover with OrchestratorMySQL on Kubernetes: the Percona operatorsMongoDB 1: why MongoDBMongoDB 2: how it stores your dataMongoDB 3: what happens on every writeMongoDB 4: high availability with replica setsMongoDB 5: running it as a DBREMongoDB 6: when it breaksMongoDB on Kubernetes: the Percona operatorB-tree and LSM treeRedis 1: why RedisRedis 2: how it stores your dataRedis 3: high availabilityRedis 4: running it as a DBRERedis 5: when it breaksCassandra 1: why CassandraCassandra 2: how it stores your dataCassandra 3: high availabilityCassandra 4: running it as a DBRECassandra 5: when it breaksVector databases 1: why vector searchVector databases 2: how it stores your dataVector databases 3: high availabilityVector databases 4: running it as a DBREVector databases 5: when it breaksDatabase familiesEngines side by sideQueries that look fine and are notLost updates and write skewMany servers 1: keep a copy runningMany servers 2: who is the leaderMany servers 3: CAP as settingsMany servers 4: unique IDsMany servers 5: split the dataMany servers 6: across servicesMany servers 7: a thousand databasesStaff path, zero to architect