Change Data Capture (CDC)
Stream every insert, update and delete out of a database into search indexes, caches, warehouses and queues.
What is it?
Your main database holds the truth, but other systems need a copy: a search index, a cache, an analytics warehouse, another service's database. Each time a row changes, those copies need to hear about it.
Change Data Capture (CDC) means detecting the changes in one database and sending them to other systems. Engineers usually try a few approaches in order:
1. Polling: every few seconds, ask the table "what changed since last time?" using an updated_at column or an increasing id. 2. Triggers: have the database copy each change into a separate change table as it happens. 3. Dual writes: have the application write to the database and to the other system. 4. Log-based CDC: read the database's own replication log (PostgreSQL's WAL, MySQL's binlog, MongoDB's oplog), which already records every committed change in order.
Log-based CDC is where most teams end up, because it sees every insert, update and delete, in commit order, without extra queries against the tables.
Explain like I'm 10
Polling is walking through a warehouse every hour to see which shelves look different: you miss things that were moved and moved back, and you can't see what was thrown away. Log-based CDC is reading the warehouse's delivery and removal logbook, where every change was written down in order the moment it happened.
Examples
Polling with an updated_at cursor, and its bugs
-- Runs every 30 seconds. :last_seen is saved after each batch.
SELECT id, name, price, updated_at
FROM products
WHERE updated_at > :last_seen
ORDER BY updated_at
LIMIT 1000;
-- Then: last_seen = max(updated_at) from the batch.Bug 1: if 1,500 rows share the same updated_at, the batch stops at 1,000 and the next query (updated_at > last_seen) skips the other 500. Bug 2: in PostgreSQL, now() is the transaction start time, so a long transaction can commit a row with an updated_at older than a value you already moved past, and it is never picked up. Bug 3: a hard DELETE leaves no row to find. Safer polling uses a keyset cursor on (updated_at, id), re-reads a small overlap window, uses soft deletes, and makes the sink idempotent so re-reads are harmless.
PostgreSQL logical replication setup for CDC
-- postgresql.conf (requires a restart)
wal_level = logical
max_replication_slots = 10
max_wal_senders = 10
-- PostgreSQL 13+: cap how much WAL a stuck slot can hold
max_slot_wal_keep_size = '50GB'
-- Choose which tables to publish
CREATE PUBLICATION orders_pub FOR TABLE orders, order_items;
-- Optional: include all old column values in UPDATE/DELETE events
-- (by default only the primary key of the old row is logged)
ALTER TABLE orders REPLICA IDENTITY FULL;
-- A slot remembers how far the consumer has read
SELECT pg_create_logical_replication_slot('orders_cdc', 'pgoutput');
-- Watch it: an inactive slot with a growing lag retains WAL on disk
SELECT slot_name, active, confirmed_flush_lsn,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained
FROM pg_replication_slots;pgoutput is the built-in logical decoding plugin (PostgreSQL 10+); wal2json is a third-party alternative that emits JSON. A CDC tool such as Debezium connects with the slot and publication names, takes an initial snapshot, then streams changes from the slot and reports back the LSN it has processed.
An idempotent sink for at-least-once change events
type ChangeEvent = {
op: "c" | "u" | "d" | "r"; // create, update, delete, snapshot read (Debezium style)
before: Product | null;
after: Product | null;
sourcePosition: bigint; // e.g. the LSN of the change
};
async function applyChange(event: ChangeEvent): Promise<void> {
if (event.op === "d") {
const id = event.before!.id;
// Deleting a row that is already gone is a no-op, so replays are safe
await search.deleteDocument("products", id);
return;
}
const row = event.after!;
// Upsert keyed by primary key; skip events older than what we already applied
await sinkDb.query(
"INSERT INTO products_copy (id, name, price, source_position) " +
"VALUES ($1, $2, $3, $4) " +
"ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name, price = EXCLUDED.price, " +
"source_position = EXCLUDED.source_position " +
"WHERE products_copy.source_position < EXCLUDED.source_position",
[row.id, row.name, row.price, event.sourcePosition],
);
}CDC pipelines deliver at least once: after a crash the consumer resumes from its last saved offset and sees some events again. Upserting by primary key makes a repeat harmless, and the source_position guard stops an old, replayed event from overwriting a newer value.
How it works
Polling. A job queries the source table on a schedule for rows with updated_at (or an auto-increment id) greater than a saved cursor. It is easy to build and needs no special database access. The problems:
- Hard deletes are invisible. A deleted row can't be selected. - Timestamp ties at a page boundary are skipped with a strict >. - Commit order is not timestamp order. A transaction can set updated_at (or take an id from a sequence) early and commit late, after the cursor has already moved past that value. Clock skew across app servers makes this worse. - Intermediate states are lost. Two updates between polls look like one. - Load and latency. Each poll is a query against the primary, and changes arrive up to one poll interval late.
Triggers. An AFTER INSERT/UPDATE/DELETE trigger writes each change into a change table that a job reads. This catches deletes and every change, but it adds a write to every transaction on the source, makes the change table a hot spot, and puts sync logic inside the database where it is hard to test and version.
Dual writes. The app writes to the database and then to Kafka, the search index or the cache. The two writes are not atomic: if the process crashes or the second call fails after the first commits, the systems disagree. If two requests update the same row, their second writes can arrive in the opposite order, leaving the copy with the older value.
Log-based CDC. Every serious database already writes each committed change to a log for crash recovery and replication. CDC reads that log as a replication client:
- PostgreSQL: set wal_level = logical. A publication chooses tables, a replication slot tracks the consumer's position (an LSN, log sequence number) and keeps the WAL it still needs, and an output plugin (pgoutput built in, or wal2json) turns WAL records into row changes. - MySQL: read the binlog with binlog_format = ROW (and usually binlog_row_image = FULL), resuming from a binlog file and position or a GTID set. - MongoDB: open a change stream (built on the oplog; needs a replica set or sharded cluster) and resume with its resume token.
Debezium is the common open-source tool for this. It usually runs as a Kafka Connect source connector, writes one Kafka topic per table, keys each message by the row's primary key, and stores its source position as a Kafka Connect offset. Each event carries before, after, op and source metadata.
Practical concerns:
- Snapshot, then stream. A new consumer first reads the existing rows (a snapshot), then streams changes from the log position recorded at the snapshot start, so nothing falls in the gap. - Resuming. The consumer saves its position (LSN, binlog position, resume token) and continues from there after a restart. - Retained logs. A PostgreSQL slot holds WAL until the consumer confirms it. If the consumer stops, WAL piles up and can fill the disk of the primary. Monitor slot lag, drop abandoned slots and set max_slot_wal_keep_size. MySQL and MongoDB have the opposite risk: if the consumer is down longer than binlog or oplog retention, its position is gone and it must re-snapshot. - Ordering. The log is in commit order. Keep per-key order downstream by partitioning on the primary key; there is no global order across partitions. - Delivery. Expect at-least-once delivery. Make the sink idempotent with upserts by primary key. - Deletes. Debezium emits a delete event and then, by default, a tombstone (same key, null value) so Kafka log compaction can remove the key. - Schema changes. Adding a column is usually fine; renaming or changing types can break consumers. Use a schema registry or versioned contracts, and roll out changes so old and new consumers both work. - Backfills. To resync a table without stopping the stream, use an incremental snapshot (Debezium supports these via a signal) or a separate backfill that writes through the same idempotent upsert.
POLLING LOG-BASED CDC
App ──writes──▶ ┌──────────┐ App ──writes──▶ ┌──────────┐
│ orders │ │ orders │
│ table │ │ table │
└────▲─────┘ └────┬─────┘
│ SELECT ... WHERE │ every commit is
│ updated_at > cursor │ appended to the log
│ (every N seconds) ▼
┌────┴─────┐ ┌───────────────────┐
│ poller │ │ WAL / binlog / │
└────┬─────┘ │ oplog │
│ └────────┬──────────┘
▼ │ read as a
┌──────────┐ │ replication client
│ sink │ ┌────────▼──────────┐
└──────────┘ │ Debezium / CDC │
│ (saves LSN/offset)│
- misses hard deletes └────────┬──────────┘
- misses late commits / ties ▼
- extra queries on primary Kafka topic (key = PK)
- latency = poll interval │
┌──────────┼──────────┐
▼ ▼ ▼
search cache warehouse
- every insert/update/delete, in commit order
- low load: reads a log the DB writes anyway
- must watch slot lag / log retentionWhy does it exist?
Modern systems keep the same data in several places, each good at one job: the database for transactions, a search engine for text search, a cache for fast reads, a warehouse for analytics. Keeping them in sync from application code is fragile (dual writes), and polling is lossy. The database's log is already a complete, ordered record of every change, so CDC reuses it instead of reinventing change tracking.
When to use it
- Keeping a search index, cache or read model in sync with a primary database. - Feeding a data warehouse or lake with changes instead of nightly full dumps. - Migrating to a new database with little downtime: snapshot, stream changes, then switch over. - Publishing domain events reliably, together with the transactional outbox. - Auditing every change to sensitive tables.
When not to use it
- One small table that changes rarely and tolerates minutes of delay: polling with a correct cursor and soft deletes may be enough. - When you can't get replication privileges or log access (some managed databases restrict it) and can't change that. - Raw row changes are not a good public API between teams. Exposing your table layout couples other services to your schema; publish deliberate events (for example through an outbox) instead. - If you only need a one-off copy, a dump and restore is simpler.
Common mistakes
Polling on updated_at with a strict > and LIMIT, which skips rows sharing a timestamp and rows that commit after the cursor has moved past their timestamp.
Leaving a PostgreSQL replication slot behind after a consumer is removed or stops, so the primary keeps WAL until its disk fills up.
Writing a sink that does plain INSERTs, so replayed events after a restart create duplicates or fail.
Ignoring deletes: the sink handles only creates and updates, so deleted rows live forever in the search index or cache.
Assuming a global order across a multi-partition topic. Order is guaranteed only per partition, so key messages by primary key.
Practice exercises
- Easy:
List three kinds of changes that a polling job using
WHERE updated_at > :cursorcan miss, and explain why each is missed. - Medium:
Write the PostgreSQL settings and SQL to publish an
orderstable for logical replication, create a slot, and a query that shows how much WAL each slot is retaining. - Hard:
Design a pipeline that keeps an Elasticsearch index in sync with a 500-million-row products table. Cover the initial load, switching to streaming without a gap, handling deletes, consumer restarts, and a full reindex later without stopping updates.
Interview questions
What is change data capture?
Detecting changes (inserts, updates, deletes) in a source database and delivering them to other systems, such as a search index, cache, warehouse or message queue, so they stay in sync.
Why does polling on an `updated_at` column miss hard deletes?
A deleted row no longer exists, so no query can select it. Polling needs soft deletes (a deleted_at column) or a separate mechanism to see deletions.
How can polling miss a row even though it was inserted with a correct timestamp?
The timestamp or sequence id is assigned before commit. A long transaction can commit after the poller already advanced past that value, so the row lands behind the cursor. Ties at a page boundary with a strict > are also skipped.
Why are dual writes from the application unsafe?
The two writes aren't atomic. A crash or failure between them leaves the systems disagreeing, and concurrent requests can apply their second writes in a different order than the database commits, leaving the copy stale.
What does log-based CDC read in PostgreSQL, MySQL and MongoDB?
PostgreSQL's write-ahead log through logical decoding (a publication plus a replication slot, using pgoutput or wal2json). MySQL's row-based binlog. MongoDB's oplog, usually through change streams.
What is a PostgreSQL replication slot, and what's the operational risk?
It records how far a consumer has confirmed reading (its LSN) and makes the server keep all WAL after that point. If the consumer stops or is abandoned, WAL accumulates and can fill the primary's disk. Monitor slot lag, drop unused slots, and cap it with max_slot_wal_keep_size (PostgreSQL 13+).
How does a CDC pipeline start on a table that already has data?
It records the current log position, takes a consistent snapshot of existing rows, then streams changes from the recorded position. Events from the overlap are harmless if the sink is idempotent.
CDC is usually at-least-once. What does that mean for the sink?
After a restart the consumer resumes from its last committed offset and may replay events. The sink must be idempotent: upsert by primary key, treat delete-of-missing as a no-op, and ideally ignore events older than the version already applied.
How do you preserve ordering when CDC events go through Kafka?
Use the row's primary key as the message key so all changes to a row go to the same partition, which is ordered. There is no ordering across partitions, so consumers must not depend on cross-row order.
Senior: when would you not expose raw CDC events of your tables to other teams?
Raw row events leak your internal schema; any column rename becomes a breaking change for consumers. For cross-service integration, publish explicit domain events via a transactional outbox (which CDC can relay) and keep raw table CDC for your own derived stores like search and analytics.