Search indexes, caches, the warehouse and downstream services all hold copies of the primary's data, and every copy is a consistency problem. Change data capture turns the one artifact that already records every committed change, in commit order, durably — the database's write-ahead log — into an event stream. The idea is simple. The hard parts are the seams: the snapshot-to-stream handoff, versioning at the sink, and a replication slot that can take down the primary it is reading from.
You know the dual-write problem: db.commit() then es.index(), and a crash between them loses the second write. The part that gets under-weighted in design reviews is that it is broken even with zero failures. Two concurrent writers serialize in one order at the database and in the other order at the index, and the index is left permanently wrong with no error raised anywhere.
Each writer does "DB, then index" correctly. But the two systems serialize the writes in different orders, and there is no shared commit to reconcile them. Add a crash between the two calls and you also get lost writes — the DB has the row, the index never hears about it.
The common "fixes" move the bug around. Index first, then DB just flips which side holds the phantom. Sending to Kafka inside the DB transaction publishes events for transactions that later roll back or fail at commit, and consumers cannot tell. A retry queue recovers lost writes but not the ordering, because it is a log with no relation to commit order. LISTEN/NOTIFY fires at commit, but it is fire-and-forget: a relay that is disconnected or restarting misses notifications for good. A nightly reconciliation job is the honest version, and it quietly makes your SLA "consistent by tomorrow". The only structural fix is to have one commit point and derive everything else from the database's own record of what committed.
Architect's note
try/catch that logs and moves on. Ask "what if the process dies on this line?" and then the more important question: "what if two requests for the same key run this concurrently?" Most teams only ever ask the first.The poller (WHERE updated_at > :hwm, as in the Kafka Connect JDBC source's timestamp modes) is known to miss hard deletes and intermediate states, and to cost an index plus a range scan per table per poll. Those are trade-offs you can accept. The one that disqualifies it for correctness is visibility order ≠ stamp order. updated_at is assigned when the statement runs, but the row becomes visible at commit. A transaction that stamps 10:00:00.5 and commits at 10:00:02 is invisible to a poll at 10:00:01 that has already advanced the high-water mark past it, so it is skipped for good. Auto-increment ids have exactly the same hole, because sequence values are handed out before commit and are not transactional. "Poll by id, it's monotonic" skips rows too.
What happened
Polling updated_at > :last
Tailing the WAL / binlog
INSERT id=7 status=NEW
✓ seen (next poll)
✓ c
UPDATE id=7 → PAID
✗ overwritten before poll
✓ u
UPDATE id=7 → SHIPPED
✓ seen, only final state
✓ u
DELETE id=9
✗ row gone — nothing to select
✓ d + tombstone
txn T1: updated_at=10:00:00.5, commits 10:00:02
✗ poll at 10:00:01 advanced past it
✓ emitted at commit, in commit order
Polling samples state at intervals; the log records every change. The last row is the subtle killer: updated_at is stamped when the statement runs, but the row only becomes visible at commit — so a long transaction can land "in the past" behind the poller's high-water mark and be skipped forever.
The usual patch is a safety lag (read only up to now() - 30s). It is only correct if no transaction runs longer than the lag, and you do not control that: a 20-minute backfill, a migration or an idle-in-transaction session will break the assumption without anyone noticing. On Postgres there is a variant that is actually correct. Store pg_current_xact_id() (Postgres 13+; older versions have txid_current()) in each row, and advance the high-water mark only up to pg_snapshot_xmin(pg_current_snapshot()). Every transaction id below that bound has finished, so nothing behind the mark can still become visible. Its lag is the longest running transaction, which is honest about the cost. Transaction ids are also 32-bit per epoch, so compare full 64-bit xact ids, not raw xid. Use it for a polling outbox relay when you cannot get replication privileges. Use it nowhere you need deletes or intermediate states.
Log-based CDC attaches to the stream the database already produces for replication (Databases track, Chapters 4 and 6) and emits events instead of applying them. On Postgres that means wal_level = logical, a publication choosing tables, a replication slot as the server-side cursor, and the built-in pgoutput plugin (Postgres 10+), which emits each transaction only once it commits. On MySQL it means a binlog client that speaks the replica protocol, binlog_format = ROW, and ideally GTIDs, so the position survives a failover to another server.
PostgreSQL · logical decoding
WAL
wal_level=logical
Replication slot
restart_lsn · confirmed_flush
pgoutput plugin
filtered by PUBLICATION
Debezium
acks LSN after Kafka write
MySQL · binlog client
Binlog
binlog_format=ROW · row_image=FULL
Replica protocol
connector poses as a replica
GTID position
server_uuid:txn_no
Debezium
+ schema-history topic
Both engines already produce an ordered, durable change log for replication. Log-based CDC is simply one more replica that, instead of applying the changes, translates them into events. Zero extra queries on your tables, every change captured, in commit order.
The details that bite are the ones replicas never cared about:
Old images are not free. With Postgres's default REPLICA IDENTITY, a DELETE logs only the primary-key columns, and an UPDATE logs no old tuple at all unless a key column changed. Debezium's before is therefore null on most updates. Any consumer that computes diffs ("status changed from PAID") silently does nothing. REPLICA IDENTITY FULL fixes that, but it logs the whole old row on every update and delete. On wide, update-heavy tables that can roughly double WAL volume for those tables (an illustrative order of magnitude; measure with pg_stat_wal). The cost also shows up in replica lag and backups, not only in CDC.
Not everything is decoded. Core Postgres logical decoding carries no DDL and no sequence state. Partitioned tables publish under each leaf partition's name unless the publication sets publish_via_partition_root (Postgres 13+), and forgetting it means topic-per-partition sprawl that breaks each time a new monthly partition is created. TRUNCATE is decoded (Postgres 11+), but Debezium skips it by default, so a truncate-and-reload job on the source leaves every sink holding rows the source no longer has.
The two engines fail in opposite directions. A Postgres slot pins WAL, so a dead consumer hurts the primary (6.6). MySQL does not retain binlog for replicas at all. Files are purged by binlog_expire_logs_seconds (30 days by default in 8.0), or much sooner on managed services such as RDS, where retention stays minimal until you raise it explicitly. So a dead consumer hurts only itself: once its position is purged, it has to resnapshot. Size MySQL binlog retention to cover your longest plausible connector outage, including a weekend.
Throughput is serial, and slots are not free. A replica's apply rate was never your problem, but a CDC connector's drain rate is. Each slot is one ordered stream. The Postgres and MySQL Debezium source connectors run a single task, so raising tasks.max does nothing. The ceiling is the narrowest of five serial stages, and in practice it is usually the connector's converters and SMT chain, not Kafka and not the database. The usual first fix, "one connector per consuming team", makes the primary pay for it. Every logical walsender reads and decodes the entire WAL stream and filters by publication only afterwards. Three slots that each capture one small table cost roughly three full decodes of all write traffic, plus three independent WAL retention pins. Consolidate to one slot per database and fan out in Kafka. Split slots only when one pipeline measurably cannot keep up, and accept that you then lose cross-table commit order between the splits.
1. walsender decode
on the PRIMARY · one process per slot · decodes all WAL, filters by publication afterwards
2. reorder buffer
holds each txn until commit · spills past logical_decoding_work_mem
3. connector task
Postgres & MySQL source connectors run one task · tasks.max > 1 buys nothing
4. converters + SMTs
Avro/JSON serialization, routing, masking · often the real ceiling
5. Kafka producer
batching, acks=all · rarely the limit if partitions are sane
bar = relative ceiling, illustrative only; measure yours per stage
Primary-side cost of N slots
WAL rate 30 MB/s (illustrative)
Each slot re-reads and decodes the whole WAL stream, even if its publication captures one small table. Cost scales with slots × WAL rate, not with how much you capture.
0
Polling queries on tables
100%
Deletes captured
Commit
Order of emission
Opposite
PG vs MySQL failure blast radius
Debezium is the de facto open-source implementation, usually run as Kafka Connect source connectors (also embedded, or as Debezium Server targeting non-Kafka sinks). Each table maps to a topic <prefix>.<schema>.<table>. The key is the row's primary key. The value is an envelope with before/after, op (c/u/d/r), and a source block carrying the LSN or binlog position, the transaction id and the commit timestamp. A delete is followed by a tombstone so that compaction can drop the key.
topic: shop.public.orders · partition = hash(key)
key: { "id": 42 }
value: {
before: { id: 42, status: "PAID", total: 99.00 }
after: { id: 42, status: "SHIPPED", total: 99.00 }
op: "u" // c · u · d · r(snapshot read)
source: { db, table: "orders", lsn: 0/1A3F2C8, txId: 8812, ts_ms }
ts_ms: 1727251200123 // when the connector processed it
}
DELETE → op:"d" (after=null), then a tombstone: key 42, value null
Elasticsearch sink
c/u/r → index doc _id=42 (upsert); d/tombstone → delete _id=42
Warehouse loader
append raw events to a bronze table; MERGE latest-by-lsn per id into orders_current
Cache invalidator
any event for key 42 → DEL order:42
Kafka log compaction
keeps the last value per key; tombstone lets key 42 disappear entirely
The envelope carries both images of the row plus provenance. Because the Kafka key is the primary key, every change to order 42 lands on the same partition in order — so each consumer sees that row's history as a clean, ordered sequence.
Worked example. UPDATE orders SET status='SHIPPED' WHERE id=42 commits. A u event keyed {id:42} lands on the partition that owns key 42, and three consumer groups act on it independently. An Elasticsearch sink upserts _id=42 with an external version. A warehouse loader appends the event to a bronze table and MERGEs the latest version per id. A cache invalidator deletes order:42. There is a caveat to the usual pitch that "next year's consumer replays the compacted topic". Compaction keeps the last value per key, so the replay gives you current state, not history. A consumer that needs transitions must be there from the start or read from the bronze table.
Architect's note
source.lsn is newer), which is the same technique the sinks in 6.6 use.WAL holds hours or days, not the ten years of rows already in orders, so a new connector must snapshot and then stream. The seam is the hard part. The mechanism Postgres provides is that creating a logical slot through the replication protocol can export a snapshot that is exactly consistent with the slot's start point LSN X. Reading tables under that snapshot and then streaming from the slot gives "never both, never neither". MySQL gets the equivalent from a consistent read plus a binlog position captured under a brief global or table lock. How closely a given Debezium version and snapshot mode follow the exact-export path varies. Treat the seam as at-least-once and make sinks idempotent, which you need anyway.
The initial snapshot reads the tables as of the exact LSN where the slot begins, so every row is either in the snapshot or in the stream — never both, never neither. Incremental snapshots re-read tables in PK chunks between two watermarks written into the log; any key the live stream changed inside that window is dropped from the chunk, because the log's version is newer.
Why the blocking snapshot fails at scale. Consider an illustrative 2 TB, 3-billion-row table read at 50k rows/s. That is roughly 17 hours inside a single REPEATABLE READ transaction. For those 17 hours the transaction holds back the xmin horizon, so vacuum cannot reclaim dead tuples on any table in that database, and your hottest update-heavy tables bloat for the entire run. Meanwhile the slot is already pinning 17 hours of WAL, and the snapshot cannot resume: a crash at 80% means starting over, with the same bloat again. On MySQL the equivalent cost is undo/history-list growth.
Incremental snapshots (from Netflix's DBLog paper) remove all three problems. Streaming never stops. A snapshot is triggered through a signal (a table, or a Kafka topic when the source is read-only) and proceeds in primary-key chunks (Debezium's default is 1,024 rows). For each chunk the connector writes a low watermark, selects the chunk, and writes a high watermark. While it replays the log between the two, it drops from the buffered chunk any key that appears as a live change, because the logged version is newer. Each chunk is a short transaction, progress is checkpointed, and one table can be re-snapshotted on demand.
The constraints are easy to miss. The chunking requires a primary key or an explicitly configured surrogate. On Postgres, the signal table must itself be in the publication, or the watermarks never appear in the stream and the snapshot stalls without an error. And snapshot r events for key 42 can arrive after stream events for key 43 from later in time. Per-key order still holds, but a consumer that assumed "all reads, then all changes" (for example, one that treats r as insert-only) will break. The decision rule is simple. Use a blocking snapshot for small tables or an empty sink during a maintenance window. Use incremental for anything over roughly an hour of read time, and for every re-snapshot on a live system.
Ordering is per key, and nothing more. Changes to different rows or tables are consumed concurrently, so an order_items insert can be processed before its parent orders insert. If you need transaction boundaries, use Debezium's transaction metadata topic and buffer until each transaction's event count is complete, or better, emit one outbox event per business transaction (6.7). Re-keying a CDC topic by anything other than the primary key throws that ordering away.
Delivery is at-least-once, so version your sinks. The connector writes to Kafka, then later commits its offset and flushes the LSN to the slot, and a crash in between replays. Kafka Connect's exactly-once source support (KIP-618) closes that gap inside Kafka only. The robust pattern is to store a version with every sink row and apply a change only if its version is newer. On Postgres, source.lsn works as a per-row version for a non-obvious reason. Two transactions cannot both have uncommitted changes to the same row, because the second blocks on the row lock until the first commits. So the second transaction's change record is written after the first one's commit record, and per row, change LSN order equals commit order. It fits in a 64-bit long, so Elasticsearch's version_type=external accepts it directly, and the warehouse MERGE takes max-LSN per key. MySQL has no equivalent. A binlog file+offset is local to one server, and a GTID set is not a single ordered number across server UUIDs, so after a failover a naive "newer position" comparison is wrong. On MySQL, version from a column you control (a row version or a monotonic updated_seq) or from Kafka offsets within one uninterrupted topic.
A replication slot is a promise: "keep every WAL segment after restart_lsn until I confirm it." If the consumer disappears, the promise stands. Illustratively, a primary generating 50 MB/s of WAL retains ~180 GB per hour of stall. The cap converts a primary outage into a resnapshot — almost always the right trade, but it is still data-pipeline downtime you must have rehearsed.
Sizing the slot risk. Headroom in hours is free disk divided by peak WAL rate, and the peak is not the average. Index rebuilds, bulk updates and full-page writes after each checkpoint can multiply WAL rate several-fold. For example (illustrative), 400 GB of free disk at a 20 MB/s peak gives about 5.5 hours from connector death to primary outage, which is shorter than many on-call escalation paths once a weekend is involved. Set max_slot_wal_keep_size (Postgres 13+) below that point, and alert on pg_wal_lsn_diff(pg_current_wal_lsn(), confirmed_flush_lsn) in bytes. Alerting on "connector task RUNNING" is not enough, because a connector stuck retrying a poisoned sink is RUNNING and not acking. Three quieter variants of the same failure:
The quiet database. WAL is cluster-wide. A slot on a database whose tables rarely change gets nothing to acknowledge, so it never advances while other databases on the same cluster generate WAL. Debezium heartbeats with a heartbeat.action.query that writes to a tiny table force traffic through the slot. catalog_xmin. A lagging logical slot also holds back vacuum of the system catalogs. Workloads that churn temp tables or run heavy DDL bloat pg_catalog, and the symptom is planning latency, not disk alerts. Big transactions. The decoder buffers each transaction until commit and spills to disk beyond logical_decoding_work_mem (64 MB by default, Postgres 13+). A 10-million-row UPDATE therefore becomes a spill-file storm on the primary, followed by a burst that spikes consumer lag. Postgres 14+ can stream in-progress transactions to plugins that ask for it, but do not assume your connector does. Batch backfills instead.
Recovery is a headroom problem. Disk sizing tells you how long you can stall. It does not tell you how long you stay stale once the stall ends. Replay drains at capacity minus ingress, not at capacity. Teams size connectors to "keep up with peak" and discover the gap only after the first long outage. In the illustrative example below, the same 4-hour stall costs 8 more hours of staleness at 1.5× headroom and over a day at 1.1×, and the slot keeps the primary's WAL pinned the whole time. The cascade usually runs like this: the sink degrades, the connector retries with the task still RUNNING, lag builds without a page, someone fixes the sink, replay starts at peak traffic, and freshness SLAs blow for the rest of the business day. Treat 2× steady-state headroom as a working floor for any pipeline with a freshness SLA (a rule of thumb, not a standard), and load-test the drain rate, not just the steady-state rate.
All numbers illustrative. Time to recover = backlog ÷ (capacity − ingress). Capacity only matters through the gap. At 1.1× headroom a 4-hour stall costs well over a day of staleness, and the WAL (or binlog read position) stays pinned for all of it.
Replay or resnapshot? The conventional answer is always to replay, because it is lossless. For state sinks (search, cache, orders_current) that is often the slower and more expensive choice. Replay cost scales with change volume. Resnapshot cost scales with table size. Consider an illustrative 5-million-row table taking 2,000 updates/s: a day's backlog is about 170 million events, or 35 times the table. An incremental snapshot of 5 million rows finishes in minutes. The rule: if the backlog exceeds the table's row count by a wide margin and the sink only needs current state, abandon the backlog for that table, re-snapshot it, and let versioned upserts absorb the overlap. A slot cannot skip one table's changes, so in practice this means discarding that table's backlog events older than the snapshot's starting position, at the sink or with a filter. If every table qualifies, drop and recreate the slot instead, which also releases the pinned WAL at once. Replay only for sinks that need transitions: audit, bronze history, and anything that computes diffs. Decide this per table, in the runbook, before the incident.
Failover. Before Postgres 17, a logical slot on the primary did not survive promotion of a standby. A failover loses the slot, and every change between the last ack and the new slot's creation is silently gone, so you resnapshot. Postgres 16 allows decoding on a standby, and Postgres 17 adds failover-synchronized slots. On a managed service, check what the provider actually exposes before you rely on either. TOAST. Unchanged out-of-line values are omitted from update records, and Debezium substitutes __debezium_unavailable_value, so a naive sink overwrites real text with the placeholder. Use REPLICA IDENTITY FULL on those tables, or have sinks treat the placeholder as "keep the existing value". Schema changes. Postgres has no DDL in the stream, so Debezium only discovers a new shape when the next row arrives. MySQL DDL is in the binlog, and Debezium keeps a schema-history topic to decode old events (lose that topic and the connector cannot restart). Either way, run migrations expand-then-contract and set registry compatibility deliberately.
Per key
Ordering guarantee
≥ 1×
Delivery — version every sink
~180 GB/h
WAL pinned at 50 MB/s (illustrative)
PG 17
Failover-synced slots
Pointing Debezium at your tables makes your physical schema a public API. Column renames become cross-team migrations, internal status codes become contracts, and consumers rebuild business meaning from row diffs spread across topics with no ordering between them. The transactional outbox (Distributed Systems track, Chapter 6) separates the two. The service inserts a designed, versioned event into an outbox table in the same transaction as the business write. Debezium captures only that table, and the Outbox Event Router routes by aggregate type and keys by aggregate id.
CDC on raw tables
▸ orders, order_items, addresses → 3 topics
▸ events = row diffs, columns as-is (incl. internal flags)
▸ a column rename is a breaking change for every consumer
▸ one business action = N row events to re-join downstream
▸ zero app changes; captures writes from every path (scripts, migrations, admin SQL)
Best for data replication you own end-to-end: warehouse, search, cache, audit.
Transactional outbox + CDC
▸ BEGIN; UPDATE orders…; INSERT INTO outbox(…); COMMIT;
▸ outbox row = OrderShipped v2 { orderId, items, carrier }
▸ Debezium Outbox Event Router: topic by aggregatetype, key = aggregateid
▸ internal schema can change freely behind the event
▸ rows may be deleted right after insert — the WAL already has them
Best for integration events between services and teams: a versioned public API.
Both ride the same log-based machinery and both are atomic with the business write. The difference is what you are promising: raw-table CDC exports your storage layout; the outbox exports a domain event you chose to publish.
Three refinements and one trap. Delete in the same transaction: the insert is already in the WAL, so the table never grows and never needs vacuuming. On Postgres, pg_logical_emit_message(true, …) writes a transactional message straight into the WAL with no table at all. The price is that Debezium surfaces these as a separate message type, so you lose the stock router. Put the event's schema version in the payload or a header, not only in the topic name, so consumers can handle a mixed stream during a rollout. The trap: once outbox rows are deleted, the only copy of your events is the Kafka topic. You cannot re-snapshot an outbox, so topic retention is now a durability decision. Anyone who expects to replay integration events from a year ago needs a real archive (tiered storage or a sink to object storage), because the outbox is not an event store.
The decision rule is about who consumes. Use raw-table CDC when the consumers are replicas of your own data — warehouse, search, cache, audit — owned by you or a platform team that accepts the coupling. Use the outbox when other services react to business facts and the event is part of your public API. Mature systems run both from the same database. For audit, raw CDC wins outright: it records the admin-console edit and the 2 a.m. hotfix SQL, and an application-level outbox never sees either.
Deletes & intermediate states
Atomic with the write
Load / risk on the primary
What consumers couple to
Prerequisite
Dual write + nightly reconcile
reconcile only
no
low
your app code
none — and it shows
xmin-bounded polling
no · final state only
yes (reads committed)
index + range scan per poll
table shape
no replication privilege
Raw-table log CDC
all, in commit order
yes
slot pins WAL · 1 full decode per slot
physical schema
replication role · REPLICA IDENTITY choice
Outbox + log CDC
only events you emit
yes
same slot risk · tiny table
a designed contract
code change on every write path
Decode on standby (PG 16+)
all, in commit order
yes
decode CPU moves off primary · needs hot_standby_feedback
physical schema
provider support · standby lag adds latency
Read the columns as questions in this order: must consumers see deletes and transitions? Must propagation be atomic with the write? Who owns the coupling? Only then ask about primary-side cost, which is the column you can most often engineer around.
Where the conventional advice is wrong. "Always use the outbox for events" ignores that the outbox is only as complete as the code paths that write it. A bulk UPDATE from a migration, a support tool writing SQL directly, or a second service sharing the database all bypass it without anyone noticing. If a consumer's correctness depends on seeing every change, the outbox is the wrong primitive, whatever the layering argument says. Conversely, "raw CDC is zero-effort" ignores the ongoing cost: every schema change needs a consumer impact review from then on. Past a handful of consuming teams, that review becomes a bigger tax than writing outbox events would have been.
Questions for the design review
max_slot_wal_keep_size set below that, and has anyone rehearsed the resnapshot it triggers?2. What is the measured drain rate against peak ingress? How long are we stale after a 4-hour stall?3. How many slots are on this cluster, who owns each, and could they be one slot fanned out in Kafka?4. What is each sink's version column, and what happens on MySQL after a failover?5. Which tables have REPLICA IDENTITY FULL or TOASTed columns, and does any consumer depend on before?6. Per table: after a long outage, do we replay or resnapshot? Who decides, and is it written down?7. What writes this database outside the application, and does the chosen mechanism see those writes?1
Commit point, always
Raw CDC
Replicate your data
Outbox
Publish a contract
Versioned
Every sink write
Where next