Logical Decoding and the Write-Ahead Log
See how PostgreSQL turns its write-ahead log into row changes: log sequence numbers, replication slots, commit order, peek versus get, replica identity for updates and deletes, the pgoutput plugin and publications, and the rights a CDC reader needs.
Contentsand lesson path
On this page
- Why it matters
- The write-ahead log and log positions
- Slots, commit order, peek and get
- What updates and deletes carry: replica identity
- pgoutput, publications and the rights a reader needs
- Check your understanding
- Apply it
- Review prompt
Lessons of Change Data Capture
- Three Ways to Detect That Data Changed Concept · 20 min
- Logical Decoding and the Write-Ahead Log Concept · 20 min
- Lab: PostgreSQL to Kafka with Debezium Lab · 30 min
- Worked Example: Applying Changes in Order with MERGE Worked example · 25 min
- Snapshots, Schema Changes and Slot Lag Concept · 20 min
- Check: CDC Failure Modes Knowledge check · 8 questions
What you will learn
- Configure log-based CDC from PostgreSQL (logical replication slot and Debezium on Kafka Connect) and interpret create, update, delete and tombstone events.
- Handle the initial snapshot, source schema changes and replication-slot lag without losing or duplicating changes.
Prerequisites: Messaging & Event Streaming
01. Why it matters
Debezium and similar tools do not invent change events. They ask PostgreSQL for them, through a feature called logical decoding, and then reshape what they receive. Almost every surprise in a CDC pipeline traces back to how that feature works: an update event without the old values, a delete that carries only a key, a disk that fills while a connector is down, or a connector that cannot start because of a missing right.
In this lesson you use logical decoding directly, with plain SQL, on the cdc-demo container from the previous lesson. If you removed it, start it again with the docker run command from there. Each step is small, and each one explains one behaviour you will meet again in the Debezium lab.
02. The write-ahead log and log positions
PostgreSQL writes every change to the write-ahead log (WAL) before it changes the data files. After a crash, the server replays the WAL to repair the data files, and standby servers stay in sync by receiving the same WAL. Every position in the WAL has an address, the log sequence number (LSN). It is a byte offset written as two hexadecimal numbers, such as 0/1A2B3C8. LSNs only grow, so a larger LSN always means a later point in the log, and pg_wal_lsn_diff(a, b) gives the number of bytes between two positions.
The amount of detail in the WAL depends on the wal_level setting. The default, replica, is enough for crash recovery and physical standbys, which copy blocks of data files. Logical decoding turns the WAL back into row changes ("row 7 of table orders now has status paid"), so it needs more: with wal_level = logical, PostgreSQL also logs the extra information that decoding needs, such as the old key of a row that was updated or deleted. Changing wal_level needs a server restart, which is why the container was started with -c wal_level=logical.
cd cdc-demo
docker exec cdc-demo psql -U postgres -X -q \
-c "SHOW wal_level" -c "SELECT pg_current_wal_lsn() AS now_at" wal_level
-----------
logical
(1 row)
now_at
-----------
0/1A2B3C8
(1 row)03. Slots, commit order, peek and get
A reader of logical changes uses a replication slot. The slot stores two things on the server: the output plugin that formats changes, and the position up to which the reader has confirmed it has the changes. The slot survives restarts of the reader and of the server. That is what lets a CDC connector stop on Friday and continue on Monday without missing anything, and it is also why a forgotten slot is dangerous, as you will see later.
The script below creates a slot and then runs three transactions. The first is rolled back. The second starts first, but before it commits, a second session (opened with the dblink extension) inserts and commits a row. Then the script reads the slot twice: once with peek, which looks without consuming, and once with get, which consumes and moves the slot forward.
CREATE EXTENSION dblink; -- lets this session run SQL in a second session
CREATE TABLE stock (sku text PRIMARY KEY, qty int NOT NULL);
INSERT INTO stock VALUES ('A1', 5);
SELECT slot_name FROM pg_create_logical_replication_slot('walk', 'test_decoding');
BEGIN; -- 1. rolled back
INSERT INTO stock VALUES ('X9', 1);
ROLLBACK;
BEGIN; -- 2. starts first, commits last
UPDATE stock SET qty = qty - 1 WHERE sku = 'A1';
INSERT INTO stock VALUES ('B2', 8);
SELECT dblink_exec('dbname=postgres', -- 3. commits in between
$$INSERT INTO stock VALUES ('C3', 1)$$) AS other_session;
COMMIT;
\echo peek: read without consuming
SELECT data FROM pg_logical_slot_peek_changes('walk', NULL, NULL, 'include-xids', '0');
\echo get: consume, then ask again
SELECT count(*) AS got FROM pg_logical_slot_get_changes('walk', NULL, NULL);
SELECT count(*) AS got_again FROM pg_logical_slot_get_changes('walk', NULL, NULL);docker exec -i cdc-demo psql -U postgres -X -q < decode.sql slot_name
-----------
walk
(1 row)
other_session
---------------
INSERT 0 1
(1 row)
peek: read without consuming
data
-----------------------------------------------------------
BEGIN
table public.stock: INSERT: sku[text]:'C3' qty[integer]:1
COMMIT
BEGIN
table public.stock: UPDATE: sku[text]:'A1' qty[integer]:4
table public.stock: INSERT: sku[text]:'B2' qty[integer]:8
COMMIT
(7 rows)
get: consume, then ask again
got
-----
7
(1 row)
got_again
-----------
0
(1 row)Three rules are visible here.
- Only committed work is decoded. The rolled-back
X9never appears. A CDC consumer never has to undo a change that did not happen. - Transactions arrive whole, in commit order.
C3committed first, so it is decoded first, even though transaction 2 started earlier and changedA1beforeC3existed. The changes of transaction 2 arrive together between its ownBEGINandCOMMIT. Commit order is also why the order of events for one row is reliable: two transactions cannot change the same row at the same time (the second waits for the first to finish), so the transaction that changes a row second also commits second. - Reading is a decision about the slot.
peekshowed seven lines and left them in the slot.getreturned the same seven lines and confirmed them, so the secondgetfound nothing. A real CDC reader confirms a position only after it has stored the changes safely downstream. If you debug a production slot withget, the connector that owns the slot will never see those changes.
04. What updates and deletes carry: replica identity
An insert is easy to decode: the WAL has the new row. For an update or a delete, a consumer also needs to know which row changed, and sometimes what it looked like before. The table setting REPLICA IDENTITY decides how much of the old row PostgreSQL writes to the WAL. With DEFAULT, it writes the old primary key, and only when the key itself changes or the row is deleted. With FULL, it writes the whole old row for every update and delete, which costs more WAL. The script changes B2 and deletes a row under each setting. substr cuts off the table name, and the two parts of the long update line are split for the page.
UPDATE stock SET qty = 7 WHERE sku = 'B2'; -- REPLICA IDENTITY DEFAULT
DELETE FROM stock WHERE sku = 'C3';
ALTER TABLE stock REPLICA IDENTITY FULL;
UPDATE stock SET qty = 6 WHERE sku = 'B2'; -- REPLICA IDENTITY FULL
DELETE FROM stock WHERE sku = 'A1';
\pset tuples_only on
\pset format unaligned
SELECT replace(substr(data, 21), ' new-tuple:', E'\n new-tuple:')
FROM pg_logical_slot_get_changes('walk', NULL, NULL)
WHERE data LIKE 'table%';docker exec -i cdc-demo psql -U postgres -X -q < identity.sqlUPDATE: sku[text]:'B2' qty[integer]:7
DELETE: sku[text]:'C3'
UPDATE: old-key: sku[text]:'B2' qty[integer]:7
new-tuple: sku[text]:'B2' qty[integer]:6
DELETE: sku[text]:'A1' qty[integer]:4Under DEFAULT, the update of B2 carries only the new row, and the delete of C3 carries only its key. A consumer can apply both: it finds the row by key and replaces or removes it. It cannot tell that the quantity went from 8 to 7, and it cannot learn anything else about the deleted row. Under FULL, the update shows the old-key (here the whole old row) and the new-tuple, and the delete carries the full old row. Choose FULL when consumers need the old values, for example an audit trail or a stream that computes differences, and accept the extra WAL. Debezium maps this directly: its before field is filled from whatever old data the WAL holds.
05. pgoutput, publications and the rights a reader needs
test_decoding is for learning. Real tools use pgoutput, the plugin that PostgreSQL's own logical replication uses. It is built into the server, so it works on managed services where you cannot install plugins, and Debezium supports it. pgoutput sends only the tables listed in a publication, a named set of tables created with CREATE PUBLICATION. Its messages are binary. The first byte of each one says what it is: B begin, C commit, I insert, U update, D delete, and R relation. A relation message describes a table's columns and types. pgoutput sends it before the first change to a table in a session, and again after the table's definition changes, so a reader always knows the current shape of the rows. This matters for schema changes, covered in the last lesson of this skill.
CREATE PUBLICATION stock_pub FOR TABLE stock;
SELECT slot_name FROM pg_create_logical_replication_slot('pgo', 'pgoutput');
INSERT INTO stock VALUES ('E5', 3);
UPDATE stock SET qty = 2 WHERE sku = 'E5';
-- pgoutput sends binary messages; the first byte says what each message is.
SELECT string_agg(chr(get_byte(data, 0)), ' ') AS messages
FROM pg_logical_slot_peek_binary_changes('pgo', NULL, NULL,
'proto_version', '1', 'publication_names', 'stock_pub');docker exec -i cdc-demo psql -U postgres -X -q < pgoutput.sql slot_name
-----------
pgo
(1 row)
messages
---------------
B R I C B U C
(1 row)Two transactions, so two B…C pairs, and one R before the first change to stock. Next, the rights. Using a replication slot needs the REPLICATION attribute on the role (or superuser). A CDC user should get that attribute plus SELECT on the captured tables, which the initial snapshot needs, and nothing more. Then slots.sql lists the slots on the server. For each one, confirmed_flush_lsn is the position its reader has confirmed, and the server must keep all WAL that the slot may still need, starting at its restart_lsn. behind is true when WAL has been written since the last confirmation.
CREATE ROLE reader LOGIN PASSWORD 'reader';
SET ROLE reader;
SELECT pg_create_logical_replication_slot('mine', 'pgoutput');
RESET ROLE;-- Every slot on the server, and whether WAL was written since its last confirmation.
SELECT slot_name, plugin, active, wal_status,
pg_wal_lsn_diff(pg_current_wal_lsn(), confirmed_flush_lsn) > 0 AS behind
FROM pg_replication_slots
ORDER BY slot_name;docker exec -i cdc-demo psql -U postgres -X -q < rights.sql
docker exec -i cdc-demo psql -U postgres -X -q < slots.sqlERROR: permission denied to use replication slots
DETAIL: Only roles with the REPLICATION attribute may use replication slots.
slot_name | plugin | active | wal_status | behind
-----------+---------------+--------+------------+--------
pgo | pgoutput | f | reserved | t
walk | test_decoding | f | reserved | t
(2 rows)Both slots are inactive (no reader is connected) and behind. walk is behind even though you consumed it, because the later statements wrote more WAL; test_decoding reads every table, so walk now holds the E5 changes too. pgo is behind because peek confirms nothing. wal_status is reserved while the WAL a slot needs is within normal limits; the last lesson of this skill shows it change as a slot falls behind, up to lost. Remove what you created so no slot keeps WAL on the server, then remove the container:
docker exec cdc-demo psql -U postgres -X -q -At \
-c "SELECT count(pg_drop_replication_slot(slot_name)) FROM pg_replication_slots"
docker rm -f -v cdc-demo2
cdc-demo06. Check your understanding
07. Apply it
Prepare the source side of the skill practice. For your orders table, decide the replica identity: does any consumer need the old values of updated or deleted rows? Write the SQL that creates a CDC role with only LOGIN, REPLICATION and SELECT on orders, and a publication that lists only orders. Write one monitoring query over pg_replication_slots that shows, for each slot, whether it is active and how many bytes of WAL lie between pg_current_wal_lsn() and its confirmed_flush_lsn. You will run all three in the lab.
08. Review prompt
Without looking back, explain: what an LSN is and why it only grows; why logical decoding needs wal_level = logical; the difference between peeking and getting changes from a slot; why changes arrive in commit order and never include rolled-back work; what REPLICA IDENTITY DEFAULT and FULL put into an update and a delete; and what a publication does for pgoutput.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.