How-To Guide

How to Implement Change Data Capture

Stream row changes from WAL logical decoding or binlog, order by transaction, consume idempotently, and handle schema evolution deliberately.

On this page

  1. Introduction
  2. Why the log is the right source
  3. Configure the source
  4. Consume idempotently with durable offsets
  5. Ordering, transactions, and fan-in
  6. Schema evolution
  7. Test with replay and fault injection
  8. Common pitfalls
  9. Conclusion

Introduction

Change data capture answers a deceptively simple question: how does another system learn, promptly and completely, what changed in the database? The naive answers all leak. Timestamp polling misses deletes, misses updates that forget to touch the column, and hammers the source with scans. Dual writes from application code, writing to the database and the message queue in one flow, atomically drift apart the first time one side fails. Triggers capture changes but add write-path latency and a hidden second schema to maintain. Log-based CDC reads the database’s own write-ahead log, the record of truth it already keeps for crash recovery, and turns it into a change stream: every insert, update, and delete, in commit order, with negligible source overhead. This tutorial sets up PostgreSQL logical replication, writes a consuming pipeline with durable offsets and idempotent apply, addresses ordering and transaction boundaries, and handles the schema evolution that kills naive pipelines.

Why the log is the right source

The write-ahead log is the database’s own account of what happened, written for durability and already paid for. Reading it after the fact costs the source almost nothing, and it carries properties no application-side approach can match. Completeness: every committed change appears, including deletes, which polling cannot see and dual writes forget under failure. Ordering: changes appear in commit order, with transaction boundaries visible, so downstreams can reconstruct causality rather than guessing from arrival order. Consistency: the log reflects what actually committed, not what the application attempted, so failed transactions never leak into the stream. The catch is representation: WAL is physical, page-level churn, so Postgres exposes a logical decoding layer, with a replication slot and an output plugin, that translates physical changes back into row-level events, insert, update, delete, with before and after images. That translation is the machinery this tutorial configures.

Configure the source

PostgreSQL needs three settings and two objects: wal_level logical, adequate max_replication_slots and max_wal_senders, then a publication defining which tables to capture and a replication slot holding the consumer’s position.

ALTER SYSTEM SET wal_level = logical;
-- restart required

CREATE PUBLICATION events_pub FOR TABLE events, customers;

SELECT pg_create_logical_replication_slot('pipeline_a', 'pgoutput');

The publication names the captured tables explicitly, which is the scoping decision: capture what downstreams consume, not everything, because every captured table adds WAL volume and slot retention pressure. The slot is the durability mechanism: Postgres retains WAL beyond the slot’s confirmed position indefinitely, so a consumer that is down for a day replays exactly where it stopped, at the cost of source disk. That cost is real and unbounded, so slot lag and retained WAL size belong on the same monitoring dashboard as replication lag in any system you operate, with alerts that fire long before disk fills. MySQL’s equivalent is binlog with ROW format, which carries row images natively, consumed through the replication protocol by tools like Debezium.

Consume idempotently with durable offsets

The consumer must be crash-safe at every point, which reduces to two disciplines: persist the offset after applying, and apply changes idempotently, because the window between apply and offset-acknowledge always allows one replay.

class ChangeApplier:
  def __init__(self, target, slot='pipeline_a'):
    self.target = target
    self.slot = slot

  def apply(self, change):
    if change.op == 'delete':
      self.target.delete(change.table, change.key)
    else:
      self.target.upsert(change.table, change.key, change.after)
    self.target.commit()
    self.ack(self.slot, change.lsn)

  def ack(self, slot, lsn):
    self.connection.send_feedback(flush_lsn=lsn)

The upsert on apply is what makes redelivery safe: replaying the same change produces the same state. The key that drives the upsert must be the source’s primary key, mapped through the publication’s replica identity, and tables without a primary key need REPLICA IDENTITY FULL or a declared key, a decision that belongs in the pipeline’s source configuration rather than discovered as missing delete events in production. Batch the feedback, acknowledging after a group rather than per message, for throughput, but keep the ack strictly after the durable apply, never before.

Ordering, transactions, and fan-in

