Sub topic 2
How the WAL becomes a stream of row changes
This chapter assumes you know what the write-ahead log (WAL) is, can run psql, and can edit postgresql.conf. It explains how PostgreSQL turns the WAL, a record of physical page changes, into a stream of row-level inserts, updates, and deletes that a subscriber can apply. Later chapters build on this model.
Why the WAL needs translating
Before PostgreSQL changes a data page, it writes a WAL record that describes the change. Crash recovery and physical (streaming) replication replay these records against the same on-disk layout. A typical record says "in block 42 of relation file 16384, put these bytes at this offset."
That description is useless to a different database. A subscriber may have a different major version, different physical layout, or only some of the tables. It needs the logical meaning: "row with id 1 in public.orders was updated, and status is now shipped."
Logical decoding is the process that reconstructs this meaning from the WAL. It runs on the publisher, inside the server, and produces a stream of changes in commit order.
What wal_level = logical adds
At the default wal_level = replica, WAL records carry enough data for recovery and physical standbys. They do not always carry what a decoder needs, such as the old key values of an updated or deleted row. Setting wal_level = logical makes PostgreSQL log extra information:
- The identifying columns of the old row for
UPDATEandDELETE, as chosen by the table's replica identity (covered in a later chapter). - Enough catalog-related information to map physical records back to tables and columns.
The cost is somewhat larger WAL volume. The setting needs a server restart, and it is a superset of replica, so physical replication and archiving keep working.
The decoding pipeline
Decoding happens in a few stages. A WAL sender process on the publisher runs them for each connected consumer.
- Reading the WAL. The walsender reads WAL records in the order they were written. Records from many concurrent transactions are interleaved.
- Reordering. The decoder collects each transaction's changes in a reorder buffer, keyed by transaction ID. When it sees a commit record, it releases that transaction's changes as one unit. If it sees an abort, it throws the changes away. Consumers therefore see only committed data, and transactions arrive in commit order, not in the order they started.
- Interpreting records. To turn a record into "table X, column values Y," the decoder needs the table definition as it existed when the change was made. It uses a historic catalog snapshot, so a row written before an
ALTER TABLEis still decoded with the old column layout. - Output plugin. An output plugin turns the decoded changes into a wire or text format. Logical replication uses the built-in
pgoutputplugin. Other plugins such astest_decoding(a debugging aid shipped incontrib) andwal2json(a separate extension) target other uses. - Delivery and confirmation. The stream goes to the consumer. The consumer reports how far it has safely processed, and the replication slot records that position.
Seeing decoded changes yourself
You can watch decoding without setting up replication. The test_decoding plugin and the SQL interface to slots let you read the stream with a query. This needs wal_level = logical and a role with the REPLICATION attribute or superuser rights. Run it on a scratch database, not on production.
CREATE TABLE demo (id int PRIMARY KEY, note text);
-- Create a logical slot that uses the test_decoding plugin
SELECT pg_create_logical_replication_slot('demo_slot', 'test_decoding');
INSERT INTO demo VALUES (1, 'first');
UPDATE demo SET note = 'changed' WHERE id = 1;
DELETE FROM demo WHERE id = 1;
-- Read and consume the changes accumulated since the slot was created
SELECT lsn, xid, data
FROM pg_logical_slot_get_changes('demo_slot', NULL, NULL);
-- Always clean up: an unused slot retains WAL
SELECT pg_drop_replication_slot('demo_slot');The data column contains lines like these:
BEGIN 751
table public.demo: INSERT: id[integer]:1 note[text]:'first'
COMMIT 751
BEGIN 752
table public.demo: UPDATE: id[integer]:1 note[text]:'changed'
COMMIT 752
BEGIN 753
table public.demo: DELETE: id[integer]:1
COMMIT 753Transaction IDs will differ on your system. Each statement ran in its own implicit transaction, so each change sits in its own BEGIN/COMMIT pair. Wrap the statements in one BEGIN; ... COMMIT; and you get a single group.
Three things to notice:
- The
CREATE TABLEdoes not appear. DDL is not part of the decoded stream. - The
DELETEcarries only the key (id), because the primary key is the replica identity. pg_logical_slot_get_changesconsumes the changes. Calling it again returns nothing new. Usepg_logical_slot_peek_changesto read without consuming.
Slots hold the decoder's place
A logical decoding session must be able to resume exactly where it stopped, so PostgreSQL stores its position in a replication slot. A slot persists across disconnects and restarts. It prevents the server from removing WAL the consumer has not yet confirmed, and it prevents cleanup of catalog rows the decoder still needs.
Two slot positions matter:
| Column in `pg_replication_slots` | Meaning |
|---|---|
| `restart_lsn` | The oldest WAL the slot may still need. WAL from here onward is retained. |
| `confirmed_flush_lsn` | The position up to which the consumer has confirmed receipt. Changes before it are not sent again. |
The next chapters cover slot management in detail. For now, remember the consequence: decoding is only as safe as the slot is attended. A slot whose consumer has gone away keeps pinning WAL until someone drops it.
Large and in-flight transactions
Because changes are released only at commit, the reorder buffer must hold a whole transaction's changes in memory. This has practical effects.
- Memory limit. The setting
logical_decoding_work_mem(default 64MB) caps the buffer memory per decoding session. Above it, the decoder spills changes to disk files under the slot's directory inpg_replslot. Big transactions therefore cost extra I/O on the publisher. - Latency. A transaction that runs for ten minutes and then commits reaches the subscriber only after the commit. The subscriber then applies it in one burst.
- Streaming option. From PostgreSQL 14, a subscription can ask for
streaming = on. The publisher then sends large in-progress transactions in chunks before they commit. The subscriber still applies them only after the commit arrives. This reduces publisher spill and lag, and it does not change which transactions become visible. - Aborts are cheap to ignore, not free. A rolled-back transaction is discarded at decode time and never reaches the subscriber, but the walsender still read its WAL records.
What is and is not in the stream
Decoding produces row changes for ordinary tables. The mapping is simple.
| Source operation | Decoded as |
|---|---|
| `INSERT` | Insert with all column values of the new row |
| `UPDATE` | Update with the new row, plus old key values when the key changed or the replica identity requires them |
| `DELETE` | Delete with the old key values |
| `TRUNCATE` | Truncate of the listed tables (PostgreSQL 11 and later, when published) |
Several things never appear:
- DDL such as
CREATE TABLE,ALTER TABLE, andCREATE INDEX. - Sequence advances. The tables that use a sequence replicate with the value already chosen, but the sequence's own state on the subscriber stays where it was.
- Large objects.
- Changes to unlogged tables, temporary tables, and system catalogs.
Unchanged TOASTed values (large values stored out of line) are not written to the WAL on an update that leaves them alone. The decoder marks them as unchanged, and the subscriber keeps its existing value. This works for logical replication into a copy of the same table, and it is one reason decoding output from test_decoding can show unchanged-toast-datum.
Resource settings that decoding depends on
| Setting | Where | Role in decoding |
|---|---|---|
| `wal_level = logical` | Publisher | Adds the information a decoder needs. Requires restart. |
| `max_replication_slots` | Publisher | Upper bound on slots, including those for decoding. |
| `max_wal_senders` | Publisher | Each logical consumer holds a walsender process. |
| `logical_decoding_work_mem` | Publisher | Reorder buffer limit before spilling to disk. |
| `max_slot_wal_keep_size` | Publisher (PostgreSQL 13 and later) | Caps WAL retained for slots. A slot that falls behind the cap is invalidated. |
You can confirm the first setting quickly:
SHOW wal_level;
SHOW logical_decoding_work_mem;Common errors
logical decoding requires wal_level >= logical. You created a logical slot whilewal_levelwasreplica. Change the setting and restart the server.replication slot "x" is active for PID n. Only one consumer can read a slot at a time. Stop the other consumer first.- Output shows only keys for deletes. This is expected with the primary key as the replica identity, not a bug.
- Disk usage grows in
pg_walandpg_replslot. A stalled or abandoned slot, or a very large open transaction, is the usual cause.
Exercise
A transaction inserts 100 rows into a published table and then rolls back. A second transaction that started later inserts one row and commits. What does a logical consumer receive, and in what form?
Show answer
The consumer receives only the second transaction: its one inserted row, delivered as a single committed transaction. The decoder buffers each transaction's changes, discards the rolled-back transaction when it sees the abort record, and releases the second transaction when it sees its commit. The 100 rows never reach the subscriber.
Exercise
You run SELECT * FROM pglogicalslotgetchanges('demo_slot', NULL, NULL) twice in a row with no writes in between. Why is the second result empty, and which function would let you read the same changes repeatedly?
Show answer
The getchanges function consumes the changes and advances the slot's confirmed position, so the second call finds nothing new. pglogicalslotpeek_changes returns the same changes without advancing the slot.