Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Concept · 20 min · revision 2

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

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.

Terminal
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"
Illustrative output (your LSN will differ)
 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.

SQL · decode.sql
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);
Terminal
docker exec -i cdc-demo psql -U postgres -X -q < decode.sql
Expected output
 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 X9 never appears. A CDC consumer never has to undo a change that did not happen.
  • Transactions arrive whole, in commit order. C3 committed first, so it is decoded first, even though transaction 2 started earlier and changed A1 before C3 existed. The changes of transaction 2 arrive together between its own BEGIN and COMMIT. 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. peek showed seven lines and left them in the slot. get returned the same seven lines and confirmed them, so the second get found nothing. A real CDC reader confirms a position only after it has stored the changes safely downstream. If you debug a production slot with get, 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.

SQL · identity.sql
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%';
Terminal
docker exec -i cdc-demo psql -U postgres -X -q < identity.sql
Expected output
UPDATE: 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]:4

Under 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.

SQL · pgoutput.sql
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');
Terminal
docker exec -i cdc-demo psql -U postgres -X -q < pgoutput.sql
Expected output
 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.

SQL · rights.sql
CREATE ROLE reader LOGIN PASSWORD 'reader';
SET ROLE reader;
SELECT pg_create_logical_replication_slot('mine', 'pgoutput');
RESET ROLE;
SQL · slots.sql
-- 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;
Terminal
docker exec -i cdc-demo psql -U postgres -X -q < rights.sql
docker exec -i cdc-demo psql -U postgres -X -q < slots.sql
Expected output
ERROR:  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:

Terminal
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-demo
Expected output
2
cdc-demo

06. Check your understanding

Practice check · 3 questions

Reading the log

Each question changes one detail of the examples above. Pick the best answer.

Q1. With REPLICA IDENTITY DEFAULT, you run `UPDATE stock SET qty = 0 WHERE sku = 'B2'`. What does `test_decoding` show for it?
Q2. To debug a stuck pipeline, an engineer runs `pg_logical_slot_get_changes` on the slot that the CDC connector uses, then restarts the connector. What happens?
Q3. Transaction T1 starts at 10:00, updates order 5 and commits at 10:07. Transaction T2 starts at 10:03, inserts order 9 and commits at 10:04. In what order does a slot return them?
Practice only: not graded, not saved, not evidence.

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.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check