MVCC, WAL and logical decoding
Part of the free LogicWiz Data Engineering course, Module 6: Batch pipelines. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is Wednesday, 18:05, and SwiftKart has stopped taking orders. Dana reads the error out loud: the database's disk is full. Not with orders: with 200 GB of log files. The trail leads to your CDC connector. It crashed on Friday at 18:00 and nobody noticed, and Postgres has kept every change since, for a reader that never came back. Nora says: "Before you restart it, find out why the database was keeping that log."
You'll learn to
- Explain how an UPDATE creates versions, and which one a query sees
- Say what VACUUM removes, and what stops it
- Follow one change from the WAL through a slot to CDC
- Find and fix a replication slot that is holding WAL
Learn
An UPDATE never overwrites a row
Start with what Postgres does on every write. The rest of the case follows from it.
Postgres never changes a row in place. An UPDATE writes a new copy of the row and marks the old copy as replaced. A DELETE only marks. One stored copy of a row is called a tuple, and every tuple carries three labels:
xmin: the id of the transaction that created it;xmax: the id of the transaction that deleted or locked it (0 if none);ctid: its address, as (page, place on the page).
Why keep the old copy? So that a query that was already reading can go on reading it while the writer works. Readers never block writers, and writers never block readers. The design is called MVCC: multi-version concurrency control.
Heap page 0 of acct after one UPDATE
An 8 KB heap page with its header, four line pointers, free space and four tuples; the old version of Jonas in Berlin has xmax set by the transaction that wrote the new Munich version.
Read the tuples from the bottom up. Transaction 754 inserted three rows. Transaction 755 then updated Jonas: the old copy at (0,1) got xmax 755, and a new copy appeared at (0,4). Only a column without an index changed and the page had room, so the index still points at (0,1), which leads on to (0,4). Postgres calls that a HOT update (heap-only tuple).
See xmin, xmax and ctid
SELECT ctid, xmin, xmax, * FROM acct ORDER BY id;
UPDATE acct SET city = 'Munich' WHERE id = 1;
SELECT ctid, xmin, xmax, * FROM acct ORDER BY id;
-- A delete that is rolled back still leaves its mark
BEGIN;
DELETE FROM acct WHERE id = 2;
ROLLBACK;
SELECT ctid, xmin, xmax, pg_xact_status(xmax::text::xid8) AS deleter, *
FROM acct
ORDER BY id;
SELECT pg_current_xact_id() AS my_xid, pg_current_snapshot() AS snapshot;
Transaction ids depend on everything this browser's database has run, so yours differ. The pattern does not. After the UPDATE, Jonas is at (0,4) with a new xmin. Amara keeps the xmax of a delete that was rolled back, and she is still visible: pg_xact_status says aborted. So a non-zero xmax alone does not mean "deleted".
Each reader gets its own photo
Two copies of Jonas are on the page. Which one does a query see? That depends on when the query looked.
Every query reads through a snapshot: a note of which transactions had finished at one instant. Think of a photo of the table. Changes committed after the photo was taken are not in it. A tuple is visible in a snapshot if the transaction that created it had committed by then, and no transaction that deleted it had.
The isolation level decides how often a new photo is taken:
- READ COMMITTED, the default: a new snapshot for every statement.
- REPEATABLE READ: one snapshot for the whole transaction.
Two concurrent transactions each read the table through their own snapshot: one sees the old version of a row and the other the new one, depending on which commits each snapshot includes.
Step through it once as Read Committed and once as Repeatable Read, and compare what each transaction sees. This is why Debezium copies every table inside one REPEATABLE READ transaction (Lesson 6.5): all the tables are read as of the same instant.
Cleaning up the old versions
The price of MVCC is the old copies. Once no snapshot can still see one, it is a dead tuple: it takes up space and helps nobody.
VACUUM is the cleaner. It walks the table and removes dead tuples that are older than every snapshot still open. That line, "older than every open snapshot", is called the xmin horizon. VACUUM then notes the freed space, so new rows can reuse it.
It does not hand the space back to the operating system, except for empty pages at the very end of the file. A table that once held 10 GB and now holds 1 GB of live rows stays 10 GB on disk. Only VACUUM FULL rewrites it smaller, and while it does, it locks the table against reads and writes.
Tuple versions on a heap page with xmin and xmax: an UPDATE writes a new version and marks the old one, which becomes a dead tuple until VACUUM removes it.
Press Next step through to the end: the UPDATE writes a new version, the old one gets an xmax and becomes a dead tuple, and VACUUM removes it.
One open transaction stops the cleaner
Nobody runs VACUUM by hand. A background process, autovacuum, cleans a table once enough dead tuples pile up: by default, 50 plus 20% of its rows. For a table of 10 million rows that is 50 + 0.2 x 10,000,000 = 2,000,050 dead tuples.
But remember the rule: VACUUM may only remove tuples older than the oldest snapshot anywhere on the server. One session left idle in transaction for six days. One six-hour REPEATABLE READ export. A replication slot pinned to an old position. In each case autovacuum runs on time and frees nothing, and every busy table on the server swells. That swelling is called bloat.
The guard is a timeout that ends such sessions: idle_in_transaction_session_timeout.
Remember: an UPDATE adds a version, a snapshot picks a version, and VACUUM removes the versions nobody can pick. A transaction left open keeps them all alive.
Dead tuples before autovacuum starts (Postgres 18 defaults)
Bars show how many dead tuples a table must collect before autovacuum runs, for tables of ten thousand, one million, ten million and one billion rows; the billion-row table is capped at one hundred million.
Each bar is how many dead tuples a table collects before autovacuum starts. The amber bar is capped: Postgres 18 added a ceiling of 100,000,000. Big, busy tables usually get their own lower setting: ALTER TABLE orders SET (autovacuum_vacuum_scale_factor = 0.02).
Every change is written to a log first
Versions explain what readers see. They do not explain 200 GB of log. For that, look at how Postgres survives a crash.
Before a changed page may be written to the table's file, a record of the change must be in a log: the write-ahead log, or WAL. At COMMIT, Postgres forces the WAL to disk and only then answers OK. After a crash it replays the WAL, so committed work is never lost. Think of a ship's logbook: every event is written down, in order, as it happens.
A position in the WAL is an LSN (log sequence number): a byte offset, printed like 0/16EF9D0. The WAL lives in 16 MB files called segments, in the folder pg_wal/. Old segments are recycled once nothing needs them any more. Hold on to that last sentence.
The life of one committed change
Four steps: an update changes a page in memory and appends a WAL record, the commit flushes the WAL to disk, a later checkpoint writes the page, and old WAL is recycled unless a slot or setting still needs it.
Read it top to bottom. A checkpoint is the moment Postgres writes the changed pages to the data files, after which older WAL is no longer needed for recovery. The amber step is where SwiftKart's disk filled up: look at the word "unless".
Watch the WAL grow
SELECT pg_current_wal_lsn() AS before_lsn;
CREATE TABLE clicks AS
SELECT g AS id, md5(g::text) AS payload
FROM generate_series(1, 10000) AS g;
SELECT pg_current_wal_lsn() AS after_lsn,
pg_walfile_name(pg_current_wal_lsn()) AS segment_file;
-- An application can write its own record into the WAL, for CDC readers
SELECT pg_logical_emit_message(true, 'swiftkart', 'nightly load done') AS message_lsn;
Subtract the two LSNs with pg_wal_lsn_diff(after, before) to get bytes: about a megabyte for 10,000 small rows. The values change with every run. The last line writes a message of your own into the WAL, which only a CDC reader sees. Debezium turns it into an op: "m" event: handy as a marker such as "batch 42 done".
Each change appends a WAL record with a growing LSN, and the records are read back as logical change events, the source of CDC.
Press Next step a few times: each change appends a WAL record with a higher LSN. Then watch the same records read back as change events. That reading-back is the next section.
Reading the log back as rows
The WAL was built for crash recovery. But it holds every change, in order, which is exactly what CDC wants.
Turning WAL records back into "this row was inserted, updated, deleted" is called logical decoding. Postgres can do it when wal_level = logical. A small plugin picks the output format: pgoutput is the built-in one, and test_decoding prints plain text for demos.
The reader needs a bookmark, and the server keeps it: a replication slot. It holds two positions. confirmed_flush_lsn is how far the reader has confirmed. restart_lsn is the oldest WAL the reader may still need, and the server promises to keep everything from there on.
This browser's Postgres runs at wal_level = replica, so the real session is shown below, not run.
test_decoding on a Postgres with wal_level = logical
Runs on your laptop:
CREATE TABLE customers (customer_id INT PRIMARY KEY, name TEXT, city TEXT);
INSERT INTO customers VALUES (18, 'Jonas Weber', 'Berlin'), (29, 'Maya Chen', 'Toronto');
SELECT * FROM pg_create_logical_replication_slot('demo', 'test_decoding');
UPDATE customers SET city = 'Munich' WHERE customer_id = 18;
DELETE FROM customers WHERE customer_id = 29;
SELECT * FROM pg_logical_slot_get_changes('demo', NULL, NULL);
SELECT pg_drop_replication_slot('demo');
lsn | xid | data
-----------+------+-------------------------------------------------------------------------
0/1A3F2A0 | 7731 | BEGIN 7731
0/1A3F2D8 | 7731 | table public.customers: UPDATE: customer_id[integer]:18 name[text]:'Jonas Weber' city[text]:'Munich'
0/1A3F3B0 | 7731 | COMMIT 7731
0/1A3F3E8 | 7732 | BEGIN 7732
0/1A3F420 | 7732 | table public.customers: DELETE: customer_id[integer]:29
0/1A3F458 | 7732 | COMMIT 7732
(6 rows)
Read the data column: each transaction arrives as BEGIN, its changes, COMMIT, in commit order. The insert from before the slot existed is not there: a slot only sees WAL written after it was created. The delete carries only the primary key, because the table's replica identity is the default (Lesson 6.5). pg_logical_slot_get_changes consumes the changes; pg_logical_slot_peek_changes reads without moving the slot. LSNs and transaction ids differ on every server.
The bookmark nobody moved
Now Wednesday's outage explains itself.
The connector crashed on Friday at 18:00. Its slot stayed. A slot with no reader is inactive, and its restart_lsn never moves. The server keeps its promise: it holds every WAL segment written since. Not only the changes to the captured tables. All of them.
SwiftKart writes about 40 GB of WAL a day, and the disk had 200 GB free. 200 / 40 = 5 days. Friday 18:00 plus five days is Wednesday 18:00. With no room to write WAL, Postgres stops.
A stuck logical slot does a second kind of damage as well: it stops VACUUM from cleaning the system catalogs.
A slot with no reader, day by day
A replication slot and the pg_wal volume over a week: while the connector reads, no WAL is held; after it crashes the held WAL grows by 40 GB a day until the 200 GB volume is full; with a 100 GB cap the slot is invalidated and the WAL is released.
Thursday: a healthy slot. The connector reads and confirms. The slot's
restart_lsnmoves forward, so old segments are recycled and the volume stays nearly empty.Friday 18:00: the connector crashes. The slot stays behind, inactive. Its
restart_lsnis frozen at Friday 18:00.Monday 18:00. Three days of writes at 40 GB a day. Nothing after
restart_lsnmay be recycled, so 120 GB of WAL is held for a reader that is not there.Wednesday 18:00. 200 GB held, nothing free. Postgres cannot write WAL, so it cannot commit anything. The store stops taking orders.
The same week with a cap. With
max_slot_wal_keep_size = 100GBthe slot is invalidated on Monday morning, after 2.5 days, and its WAL is released. The connector must take a new snapshot, but the database never stops.
Watch the two boxes inside the volume trade places. Days to full = free space / WAL per day = 200 / 40 = 5.
A slot holds WAL for a reader that never comes
-- Clean up a slot an earlier run may have left
SELECT pg_drop_replication_slot(slot_name)
FROM pg_replication_slots
WHERE slot_name = 'abandoned_cdc';
-- A physical slot that reserves WAL from now on (the mechanism logical slots share)
SELECT slot_name, lsn AS restart_lsn
FROM pg_create_physical_replication_slot('abandoned_cdc', true);
-- Nobody reads from it; the shop keeps writing
CREATE TABLE clicks AS
SELECT g AS id, md5(g::text) AS payload
FROM generate_series(1, 20000) AS g;
SELECT slot_name, active, wal_status,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS wal_held
FROM pg_replication_slots;
SELECT pg_drop_replication_slot('abandoned_cdc');
The slot is inactive and its restart_lsn stays put, so wal_held grows with every write. (This is a physical slot, the kind replicas use; a logical slot holds WAL by the same mechanism.) A slot belongs to the whole server, not to a schema, so this card drops it at the end. The sizes depend on what ran before.
The trap: a replication slot is a promise to keep WAL until someone reads it. Teams create one for a CDC trial, the trial ends, the slot stays, and weeks later the database runs out of disk. Every slot needs an owner, an alert on pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn), and a cap with max_slot_wal_keep_size. The same goes for long transactions: an export that keeps a snapshot open for hours bloats every busy table on the server.
Remember: a lost slot costs you a new snapshot. A full disk costs you the store. Cap every slot.
Numbers to remember
| Name | Value | What it is |
|---|---|---|
| pgcurrentsnapshot() | xmin:xmax:in-progress list | The oldest transaction still running, the next id to be handed out, and the ids in progress between them |
| Isolation levels | READ COMMITTED is the default | REPEATABLE READ fails an update of a row that another transaction changed and committed meanwhile: could not serialize access due to concurrent update. SERIALIZABLE adds checks that fail with could not serialize access due to read/write dependencies among transactions. READ UNCOMMITTED behaves like READ COMMITTED |
| What else VACUUM does | free space map, visibility map, freezing | Records freed space for reuse, sets the bits that make index-only scans possible, and freezes old tuples so their 32-bit transaction ids can be reused. VACUUM FULL (or a tool like pgrepack) rewrites the file; VACUUM FULL holds an ACCESS EXCLUSIVE lock |
| Autovacuum starts at | autovacuumvacuumthreshold (50) + autovacuumvacuumscalefactor (0.2) x rows | Postgres 18 adds a cap, autovacuumvacuummaxthreshold (default 100,000,000) |
| idleintransactionsessiontimeout, transactiontimeout | both 0 (off) by default | transactiontimeout exists since Postgres 17 |
| autovacuumfreezemaxage | 200 million | If freezing falls far behind, Postgres refuses new ids: database is not accepting commands that assign new transaction IDs to avoid wraparound data loss |
| synchronouscommit | on by default | COMMIT waits until the WAL is flushed to disk |
| wallevel | minimal, replica (the default), logical | logical adds what is needed to decode changes back into rows |
| Output plugins | pgoutput, testdecoding, decoderbufs | pgoutput is what native logical replication uses (CREATE PUBLICATION, CREATE SUBSCRIPTION). Debezium supports pgoutput and decoderbufs (its documented default) |
| logicaldecodingworkmem | 64 MB by default | A bigger transaction spills to disk or, since Postgres 14, can be streamed before it commits |
| maxslotwalkeepsize | Postgres 13 and later; default -1 (unlimited) | Past it the slot is invalidated (walstatus = lost) and the connector must take a new snapshot |
| idlereplicationslottimeout | Postgres 18; default 0 (off) | Invalidates slots that have been inactive that long, at a checkpoint |
| Debezium heartbeat.interval.ms | default 0 (off) | Turn it on so the slot advances when the captured tables are quiet but the server is busy |
| Failover slots | Postgres 17 | Before 17, slots lived only on the primary, so a failover lost them and forced a new snapshot. 17 can synchronize them to a standby |
| Who reads through a logical slot | Debezium, AWS DMS, Fivetran, Airbyte's CDC mode | Managed database services make you switch on logical replication as a parameter first |
A long table, because this lesson sits on three mechanisms. The rows you will reach for first are max_slot_wal_keep_size and the two timeouts.
What changed at SwiftKart
Dana drops the dead slot, the WAL is recycled, and orders flow again. You restart the connector, and it takes a new snapshot.
Then the guards go in. max_slot_wal_keep_size caps what any slot may hold. An alert fires on every inactive slot and on the WAL held per slot. Debezium sends heartbeats, so the slot keeps moving on quiet days. Sessions idle in a transaction are timed out, so no forgotten export can stop VACUUM. And every slot has an owner.
That ends Module 6. You can land data, load only what changed, rerun safely, catch late rows and capture every change, down to the log it comes from. But is the data right? Module 7 starts with the six checks every table should pass.
In one line
Postgres keeps row versions that snapshots choose between and VACUUM later removes; every change goes to the WAL first, a logical slot decodes it in commit order for CDC, and a slot nobody reads keeps WAL until the disk is full.
Interview corner
What happens inside Postgres when you UPDATE a row?
It writes a new tuple with xmin = my transaction id and sets xmax on the old tuple; with a HOT update the new version goes on the same page and the indexes are untouched. A WAL record for the change goes into the WAL buffers and is flushed at commit before the client gets OK. Other sessions keep seeing the old version until their snapshot includes my commit. The old tuple becomes dead and is removed by VACUUM once no snapshot can see it.
The primary's disk is filling up and pg_wal is 300 GB. How do you diagnose and fix it?
I check pg_replication_slots: an inactive slot whose restart_lsn is far behind pg_current_wal_lsn() pins every WAL segment since then; pg_wal_lsn_diff gives the bytes. Other causes are a large wal_keep_size, failing WAL archiving, or checkpoints not completing. For a dead slot I either restart its consumer or drop it, accepting a re-snapshot for that connector. Then I set max_slot_wal_keep_size, alert on slot lag and inactive slots, and enable heartbeats for quiet captured tables.
Why can one long-running transaction make every table on a server bloat?
VACUUM may only remove tuple versions that no open snapshot could still see, and the oldest snapshot on the server sets that horizon. A session idle in transaction for days, or a long REPEATABLE READ export, keeps the horizon at its start, so every update and delete since leaves a dead tuple that cannot be removed. Autovacuum keeps running and frees nothing. I find it in pg_stat_activity by xact_start, end it, and set idle_in_transaction_session_timeout or transaction_timeout.
How does logical decoding order changes from concurrent transactions?
In the WAL, changes from concurrent transactions are interleaved in the order they were written. The decoder buffers each transaction's changes and emits them all at its commit, so the output is in commit order and rolled-back transactions never appear; big transactions spill to disk past logical_decoding_work_mem or, since Postgres 14, can be streamed. For a consumer that means a transaction arrives whole and in commit order, but in Kafka it may be split across partitions by key, so the sink should still apply per key by LSN.