Logical Replication and CDC

Topics Covered

Logical Decoding

From WAL to row changes

Commit order and the reorder buffer

Logical replication slots

Output plugins

Consuming a slot

At least once delivery

Replica identity

What decoding does not include

Large transactions

Decoding cost

Logical messages

Exported snapshots

Slot creation needs a quiet moment

Decoding on standbys

Toasted values

Origins

Logical decoding and two phase commit

Physical replication ships raw WAL that only an identical server can replay. Logical decoding reads the same WAL and turns it into a stream of row level changes, inserts, updates and deletes with their values, grouped by transaction in commit order. That stream feeds logical replication between Postgres servers, change data capture into other systems and auditing. This section explains how decoding works, what logical slots do and how output plugins shape the stream.

From WAL to row changes

WAL records describe changes to pages: a tuple inserted at a block and offset, a tuple updated. With wal_level set to logical, Postgres adds enough information to identify the rows changed, such as the old key for updates and deletes, and catalog information so the decoder can interpret tuple bytes as columns. The decoder reads WAL, reconstructs each change as a row with column values and emits it to an output plugin.

Commit order and the reorder buffer

WAL interleaves records from many concurrent transactions, and some of them roll back. Logical decoding collects the changes of each transaction in a reorder buffer, keyed by transaction id, and emits a transaction only when its commit record arrives, all of its changes together, in commit order. Aborted transactions are discarded. Consumers therefore see a clean sequence of complete transactions, as if they had run one after another.

The decoder buffers each transaction changes and emits them whole at commit, in commit order, dropping aborted work.

Loading problem...

Logical replication slots

A logical slot records how far a consumer has confirmed the stream, its confirmed_flush_lsn, and makes the server retain the WAL needed to resume from there. It also holds back the catalog xmin, so vacuum keeps old catalog rows needed to decode older WAL with the schema that applied at that time. Slots make consumption reliable across disconnects, but like physical slots they retain WAL indefinitely if the consumer stops, and they also cause catalog bloat.

Output plugins

An output plugin turns decoded changes into a format. pgoutput is the built in plugin used by native logical replication and by many CDC tools, producing a binary protocol. test_decoding produces readable text for experiments. wal2json emits JSON and is popular with older tools. Consumers choose the plugin when creating the slot, and the plugin determines what information is available, such as old values, transaction boundaries and message types.

Consuming a slot

Changes can be read with SQL functions such as pg_logical_slot_get_changes, which consume the changes, or pg_logical_slot_peek_changes, which do not, convenient for testing. Production consumers use the streaming replication protocol, START_REPLICATION on a logical slot, receiving changes continuously and periodically sending feedback with the LSN they have durably processed. The server only advances the slot when the consumer confirms, so a crash before confirmation leads to redelivery.

At least once delivery

Because the slot advances only on confirmation, and a consumer may crash after processing changes but before confirming them, changes after the last confirmed position are delivered again on restart. Logical decoding therefore provides at least once delivery. Consumers must make processing idempotent, for example by recording the last applied LSN alongside the data they write, in the same transaction, and skipping changes at or below it.

Slots redeliver everything after the last confirmation. Storing the applied LSN with the data turns redelivery into a no op.

Replica identity

To decode an update or delete, the consumer needs to know which row changed. REPLICA IDENTITY controls what old values are logged: DEFAULT logs the primary key columns, USING INDEX logs the columns of a chosen unique index, FULL logs the entire old row, and NOTHING logs no old values. Tables without a primary key need FULL or a unique index, and FULL increases WAL volume and makes the subscriber locate rows by comparing all columns.

What decoding does not include

Logical decoding emits changes to table rows. It does not emit DDL, so schema changes are invisible to the stream except through the changed shape of later rows. Sequence advances were not decoded before version 16 added some support in the protocol for future use, so native replication still does not replicate sequences. Large objects are not decoded, and TRUNCATE is decoded since version 11. Consumers must handle these gaps through other means.

Large transactions

Before version 14, a transaction was decoded only after commit, and its changes were spilled to disk in the reorder buffer when they exceeded logical_decoding_work_mem, so a huge transaction caused large temporary files and a long delay before the consumer saw anything. Since version 14, in progress transactions can be streamed to consumers that support it, which then apply or buffer them and discard them if the transaction aborts, reducing delay and disk use.

Decoding cost

Decoding runs inside the walsender process for each slot, reading and parsing WAL, building tuples and looking up catalog entries. Each slot decodes independently, so ten consumers mean ten decoders reading the same WAL. A high write rate with many slots can use significant CPU on the primary. Consolidating consumers onto fewer slots, for example one CDC connector feeding a message bus that many systems read, reduces this cost.

Logical messages

pg_logical_emit_message writes a custom message into WAL, transactional or not, which decoders deliver to consumers alongside row changes. Applications use it to mark points in the stream, signal events without writing to a table, or carry metadata such as the user who made a change. Messages avoid creating table rows only to have them decoded, which makes them a lightweight alternative to an outbox for some use cases.

Exported snapshots

When a logical slot is created through the replication protocol, it can export a snapshot that matches the exact position where the slot starts. A tool can then open a transaction using that snapshot, with SET TRANSACTION SNAPSHOT, and read every table as it was at that point. Changes after it arrive through the slot. This pairing of a consistent copy with a stream that begins precisely at the copy point is the basis of every reliable initial sync, both in native replication and in CDC tools.

Slot creation needs a quiet moment

Creating a logical slot waits until all transactions that were running when the request arrived have finished, because the decoder needs a clean starting point. On a database with a long running transaction, slot creation can hang for as long as that transaction runs. Checking pg_stat_activity for old transactions before creating slots, and setting timeouts on the creating tool, avoids a mysterious stall during setup.

Decoding on standbys

Since version 16, logical decoding can run on a physical standby, so CDC connectors can read from a replica instead of the primary. This moves decoding CPU off the primary. The standby needs hot_standby_feedback on so the primary keeps the catalog rows the decoder needs, and slots on the standby can be invalidated by conflicts during replay if those rows are removed anyway, which must be monitored like any other slot.

Toasted values

Large column values stored out of line in TOAST are only written to WAL when they change. An update that modifies other columns logs the row without the unchanged toasted value, so decoders see a placeholder instead of the value. Consumers that need the full row, such as a search index rebuilding documents, must keep the old value themselves, read it from the table, or use REPLICA IDENTITY FULL, which logs the complete old row including toasted columns.

Origins

Replication origins record which source each applied change came from and how far each source has been applied. Native subscriptions use them to track progress on the subscriber side in a crash safe way, because the origin position is updated in the same transaction as the applied changes. Custom consumers that write into Postgres can use the same mechanism, through pg_replication_origin functions, to get exactly once application into the target database.

Logical decoding and two phase commit

Since version 15, decoding can emit prepared transactions at PREPARE time instead of waiting for COMMIT PREPARED, if the plugin and subscription enable two_phase. This lets subscribers prepare the transaction too, which is useful when the subscriber participates in a distributed commit. Most CDC pipelines do not need this, but it explains a setting that appears in subscription options and slot listings.

Decoding turns WAL into transactions

With wal_level logical, the decoder rebuilds row changes, groups them per transaction and emits them in commit order through an output plugin. Logical slots track confirmed progress and retain WAL, delivery is at least once, replica identity decides which old values are available and DDL and sequences are not in the stream.