In short
Change data capture (CDC) turns every committed insert, update and delete in a database into an event other systems can consume, so search indexes, caches and warehouses stay in step without the application writing to each of them. The dependable way to do it is log-based: read the database’s own commit log, the write-ahead log through logical decoding in PostgreSQL or the row-format binary log in MySQL, take a consistent snapshot, then stream from the exact position the snapshot ended. Delivery is at least once and ordered per row, so every consumer has to be idempotent.
Key points
- Polling by
updated_atis simple, but it misses deletes, merges intermediate states and can skip rows from transactions that commit late. - Log-based CDC reads committed changes in commit order, deletes included, with little extra work on the write path.
- In PostgreSQL, a publication says what to stream and a replication slot remembers how far the consumer got; the slot also keeps WAL on disk until the consumer confirms it.
- Start with a consistent snapshot, then stream from where the snapshot ended; tools such as Debezium do this and mark snapshot rows as reads.
- Expect duplicates after a crash and order only per key: upsert by primary key and skip changes older than the log position you already applied.
- Alert on retained WAL per slot, cap it with
max_slot_wal_keep_size, and drop slots nobody reads.
What change data capture is, and why teams use it
Most applications have one database that holds the truth and several other systems that need a copy of part of it: a search index, a cache, an analytics warehouse, another service. Writing to all of them from application code is a dual write. The database commit can succeed while the search update fails, and nothing brings the two back in step. CDC turns it around. The database commits, and a separate process reads the committed change and passes it on.
- Search indexes: stream product or document rows into a search engine so results reflect edits. The indexing side is in hybrid search with BM25 and vector search.
- Cache invalidation: evict or refresh an entry when its row changes, instead of waiting for a TTL; see caching strategies.
- Analytics: copy changes into a warehouse continuously instead of a nightly full export.
- The outbox: the application writes an event row into an
outboxtable in the same transaction as the business change, and CDC publishes it. The event and the change commit together, with no poller and no two-phase commit. The pattern is in idempotency and job queues. - Replication between services or databases, and audit trails of what changed when.
CDC is not event sourcing. A CDC event says a row went from one state to another; it does not say why. If consumers need business meaning, such as “order cancelled by the customer”, publish explicit domain events, for example through an outbox, rather than reverse-engineering intent from column diffs. The difference is covered in event sourcing and CQRS.
Three ways to capture changes
| Approach | How it works | Deletes | Cost on the write path | Main risk |
|---|---|---|---|---|
Polling by updated_at | A job queries rows changed since a stored cursor | Missed, unless deletes are soft | An index on the column | Rows from late-committing transactions are skipped; intermediate states are lost |
| Triggers | A trigger copies each change into a change table in the same transaction | Captured | Every write also writes the change table | Write amplification; the change table needs draining and pruning |
| Log-based | A reader decodes the database’s commit log: the WAL or the binlog | Captured | Small: the log is written anyway, with some extra detail | Retained log fills the disk if the reader stops; needs replication privileges |
Polling is fine when you control the schema and can live with its gaps. The sketch below keeps a cursor of (updated_at, id), so rows that share a timestamp are not skipped, and pages through changes oldest first. Run against SQLite, it prints what the comments show.
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, updated_at INTEGER)")
def poll(cursor):
"""Rows changed after the (updated_at, id) cursor, oldest first, and the new cursor."""
rows = db.execute(
"SELECT id, name, updated_at FROM products"
" WHERE (updated_at, id) > (?, ?) ORDER BY updated_at, id LIMIT 100",
cursor,
).fetchall()
return rows, ((rows[-1][2], rows[-1][0]) if rows else cursor)
db.executemany("INSERT INTO products VALUES (?, ?, ?)",
[(1, "mug", 100), (2, "lamp", 100), (3, "desk", 101)])
changes, cursor = poll((0, 0))
print(changes, cursor)
# [(1, 'mug', 100), (2, 'lamp', 100), (3, 'desk', 101)] (101, 3)
db.execute("UPDATE products SET name = 'blue mug', updated_at = 102 WHERE id = 1")
db.execute("DELETE FROM products WHERE id = 2") # leaves no row to find
changes, cursor = poll(cursor)
print(changes, cursor)
# [(1, 'blue mug', 102)] (102, 1) <- the lamp's deletion never shows upThree things go wrong. Deletes leave no row, so the lamp’s removal is never seen; the usual workaround is a soft delete with a deleted_at column, which every other query then has to respect. Two updates between polls arrive as one, because the poller only sees the latest state. And updated_at is set when a row is written, not when its transaction commits: a long transaction can write a row stamped 100 and commit after the poller has moved its cursor to 101, and that row is never read. Re-reading a trailing window behind the cursor narrows the gap without closing it, and needs a consumer that tolerates repeats.
Triggers capture deletes and every intermediate state, at the cost of a second write inside every transaction. They share the commit-order problem if the change table is read by an increasing id: sequence values are handed out when rows are inserted, transactions commit in a different order, so a reader can see id 11 before id 10 is visible. Log-based CDC avoids both problems. In PostgreSQL, the documentation for output plugins says concurrent transactions are decoded in commit order, and rolled-back transactions are never decoded at all.
PostgreSQL: logical decoding, publications and replication slots
PostgreSQL writes every change to its write-ahead log (WAL) before applying it, for crash recovery and replication. Logical decoding turns those physical records back into row changes, and it needs wal_level = logical. Three pieces matter.
- An output plugin formats the changes.
pgoutputis the standard plugin behind built-in logical replication and most CDC tools;test_decodingis a readable example plugin. - A publication names the tables and the operations to stream.
FOR ALL TABLESalso covers tables created later, and needs superuser rights. - A replication slot is the consumer’s bookmark. Slots persist across restarts and crashes, and they stop PostgreSQL from removing WAL the consumer has not confirmed. Only one receiver reads a slot at a time, so most setups give every consumer its own slot.
Replica identity decides what an update or delete carries about the old row. The default writes the old values of the primary key columns. REPLICA IDENTITY FULL writes the old value of every column. A table in a publication that publishes updates or deletes must have a replica identity, or PostgreSQL disallows those operations on it.
-- postgresql.conf: wal_level = logical (takes a restart)
-- Write every old column value on UPDATE and DELETE, not only the key.
ALTER TABLE orders REPLICA IDENTITY FULL;
-- What to stream: these tables, these operations.
CREATE PUBLICATION orders_cdc FOR TABLE orders, customers
WITH (publish = 'insert, update, delete');
-- The consumer's position in the WAL. pgoutput is the built-in plugin.
SELECT slot_name, lsn
FROM pg_create_logical_replication_slot('orders_cdc_slot', 'pgoutput');
-- How much WAL each slot holds back, and whether it is still usable.
SELECT slot_name, active, wal_status,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained
FROM pg_replication_slots;
-- When the consumer is retired for good, drop its slot.
SELECT pg_drop_replication_slot('orders_cdc_slot');These statements were run against a scratch PostgreSQL 14 database. Connectors usually create the slot themselves; doing it by hand shows what they set up. To see what decoding produces, here is real test_decoding output from the same scratch database, for an orders table with an items column, under both replica identity settings.
-- test_decoding output for one UPDATE and one DELETE, run on PostgreSQL 14
-- REPLICA IDENTITY FULL: the old row travels with the change
table public.orders: UPDATE: old-key: id[bigint]:1 status[text]:'new' items[integer]:3 new-tuple: id[bigint]:1 status[text]:'paid' items[integer]:3
table public.orders: DELETE: id[bigint]:1 status[text]:'paid' items[integer]:3
-- REPLICA IDENTITY DEFAULT: no old values unless the key changed; a DELETE carries only the key
table public.orders: UPDATE: id[bigint]:2 status[text]:'paid' items[integer]:1
table public.orders: DELETE: id[bigint]:2With the default identity, a consumer learns the new row on an update but only the key on a delete. That is enough to delete a copy by key. It is not enough to, say, subtract the deleted row’s items from a running total kept elsewhere; that consumer needs FULL, which makes every update and delete write more WAL.
MySQL: the binary log in row format
MySQL’s equivalent is the binary log. With row-based logging, the default, the binlog records how individual rows changed rather than the SQL statements that changed them. MySQL’s documentation marks binlog_format itself as deprecated and says new replication setups should use row-based logging only. binlog_row_image sets how much of each row is logged: full, the default, logs every column in the before and after images; minimal logs only the columns that identify the row and the ones the statement set; noblob skips BLOB and TEXT columns that neither identify the row nor changed. For CDC, full is the safe choice, for the same reason as REPLICA IDENTITY FULL.
The failure mode is the mirror image of PostgreSQL’s. MySQL has no slot holding the log for a reader; it removes binlog files after binlog_expire_logs_seconds, which defaults to 30 days. A connector that stays down longer than the retention comes back to a position that no longer exists and has to take a new snapshot. PostgreSQL keeps the WAL for a stopped reader instead, and pays for it in disk space.
Initial snapshot, then streaming
A new consumer needs the current state of the tables, not only the changes from now on. The standard sequence: create the slot, read a consistent snapshot of the data as of the slot’s starting point, then stream from that point. PostgreSQL supports this directly. A slot created through the replication protocol exports a snapshot that shows the database exactly as it was before the first change in the slot’s stream. Read the tables inside that snapshot, and no change is missed or counted twice.
Debezium, an open-source CDC platform, is a useful neutral reference for how a mature tool behaves. By default its PostgreSQL connector takes a snapshot when it has no stored offsets, then streams from the position the snapshot read. Snapshot rows are emitted as reads. For large tables it also offers incremental snapshots, which run in parallel with streaming. Each change event has a key built from the row’s primary key, and a value wrapped in an envelope:
| Field | What it holds |
|---|---|
op | c create, u update, d delete, r snapshot read, t truncate |
before | The row before the change; how complete it is depends on the replica identity |
after | The row after the change; empty for a delete |
source | Where the change came from: connector, database, schema, table, transaction id and LSN |
ts_ms | A timestamp for the event, alongside the source’s own timestamps |
Send snapshot reads and live inserts down one code path in the consumer. Both mean “this row now looks like this”, and treating them the same way is what lets you re-snapshot a table later without special cases.
Ordering, duplicates and idempotent consumers
A logical slot emits each change once in normal operation. After a crash it can go back: PostgreSQL saves a slot’s position only at checkpoints, so a restarted server may send recent changes again, and its documentation makes the client responsible for handling repeats. Debezium’s FAQ says the same of the whole pipeline: each event exactly once when things go well, at least once after a crash or a network failure. Design for duplicates, not for exactly-once.
Order holds per key, not globally. Debezium keys events by primary key, and Kafka writes events with the same key to the same partition and serves each partition in the order written. So the changes to one row arrive in order. Changes to different rows, or to two tables touched by one transaction, can be read in any interleaving by consumers of different partitions. A consumer that needs whole transactions has to regroup events using the transaction metadata, which Debezium can emit as separate boundary events.
- Store the source position, the LSN in PostgreSQL, next to every row you copy.
- Apply a change only if its position is newer than the stored one. Anything older is a repeat or a stale reorder, and is skipped.
- Apply deletes the same way, keeping a short-lived marker with the delete’s position, so a late, older update cannot bring the row back.
- Commit the consumer’s own offset after the write, not before, so a crash replays changes instead of dropping them.
That is an upsert keyed by primary key and guarded by position. It turns at-least-once delivery into an effectively-once result. The wider family of patterns, dedupe tables and the outbox among them, is in idempotency and job queues.
Deletes, tombstones and schema changes
Deletes are where CDC earns its keep and where consumers most often break. A delete event carries the key, plus the old row if the replica identity allows it. Debezium follows each delete with a tombstone by default: a second message with the same key and an empty value. The tombstone exists for Kafka log compaction, which may discard older messages as long as the latest one per key is kept; an empty latest message lets compaction remove the key entirely. Consumers must handle both the delete and the empty message without crashing, and tombstones.on.delete turns tombstones off where compaction is not used.
TRUNCATE is its own case: it removes rows without a per-row event. PostgreSQL publishes it as one operation when the publication includes truncate, and Debezium emits it as a t event. A consumer has to treat it as “clear this table”, not ignore it.
Schema changes are not in the stream. Debezium’s documentation notes that PostgreSQL logical decoding does not support DDL changes, so a connector cannot pass an ALTER TABLE on to consumers. Treat the change stream as a public API: add columns as optional, deploy consumers that ignore unknown fields before producers start sending them, and rename or drop columns in expand-and-contract steps, as in zero-downtime database migrations. Some teams put a schema registry between the connector and its consumers, so an incompatible change fails when it is published rather than when it is read.
Running CDC: slots, disk and monitoring
The biggest operational risk is a slot nobody reads. A slot keeps every WAL file its consumer has not confirmed, connected or not. It also stops VACUUM from removing catalog rows it still needs, and PostgreSQL’s documentation warns that in extreme cases this can force a shutdown to prevent transaction ID wraparound. A connector stopped over a weekend on a busy database can fill the primary’s disk.
- Cap retention with
max_slot_wal_keep_size. The default, -1, keeps WAL without limit. With a cap, a slot that falls too far behind loses the WAL it needs: itswal_statusinpg_replication_slotsmoves tounreservedand then tolost, and a lost slot is no longer usable, so the consumer re-snapshots. That is a recoverable failure for one consumer instead of an outage for the database. - Alert on retained WAL per slot, using the query above, and on
activestaying false, long before the cap is reached. - Drop slots for retired consumers. The current PostgreSQL documentation also lists
idle_replication_slot_timeout, which invalidates slots left inactive longer than a set time. - Watch for a quiet table in a busy database. If the captured tables rarely change, the consumer has nothing to confirm and its slot does not advance while other tables keep writing WAL. Debezium’s answer is heartbeat events, set with
heartbeat.interval.ms, which let it report a newer position. - Measure lag end to end, from commit to the consumer’s write, not only whether the connector process is up.
BYD Tech builds web apps and their backends: the code lives in the client’s GitHub from day one, the founders are on the calls, and AI-assisted work is reviewed by an engineer.
Sources
Checked when this post was written.
- PostgreSQL docs: Logical decoding concepts
- PostgreSQL docs: Logical decoding output plugins
- PostgreSQL docs: CREATE PUBLICATION
- PostgreSQL docs: ALTER TABLE (REPLICA IDENTITY)
- PostgreSQL docs: Replication settings (max_slot_wal_keep_size)
- PostgreSQL docs: pg_replication_slots
- MySQL 8.4 Reference Manual: Binary logging options and variables
- Debezium docs: PostgreSQL connector
- Debezium FAQ
- Apache Kafka: Introduction