The stream arrives in commit order, which is the strongest ordering the source can provide, and downstreams must not accidentally weaken it. Three rules preserve it. Apply per source transaction: events from one transaction belong together, and a consumer that interleaves them with another transaction’s events can build states the source never had; most decoders expose transaction boundaries as begin and commit markers, and the apply unit should be the transaction, not the row. Preserve per-key ordering under parallelism: partitioning work by primary key hash keeps all changes to one key on one worker, allowing parallelism without reordering any key’s history. Respect fan-in causality: when two source tables feed one derived view, the view’s state after any prefix of the stream should equal a consistent source state, which per-transaction apply and monotonic LSN tracking provide, and which naive concurrent consumers destroy. Ordering bugs manifest as intermittent wrong states that re-running the pipeline fixes, which is the signature to watch for in tests.

Schema evolution

A column added on the source reaches the stream before the consumer knows about it, and an unprepared pipeline dies mid-stream or silently drops the field. The durable answer is contract versioning: the change event carries a schema version, the consumer understands a range of versions, and unknown versions park the event in a dead-letter topic for handling rather than skipping it silently. Coordinate DDL windows operationally: additive changes, new nullable columns, flow through harmlessly if the consumer maps by name; renames and type changes need a sequenced rollout, consumer taught the new shape first, then source migrated, then old shape retired. The sequence matters because the log replays history: after a rename, old events still carry the old column name, so the consumer must translate both shapes for as long as replay can reach back. Debezium and similar frameworks version their envelopes and provide schema-history topics that replay the source’s DDL alongside the data; whether using a framework or a hand-rolled consumer, the requirement is the same: the pipeline’s contract must survive the source’s schema drifting underneath it.

Test with replay and fault injection

CDC pipelines fail at the seams between apply, offset, and crash, and those seams need deliberate tests. Crash windows: kill the consumer between apply and ack, restart, and assert the downstream state is correct and no change is lost or duplicated, the core idempotency property. Slot retention: pause the consumer, generate traffic, and assert WAL retention grows and alerts fire, then resume and assert catch-up. Transaction integrity: commit a multi-row transaction on the source and assert the downstream applies all rows or none, never a prefix. Delete fidelity: delete rows including rows without a primary key declared identity and assert deletes arrive. Schema drift: add a column mid-stream and assert the versioned consumer handles or quarantines the event rather than crashing. The full suite should run against a real Postgres in a container, because logical decoding behavior, slot mechanics, and feedback timing are exactly the parts mocks erase.

pg_recvlogical -d postgres --slot pipeline_a --start -f - \\
 --option proto_version=1 --option publication_names=events_pub

Common pitfalls

  • Unmonitored replication slots. A dead consumer’s slot retains WAL until the source disk fills; alert on slot lag and retention size.
  • Offsets acked before apply. A crash in the window loses changes permanently; ack strictly after durable apply.
  • Non-idempotent apply. Redelivery duplicates rows; upsert by source primary key.
  • Row-by-row transaction interleaving. Events from one transaction applied against another’s partial state build impossible source states; apply per transaction.
  • Tables without replica identity. Deletes arrive keyless or not at all; declare keys in the publication.
  • Silent schema drift. Unknown columns dropped quietly corrupt downstreams; version the contract and quarantine unknowns.

Conclusion

Change data capture is the correct foundation for caches, search indexes, analytics mirrors, and event publishing, because the write-ahead log is complete, ordered, and already paid for. Configure logical replication with a narrowly scoped publication and a monitored replication slot, whose retention is durability traded for source disk. Consume with the two disciplines that make crashes harmless: durable offsets acknowledged strictly after apply, and idempotent upserts keyed on the source primary key. Preserve commit order by applying per transaction and partitioning by key, version the event contract so schema evolution parks unknowns instead of dropping them, and test the crash windows, slot retention, and delete fidelity against a real database. A pipeline built this way keeps downstreams consistent without touching the application’s write path, which is the property every alternative approach fails.

Sources: PostgreSQL: logical replication, PostgreSQL: logical replication protocol, Debezium documentation.

FAQ

Why not just poll updated_at?
Timestamp polling misses deletes, misses in-place updates that do not touch the column, races window boundaries, and loads the source with scans. Log-based capture sees every committed change including deletes, in commit order, without extra source queries.
What happens if the consumer is down for a day?
With a replication slot, Postgres retains WAL until the consumer acknowledges, so changes accumulate and replay on reconnect. The trade is disk usage on the source, which is why slot monitoring with alerts is mandatory.
Do I need Kafka in the middle?
Not necessarily. A direct logical replication consumer is fine for one or two downstreams. Kafka earns its place with many consumers, replay requirements, or team boundaries, and it also isolates source retention from consumer downtime.

Related Examples