Skip to content

Change Data Capture and the Outbox Pattern

Intermediate 44 min read Part 8 of 18

Stream every database change to caches, search indexes and warehouses from the database's own log, and publish events reliably with an outbox.

Summary#

When one database is the source of truth but other systems (a search index, a cache, a warehouse, other services) need its data, writing to all of them from application code (a dual write) eventually leaves them out of sync. Change data capture (CDC) reads every committed change from the database's own replication log (the MySQL binlog or the Postgres write-ahead log) and streams it, in commit order, to a broker such as Kafka. Tools like Debezium do this for most popular databases. The transactional outbox applies the same idea to business events: the service writes an event row in the same transaction as its data, and CDC or a relay publishes it. The cost is an extra pipeline to run, delivery that is asynchronous (typically tens of milliseconds to seconds behind) and at-least-once, and care with ordering and schema changes.

Why It Exists#

Picture a product catalogue. Postgres holds the products and is the source of truth. Elasticsearch powers product search. Every time a product is created, renamed, repriced or deleted, the search index must change too.

The obvious approach is to have the application update both: write to Postgres, then write to Elasticsearch. It works in a demo. In production, it drifts:

  • Partial failure. The Postgres write succeeds and the Elasticsearch write times out. The product is renamed in the database but still found under its old name in search.
  • Crashes in between. The service process dies after committing to Postgres but before calling Elasticsearch. No retry logic runs, because the process that would retry is gone.
  • Races. Two requests update the same product at nearly the same time. Postgres applies them in the order A then B. The two Elasticsearch calls arrive in the order B then A. Search now permanently shows A's version, while the database holds B's, and nothing will ever correct it.
  • Rollbacks after publishing. If the code publishes first and then the transaction rolls back, downstream systems have a change that never happened.

You can add retries, idempotency keys and reconciliation jobs, but you are rebuilding, badly, something the database already has. Every database that supports replication already keeps an exact, ordered, durable record of every committed change. It needs that record to recover from crashes and to feed its replicas. CDC simply lets other systems read that record too.

The same problem appears between services. An order service that saves an order and then publishes OrderPlaced to Kafka has the same dual write and the same failure modes. The outbox pattern fixes that case by putting the event into the database transaction, so that the database log carries the event too.

How It Works#

The idea has three parts. The database already writes every committed change to a log. A CDC connector reads that log, much like a replica would, and turns each change into a change event. The connector publishes change events to a durable stream (usually Kafka), where any number of consumers read them at their own pace.

The application only writes to its own database. Everything downstream is derived from the log, so every consumer eventually sees every committed change, in the order the database committed it, and never sees a change that was rolled back.

The dual-write problem#

A dual write is any code path that updates two systems with no transaction spanning both. It shows up as "save to the database, then publish to Kafka", "save, then update the cache", "save, then call the search service", or "save, then call the billing service".

The problem is not that one write might fail. It is that two independent systems cannot agree on an outcome or an order without coordination, and the application is a poor coordinator. It can crash, it runs on many machines at once, and its network calls can be delayed for arbitrary amounts of time.

The dual-write problem, in depth#

It helps to list exactly which failures dual writes cause, because each popular fix only handles some of them.

FailureExampleRetries fix it?Idempotency fixes it?
Second write failsKafka times out after the DB commitYes, if the process survivesMakes retries safe
Process crashes between writesPod killed by a deploy after commitNo, the retry state is lostNo
Concurrent writes reorderTwo updates to one row raceNoNo
First system rolls backPublish, then the DB transaction abortsNoNo
Second write succeeds but the reply is lostEvent published twice after a retryCauses itYes

Why distributed transactions do not rescue you. The textbook answer to "two systems must agree" is two-phase commit (2PC), covered in Distributed Transactions. In practice, it is rarely available here. Kafka, Elasticsearch and Redis do not take part in XA transactions with your database. Where 2PC is available, it adds round trips to every write, and a coordinator failure can leave participants blocked holding locks. For "keep a derived copy in sync", the cost is far higher than the benefit.

Why "write to Kafka first, then consume into the database" is not a full answer. Some teams invert the flow. The service publishes the change to Kafka, and a consumer (possibly the same service) writes it to the database. This is sometimes called "listen to yourself". It removes the dual write, because the log is the single source of truth, but it loses something big: the database can no longer validate the write synchronously. A uniqueness check, a balance check or a foreign-key check now happens after the request has already been accepted. For event-sourced systems that is the design (see Event Sourcing and CQRS). For ordinary CRUD services, it makes simple things such as "reject a duplicate username" much harder.

Why reconciliation is only a backstop. A nightly job that compares the database with the index and fixes differences is worth having anyway, but on its own it means search can be wrong for up to a day. Scanning hundreds of millions of rows also costs real load. CDC makes drift rare, and reconciliation catches the rare cases left over, such as bugs in the indexer.

The general rule: write to exactly one system synchronously, and derive everything else from that system's log. CDC derives from the database's log. The outbox lets you put events into that log. Event sourcing makes the event log itself the primary store.

Ways to capture changes#

There are three ways to find out what changed in a database. Only the third is what people usually mean by CDC today, but the first two are still common, and it is worth knowing why they lose.

Query-based capture (polling). Every table gets an updated_at column with an index. A job runs SELECT ... WHERE updated_at > :last_seen ORDER BY updated_at every few seconds and ships the results. The Kafka Connect JDBC source connector works this way.

Trigger-based capture. Database triggers on each table write a copy of every insert, update and delete into a change table, inside the same transaction. A job reads and drains the change table.

Log-based capture. The connector reads the database's own transaction log, the same stream that replicas consume, and decodes each committed change.

PropertyQuery-basedTrigger-basedLog-based
Captures deletesNo, unless you use soft deletesYesYes
Captures every intermediate stateNo; two updates between polls look like oneYesYes
Extra load on the databaseRepeated index scansExtra write per change, inside the transactionReading the log, usually small
LatencyThe polling interval, often secondsPolling the change tableTypically milliseconds to about a second
Requires schema changesAn updated_at column and indexTriggers and change tablesNone, but needs log settings and permissions
OrderingBy timestamp, which is unsafe under clock skew and long transactionsChange-table sequenceExact commit order
Sees a transaction's changes togetherNoPartlyYes, with transaction metadata

Query-based capture has a subtle flaw beyond missing deletes. Timestamps are assigned when a row is written, not when the transaction commits. A long transaction can write a row with updated_at = 10:00:00 but commit at 10:00:07. If the poller already advanced past 10:00:05, it never sees that row. Fixes such as a safety lag ("only read rows older than 30 seconds") trade latency for correctness. Log-based capture avoids the issue entirely, because the log is in commit order.

Log-based CDC: reading the binlog or the WAL#

Every durable database writes changes to a sequential log before (or as) it changes its data files. The log exists for two internal reasons: crash recovery (replay the log to restore committed changes) and replication (ship the log to replicas). Log-based CDC is a third reader of the same log.

  • Postgres writes the write-ahead log (WAL). The physical WAL describes changes to disk pages, which is useless to anything but another Postgres server. Logical decoding, enabled with wal_level = logical, turns WAL records back into row-level changes: "insert into products, row with these values". A replication slot is a named cursor that remembers how far a consumer has read, and it stops Postgres from deleting WAL the consumer still needs. An output plugin such as pgoutput (built in, used by native logical replication) formats the decoded changes. A publication selects which tables are included.
  • MySQL writes the binary log (binlog) for replication. With binlog_format = ROW, each event contains the actual row images rather than the SQL statement. With binlog_row_image = FULL, updates include the whole row before and after the change. A CDC connector connects as if it were a replica, asks for the binlog from a position (or from a GTID set, a global transaction identifier), and receives events as they are written.
  • MongoDB exposes change streams, an API over its replication oplog, with a resume token for restarting where you left off.
  • SQL Server has built-in CDC that copies changes from its transaction log into change tables. Oracle offers LogMiner and GoldenGate for reading redo logs.
  • DynamoDB Streams and Cassandra CDC provide the equivalent for those stores. DynamoDB Streams keeps each change record for 24 hours, ordered per item.

Each of these gives the connector the same four things: the change (table, key, old and new values), its position in the log (a log sequence number, LSN, in Postgres; a binlog file and offset, or a GTID, in MySQL), the transaction it belonged to, and the commit time.

Notice that the application's request finishes as soon as Postgres commits. CDC adds nothing to the write path. The connector runs entirely in the background.

Log-based CDC, in depth#

What a change event contains. Debezium's events are a good model, because most tools copy their shape:

{
  "before": { "id": 7, "name": "Desk lamp", "price": 10.00 },
  "after":  { "id": 7, "name": "Desk lamp", "price": 12.00 },
  "op": "u",
  "ts_ms": 1767225600123,
  "source": {
    "connector": "postgresql", "db": "shop", "schema": "public",
    "table": "products", "lsn": 23803720, "txId": 91822,
    "ts_ms": 1767225600101, "snapshot": "false"
  }
}

op is c (create), u (update), d (delete) or r (read, meaning a row emitted during an initial snapshot). For a delete, after is null. Debezium usually follows a delete with a tombstone, a record with the same key and a null value, so that Kafka log compaction can eventually remove every record for that key. The two timestamps let you measure lag: source.ts_ms is when the database committed, and ts_ms is when the connector processed the change.

The "before" image is not always there. In Postgres, the old row values for updates and deletes depend on the table's replica identity. With the default setting, Postgres logs only the old primary key. With REPLICA IDENTITY FULL, it logs the whole old row, at the cost of more WAL. A related trap is TOAST, Postgres's out-of-line storage for large values. If an update does not touch a large text column, the decoded change may leave that column out, marked as "unchanged toasted value", unless the replica identity is FULL. A consumer that blindly overwrites a document with the change event can then wipe a field. Indexers must treat "missing" as "unchanged", not as "null".

Replication slots can fill your disk. A Postgres slot keeps every WAL segment that its consumer has not confirmed. If the connector is down for a day on a database writing 50 GB of WAL a day, the primary keeps an extra 50 GB on disk, and if the disk fills, the primary stops accepting writes. This is the most common CDC production incident. Defences:

  • Monitor slot lag (the bytes between pg_current_wal_lsn() and the slot's confirmed_flush_lsn) and alert well before the disk is at risk.
  • Set max_slot_wal_keep_size (Postgres 13 and later) so that Postgres invalidates a slot that falls too far behind, instead of taking down the primary. The connector then has to re-snapshot, which is far better than an outage.
  • Drop slots that belong to retired consumers. An abandoned slot keeps growing forever.

A second, quieter version of the same problem: if the captured tables are idle but other tables in the database are busy, the connector receives nothing to confirm, so the slot never advances while WAL keeps growing. Debezium's heartbeat setting fixes this by periodically emitting a heartbeat record (optionally writing to a small heartbeat table), so that the confirmed position keeps moving.

Slots and failover. A logical replication slot historically lived only on the primary. After a failover, the new primary had no slot, and the connector could not resume exactly where it left off. It either re-snapshotted or risked missing changes. Postgres 17 added synchronisation of logical slots to standbys, so a slot can survive failover. On older versions, plan for a re-snapshot after failover, or use a managed service that handles slot failover for you. MySQL with GTIDs is more forgiving: the connector stores the GTID set it has processed, and any replica that has those transactions can continue the stream.

Binlog retention. MySQL deletes old binlog files after binlog_expire_logs_seconds. If the connector is down longer than the retention, the position it needs no longer exists, and it must re-snapshot. Size retention for your worst realistic outage, typically several days.

The initial snapshot and the handoff. A new CDC pipeline starts with a database that already holds data. The connector must first emit every existing row (the snapshot) and then switch to streaming, without losing or misordering any change in between. The classic approach:

  1. Create the replication slot (or record the binlog position). This marks point P in the log.
  2. Read every table in a transaction that sees exactly the database state at P. Postgres can export the snapshot taken when the slot is created, and MySQL connectors briefly hold a lock or use a consistent snapshot to align the read with a binlog position.
  3. Emit every row as an r event.
  4. Start streaming from P.

Rows changed during the snapshot appear in the stream after P, so consumers that apply events in order converge on the right state. The weakness is size. Snapshotting a 2 TB table can take many hours, during which the slot holds WAL and no live changes flow.

Incremental snapshots. Netflix described a better approach in "DBLog: A Watermark Based Change-Data-Capture Framework" (Andreas Andreakis and Ioannis Papapanagiotou, 2020). The snapshot runs in small chunks, interleaved with live streaming, so live changes keep flowing. The trick is to write a low watermark to a watermark table, select one chunk of rows by primary key, then write a high watermark. Both watermark writes appear in the log. Any row in the chunk that also appears in the log between the two watermarks has been changed concurrently. The log version is newer, so that row is dropped from the chunk. The rest of the chunk is emitted at the high watermark position. Debezium adopted the same idea as incremental snapshots, triggered by a signal, which also lets you re-snapshot a single table later without restarting the pipeline.

How much does CDC cost the database? Reading the WAL or the binlog is sequential and cheap compared with serving queries. The main costs are elsewhere. Logical decoding uses CPU on the primary, roughly in proportion to the volume of changes. REPLICA IDENTITY FULL or binlog_row_image = FULL make the log bigger. And a stalled slot retains WAL. For most OLTP databases writing a few thousand rows per second, a single connector is a small fraction of the server's load. Teams with very high write rates often run CDC against a replica where the database allows it (MySQL can stream the binlog from a replica, and Postgres 16 and later can do logical decoding on a standby), so that the primary does none of the decoding work.

Debezium and Kafka#

Debezium is the most widely used open-source CDC platform. It is an open-source project sponsored by Red Hat, with connectors for Postgres, MySQL, MariaDB, MongoDB, SQL Server, Oracle, Db2, Cassandra and others. It usually runs on Kafka Connect, Kafka's framework for moving data in and out of Kafka. Connect runs source connectors (which read from an external system into Kafka) and sink connectors (which write from Kafka into an external system) as managed, restartable tasks in a cluster of worker processes.

A typical setup:

  • A Debezium source connector per database. It writes one Kafka topic per captured table, named like shop.public.products (server name, schema, table).
  • The record key is the row's primary key. Kafka sends all records with the same key to the same partition, so all changes to one row stay in order.
  • The record value is the change event (before, after, op, source).
  • The connector's position in the log (the LSN, binlog position or GTID set) is stored as a Connect offset in an internal Kafka topic. After a restart, the connector resumes from the last stored offset.
  • Records are serialised with a converter: JSON for simplicity, or Avro or Protobuf with a schema registry, which stores each table's schema version and lets consumers decode safely as schemas change.
  • Sink connectors move the data onward: an Elasticsearch sink, a JDBC sink to another database, an S3 sink for the data lake. Or you write your own consumers.

Kafka is the natural partner because it is a durable, replayable, partitioned log. A consumer added next year can start from the earliest retained offset. With log compaction enabled on a CDC topic, Kafka keeps at least the latest record for every key indefinitely. A new consumer can then rebuild a full copy of the table from the topic alone, without touching the source database.

Debezium can also run without Kafka Connect. Debezium Server is a standalone process that sends change events to other targets such as Amazon Kinesis, Google Pub/Sub, Pulsar or Redis Streams. The Debezium Engine embeds a connector as a library inside your own Java application.

Debezium, in depth#

A minimal Postgres connector configuration.

{
  "name": "orders-cdc",
  "config": {
    "connector.class": "io.debezium.connector.postgresql.PostgresConnector",
    "database.hostname": "orders-db.internal",
    "database.dbname": "orders",
    "database.user": "cdc_reader",
    "topic.prefix": "orders",
    "plugin.name": "pgoutput",
    "slot.name": "debezium_orders",
    "publication.name": "dbz_orders",
    "table.include.list": "public.orders,public.order_items,public.outbox",
    "snapshot.mode": "initial",
    "heartbeat.interval.ms": "10000",
    "tombstones.on.delete": "true",
    "key.converter": "io.confluent.connect.avro.AvroConverter",
    "value.converter": "io.confluent.connect.avro.AvroConverter"
  }
}

The database side needs wal_level = logical, a user with the replication privilege and read access to the captured tables, and enough max_replication_slots and max_wal_senders.

Delivery guarantees. By default, Debezium gives at-least-once delivery. The connector writes events to Kafka and only later commits its offset. If it crashes in between, it replays from the last committed offset after a restart, re-emitting some events. Kafka Connect added support for exactly-once source connectors (KIP-618, in Kafka 3.3), which commits records and offsets in one Kafka transaction, and Debezium supports it for some connectors. Even so, the sink or consumer side has its own failure window. So the robust rule is unchanged: design every CDC consumer to be idempotent. See Delivery Semantics. For CDC, idempotency is unusually easy. Each event carries the source position (the LSN), which only ever increases for a given row. A consumer that stores the last applied LSN per key and ignores anything older handles both duplicates and replays.

Single message transforms (SMTs). Connect can apply small transformations to each record in flight. Two Debezium SMTs come up often:

  • New record state extraction (often called "unwrap") flattens the before/after envelope into just the new row, which many sinks expect.
  • The outbox event router turns rows of an outbox table into proper events on per-aggregate topics (covered below).

Keep SMTs simple. Heavy business logic belongs in a stream processor or a consumer, where it can be tested and versioned.

Monitoring. Watch these four signals:

  1. Connector status (running, failed, paused) and task restarts.
  2. End-to-end lag: the time between commit (source.ts_ms) and processing, or Debezium's "milliseconds behind source" metric. A healthy pipeline is usually well under a second. Sustained growth means the connector or Kafka cannot keep up.
  3. Replication slot retained WAL, or binlog position versus retention.
  4. Consumer group lag on each CDC topic, per consumer.

Throughput. One Debezium connector reads one database's log with a single task, because the log is a single ordered stream. A single connector commonly handles thousands to tens of thousands of change events per second, depending on event size, converters and network. That is enough for most OLTP databases, because those rarely sustain more row changes than that. If one database produces more, the bottleneck is usually serialisation or Kafka produce settings (batching, compression), not log reading. Downstream, topics can have many partitions, so consumers scale out by key.

The transactional outbox#

Table-level CDC publishes what changed in a row. Often, other services need what happened in the business: "order 42 was placed with these items", not "a row in orders changed and three rows in order_items changed". The transactional outbox gives you business events with the same reliability as CDC.

  1. The service creates an outbox table in its own database.
  2. In the same transaction as its normal writes, it inserts one row per business event: an event ID, the aggregate type and ID, the event type, and the payload.
  3. A relay reads new outbox rows and publishes them to the broker. The relay is either CDC on the outbox table, or a polling process.
  4. Consumers read the events and deduplicate by event ID.

Because the business change and the event commit atomically, either both happen or neither does. No crash window exists between "saved" and "published". If the relay is down, events wait in the table and are published when it recovers.

CREATE TABLE outbox (
  id             uuid PRIMARY KEY,           -- event ID, used for dedup
  aggregate_type text        NOT NULL,       -- e.g. 'order', picks the topic
  aggregate_id   text        NOT NULL,       -- e.g. '42', becomes the message key
  type           text        NOT NULL,       -- e.g. 'OrderPlaced'
  payload        jsonb       NOT NULL,
  created_at     timestamptz NOT NULL DEFAULT now()
);
 
BEGIN;
INSERT INTO orders (id, customer_id, total_cents, status)
  VALUES (42, 1001, 5998, 'placed');
INSERT INTO outbox (id, aggregate_type, aggregate_id, type, payload)
  VALUES (gen_random_uuid(), 'order', '42', 'OrderPlaced',
          '{"orderId":42,"customerId":1001,"totalCents":5998}');
COMMIT;

Debezium's outbox event router reads the outbox table's change events, routes each one to a topic chosen by aggregate_type (for example outbox.event.order), uses aggregate_id as the Kafka key so that all events for one order stay in order, and passes the event ID as a header for deduplication.

The outbox, in depth#

CDC relay or polling relay? Both are valid.

  • A CDC relay (Debezium on the outbox table) has low latency, adds no query load, and preserves commit order. It needs the CDC infrastructure: log settings, a slot or binlog access, and Kafka Connect.
  • A polling relay is a small process that runs a query like the one below every 100 ms to 1 s, publishes the rows, then marks or deletes them. It needs nothing but the database, which makes it a good first version.
-- polling relay: claim a batch without blocking other relay instances
WITH batch AS (
  SELECT id FROM outbox
  WHERE published_at IS NULL
  ORDER BY created_at
  LIMIT 500
  FOR UPDATE SKIP LOCKED
)
UPDATE outbox o SET published_at = now()
FROM batch WHERE o.id = batch.id
RETURNING o.*;
-- publish the returned rows, then COMMIT; on failure ROLLBACK and they reappear

FOR UPDATE SKIP LOCKED lets several relay instances run without picking the same rows. The relay publishes inside the transaction and commits only after the broker acknowledges. A crash after publishing but before the commit means the rows are published again. That is at-least-once, which is why consumers deduplicate. Polling has the timestamp-ordering weakness described earlier: two concurrent transactions can commit in the opposite order from their created_at values. If per-aggregate order matters, order by a per-aggregate sequence number written by the service, or use the CDC relay.

Keeping the outbox small. Outbox rows are only needed until they are published. With a CDC relay you can delete the row in the same transaction right after inserting it. The insert is still in the WAL, so CDC sees it, but the table never grows. Debezium's outbox router ignores the delete. Postgres also offers pg_logical_emit_message(), which writes a message straight into the WAL without any table. Debezium can capture these as logical decoding messages, giving an outbox with no table at all. With a polling relay, delete published rows in batches, or partition the table by day and drop old partitions, because large deletes on a hot table cause bloat.

The inbox, the consumer's half. The outbox guarantees that every event is published at least once. The consumer must turn "at least once" into "effect applied once". The inbox pattern records each processed event ID in a processed_events table in the same transaction as the consumer's own state change. A redelivered event finds its ID already present and is skipped. See Idempotency.

Outbox events are a public contract. An outbox event is designed deliberately, versioned, and documented. It should not just mirror the row. This is the outbox's biggest advantage over raw table CDC, and it leads to the most useful question in this whole topic.

Table CDC or outbox: does the consumer need a copy, or a reason? Ask what the consumer needs:

  • If it needs a copy of the data, use table CDC. Examples: a search index, a cache, a warehouse table, a read replica in another service. It wants the current state of rows and does not care why they changed. Row change events are exactly that, and the source team does not have to write any publishing code.
  • If it needs to know what happened and why, use an outbox event. Examples: send an email, start a fulfilment workflow, charge a card. A row change event cannot tell "the order shipped" from "an engineer corrected a status column", "a backfill rewrote every row" or "a migration copied the table". A consumer that sends an email on every row update with status = 'shipped' will one day email a million customers during a data repair, or again on every re-snapshot. Intent has to be published explicitly.

Table CDC also exposes your internal schema. Every consumer of orders.public.orders is coupled to your column names. Renaming a column can break three other teams. For consumers inside your own team (your own search index, your own cache), that coupling is acceptable. For consumers in other teams, publish designed events through an outbox, or put a translation step in a stream processor that maps internal row changes into a stable public schema.

CDC use cases#

CDC is the standard way to keep derived data in sync with a source of truth. Derived data is any copy, index or aggregate that can be rebuilt from the source.

  • Search indexing. Keep Elasticsearch or OpenSearch in step with Postgres or DynamoDB. This is by far the most common reason CDC appears in designs. Search engines are poor primary databases, so they are fed from one. See Elasticsearch.
  • Cache invalidation and refresh. Delete (or update) cached entries when their source rows change, so that no application code path can forget to.
  • Analytics and the data warehouse. Stream OLTP changes into Snowflake, BigQuery, Redshift, or a lakehouse table on S3, instead of nightly full exports. See Data Pipelines, Warehouses and Lakes.
  • Zero-downtime database migration. Copy a live database to a new engine, schema or shard layout while it keeps taking writes, then cut over. See Data Migration.
  • Data sharing between microservices. Service B keeps a local read-only copy of the parts of service A's data it needs, so it does not call A on every request.
  • Audit logs and history. Keep every version of every row, with timestamps and transaction IDs, without the application having to write audit rows.
  • Materialised views and streaming joins. A stream processor (Flink, Kafka Streams) joins several CDC streams into a precomputed view, for example orders enriched with customer and product data.

CDC use cases, in depth#

Search indexing without stale overwrites. The indexer consumes the product topic and upserts each after image into Elasticsearch (or deletes the document on d). Two subtleties matter.

First, guard against out-of-order application. Ordering holds per key within a partition, but replays after a failure, or a second indexer instance briefly processing the same partition during a rebalance, can apply an older change after a newer one. Elasticsearch supports external versioning: index with version_type=external and the source LSN (or another increasing number) as the version, and Elasticsearch rejects any write with a version lower than the stored one. The index converges no matter how events are replayed.

Second, documents often join several tables. A product search document might include the brand name, category path and current stock. A change to a brand must update every product of that brand. You can either have a stream processor maintain the joined document from several CDC streams (stateful, but precise), or have the indexer re-read the joined row from the source database when any part changes (simpler, but adds read load and needs care for consistency). Elasticsearch is eventually consistent anyway: a document becomes searchable only after a refresh, by default about once per second. Searches are usually about 1 to 2 seconds behind the database end to end, and product teams must accept that.

Cache invalidation: a good backstop, a poor sole mechanism. CDC-driven invalidation means no code path can forget to invalidate the cache, which is a real benefit when many services or scripts write to the same tables. But it has two limits. The first is lag. Between the commit and the invalidation, typically tens of milliseconds to a few seconds and much longer if the pipeline is unhealthy, readers still get the old value. A user who updates their profile and reloads the page can see the old one. When a change must be visible immediately to the person who made it, invalidate (or update) the cache synchronously in the write path, or route that user's reads to the primary for a short window, and keep CDC as the backstop. The second limit is a race with cache-aside refills. A reader misses the cache, reads the old value from a lagging replica, and writes it to the cache after the CDC invalidation has already run. The stale value then lives until its TTL expires. Mitigations are to set the cache with a version and refuse older versions, delete again after a short delay ("delayed double delete"), and always keep a TTL as the last line of defence. Cache Eviction and Invalidation covers these races.

When a very hot key must be refreshed rather than deleted, because deleting would send thousands of concurrent readers to the database at once, the CDC consumer can write the new value into the cache instead of deleting it, using the version check above. That avoids the stampede that a delete would trigger.

Warehouse loading. CDC events are a stream of upserts and deletes, but analytical stores prefer large, append-only batches. The common pipeline lands raw change events in object storage (S3 or GCS), then periodically merges them into the warehouse table, keeping the latest version of each key and removing deleted keys (MERGE INTO). Open table formats such as Apache Iceberg, Delta Lake and Apache Hudi exist largely to make this kind of upsert efficient on files in object storage. Merge every few minutes and the warehouse is minutes fresh. Merge every hour and it is cheaper. This replaces the nightly "dump the whole table" job, which grows slower every year and puts a heavy scan on the production database.

Not every analytics problem needs CDC. When events are born as events, such as ad clicks, page views or sensor readings, they should go straight into a stream or event store and be aggregated there, by batch jobs (for example Spark every few minutes into an OLAP store) or by stream processing for freshness. CDC is for state that lives in an OLTP database first. Likewise, data that changes very often and matters only for seconds, like a driver's location every few seconds, should not go through a relational database and CDC at all. It belongs in an in-memory store built for that write rate. CDC moves durable state. It is not a transport for high-frequency ephemeral signals.

Zero-downtime migration. To move from a single Postgres database to a sharded cluster, or from MySQL to Postgres:

  1. Start CDC on the old database, retaining changes from now on.
  2. Backfill the new store from a consistent snapshot (or an incremental snapshot).
  3. Apply the CDC stream to the new store until it catches up, then keep it applied continuously.
  4. Verify: compare row counts and checksums per key range, and run shadow reads that query both stores and log differences.
  5. Cut over reads gradually, then writes. Optionally run CDC in reverse, from the new store back to the old one, so that you can roll back.

The key property is that the old database never stops taking writes, and the cutover is a routing change measured in seconds.

Sharing data between services. When a pricing service needs product data from the catalogue service, it can call the catalogue API on every request (coupled availability, plus extra latency) or keep a local copy fed by CDC (decoupled, but eventually consistent). The local copy should be read-only and treated as a cache that can be rebuilt from the compacted topic. Only the owning service writes the source.

Ordering and schema changes#

Ordering. The database log is totally ordered: every committed change has a position. CDC keeps as much of that order as the downstream stream can represent:

  • Per row: preserved. Events are keyed by primary key, and Kafka keeps per-partition order, so every change to one row reaches consumers in commit order.
  • Across rows and tables: not preserved by default. Two rows usually land on different partitions or topics, and consumers read those independently. A consumer can see an order_items insert before the orders insert from the same transaction.
  • Transactions: optional metadata. Debezium can emit transaction boundary events (begin and end, with the number of events per table) and tag each change with its transaction ID. A consumer that needs whole transactions can buffer events until the end marker arrives.

Schema changes. Tables change: columns are added, renamed, retyped and dropped. CDC events carry the table's shape, so every schema change ripples to consumers.

  • In MySQL, DDL statements appear in the binlog. Debezium records them in a schema history topic so that it can decode older binlog events with the schema that was in force when they were written.
  • In Postgres, logical decoding does not emit DDL. The connector learns the new shape when the next change for that table arrives, through the relation metadata sent by pgoutput.
  • With a schema registry, each new shape becomes a new registered schema version, checked against a compatibility rule (for example backward compatible: new consumers can read old data).

The safe way to change a captured table is the expand and contract sequence. Add the new column as nullable, deploy writers that fill both columns, backfill, move consumers to the new column, and only then drop the old one. Every step is compatible with consumers that have not upgraded yet.

Ordering and schema changes, in depth#

Keeping order when you repartition. Per-key order depends on a key always mapping to the same partition. Adding partitions to a CDC topic changes the mapping for most keys. For a while, a row's older events sit in one partition and its newer events in another, and a consumer can apply them out of order. Avoid this by choosing a generous partition count up front, or by creating a new topic and migrating consumers. If you must change partitions, protect consumers with the version (LSN) check described earlier, which makes the order of arrival irrelevant.

Order across aggregates. If a consumer must see the parent before the children, for example an order before its items, there are three options:

  1. Key both topics by the parent ID (order ID) rather than by each table's own primary key, so that they share a partition number. Note that this only aligns order within one topic, and different topics still interleave arbitrarily.
  2. Use the outbox to publish a single OrderPlaced event that contains the items, so that the unit of ordering is the business event.
  3. Make the consumer tolerant. Store children whose parent has not arrived yet, and apply them when it does. This is how most robust consumers work anyway.

Option 2 is usually best for events between services, and option 3 for derived stores.

Transaction-consistent reads downstream. A consumer that applies change events one by one exposes intermediate states. A transfer between two accounts, applied halfway, shows money that has left one account and not yet arrived in the other. For warehouses this rarely matters, because queries run on data minutes old, and merges apply whole batches. For a read model that users see, buffer by transaction using the boundary events, or accept the brief inconsistency and design around it.

A schema-change worked example: renaming price to price_cents. A naive ALTER TABLE products RENAME COLUMN price TO price_cents breaks every consumer reading after.price. Changing the type from decimal dollars to integer cents at the same moment breaks them in a second way. Using expand and contract:

  1. Add price_cents BIGINT NULL. Change events now carry both fields, and old consumers ignore the new one.
  2. Deploy writers that set both price and price_cents on every write.
  3. Backfill price_cents for existing rows in small batches, for example 1,000 rows per transaction, so that the CDC stream and replicas are not flooded. A backfill of 50 million rows at 5,000 rows per second takes under 3 hours and produces 50 million change events, so tell downstream teams before you start.
  4. Move each consumer to price_cents, one at a time.
  5. Stop writing price, then drop it once no consumer reads it. Under backward compatibility, the registry accepts a dropped field only if consumers treat it as optional or have defaults.

The backfill in step 3 shows a general CDC fact: bulk data changes in the source become bulk event streams downstream. A one-line UPDATE products SET ... touching 50 million rows produces 50 million change events, which can lag every consumer by an hour. Batch large updates and schedule them.

Type mapping pitfalls. Databases have types that streams represent awkwardly. Decimals may arrive as base64-encoded bytes unless the connector is configured to emit them as strings or doubles. Timestamps lose time zone information. Postgres arrays, enums and JSON columns need explicit handling. Check how each column type appears in your events before consumers depend on them. A wrong mapping is far easier to fix before data exists in five downstream systems.

When to Use It#

  • A derived store must track a source database: search index, cache, warehouse, read model, or another service's local copy.
  • Writes already happen in many places, including several services, admin tools, scripts and migrations, so application-level hooks would miss some.
  • You need every change, including deletes, in commit order, not just the latest state found by periodic scans.
  • Nightly full exports are too slow, too stale, or too heavy on the production database. A few seconds of freshness from CDC replaces hours.
  • A service must publish events reliably after a database write. Use the outbox with a CDC or polling relay.
  • You are migrating a live database to a new engine, schema or shard layout without downtime.
  • Typical numbers: a source changing from hundreds to tens of thousands of rows per second, with consumers that can accept roughly 100 ms to a few seconds of lag.

When NOT to Use It#

  • The consumer needs intent, not a copy. Emails, payments, workflows and cleanup jobs should react to designed business events from an outbox, not to row changes that backfills and repairs also produce.
  • The change must be visible immediately to the writer (read-your-writes on a cache). Do the update synchronously, and keep CDC as a backstop.
  • A single database query is enough. If the search is over 100,000 rows that a Postgres full-text index or trigram index handles in milliseconds, a CDC pipeline plus Elasticsearch is a lot of machinery for nothing.
  • The data is born as events. Clickstreams, logs and metrics should be produced straight to a stream, not written to an OLTP database first just so that CDC can read them.
  • High-frequency ephemeral state, like location pings every few seconds, belongs in an in-memory store, not in a relational database plus CDC.
  • No one can own the pipeline. CDC is infrastructure: slots, connectors, topics, schemas and alerts. Without an owner, a stalled slot will eventually fill a primary's disk.

How to Implement It#

  1. Decide copy or reason. Use table CDC for derived copies. Use the outbox for events other teams act on.
  2. Prepare the database. For Postgres: wal_level = logical, a replication user, a publication, and max_slot_wal_keep_size set. For MySQL: row-based binlog, full row images, GTIDs on, and retention of several days.
  3. Deploy the connector. Usually Debezium on Kafka Connect or a managed equivalent. Use a schema registry with Avro or Protobuf, and a compatibility rule.
  4. Plan the snapshot. Use an initial snapshot for small tables, and incremental snapshots for large ones. Schedule it off-peak.
  5. Configure topics. Use per-table topics keyed by primary key, a partition count chosen for future growth, log compaction for "latest state" topics, and an explicit retention policy.
  6. Write idempotent consumers. Apply upserts keyed by primary key, guarded by the source position (LSN or GTID) so that older events never overwrite newer ones, and handle tombstones as deletes.
  7. Monitor and alert. Track connector health, end-to-end lag, slot retained WAL or binlog headroom, and consumer lag. Run a periodic reconciliation (counts or checksums per key range) between source and each derived store.
  8. Document schema-change rules. Expand and contract only, with registry compatibility checks in CI, and advance notice of bulk backfills.
-- Postgres setup for CDC (run as a superuser; wal_level needs a restart)
ALTER SYSTEM SET wal_level = 'logical';
ALTER SYSTEM SET max_replication_slots = 10;
ALTER SYSTEM SET max_wal_senders = 10;
ALTER SYSTEM SET max_slot_wal_keep_size = '100GB';  -- protect the primary's disk
 
CREATE ROLE cdc_reader WITH LOGIN REPLICATION PASSWORD '...';
GRANT SELECT ON public.products, public.orders, public.outbox TO cdc_reader;
CREATE PUBLICATION dbz_shop FOR TABLE public.products, public.orders, public.outbox;
ALTER TABLE public.products REPLICA IDENTITY FULL;  -- full before-images, more WAL
 
-- watch slot lag: alert if retained WAL keeps growing
SELECT slot_name, active,
       pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), confirmed_flush_lsn)) AS retained
FROM pg_replication_slots;
TechnologyFits when
Debezium on Kafka ConnectYou run Kafka and want open-source, log-based CDC for Postgres, MySQL, MongoDB, SQL Server, Oracle and more
Debezium ServerYou want Debezium's connectors but your stream is Kinesis, Google Pub/Sub, Pulsar or Redis Streams
Postgres native logical replicationPostgres to Postgres copies (for example for major-version upgrades) without extra tools
AWS Database Migration Service (DMS)Migrations and ongoing replication on AWS between databases or into S3, managed for you
Google Cloud DatastreamManaged CDC from MySQL, Postgres or Oracle into BigQuery or Cloud Storage
Fivetran, AirbyteManaged or open-source ELT connectors loading many SaaS and database sources into a warehouse, minutes fresh
DynamoDB Streams, MongoDB change streamsThe source is DynamoDB or MongoDB, using the native change feed
Flink CDCYou want to read CDC streams directly into Flink jobs for joins and transformations
Kafka Connect JDBC source (query-based)The database cannot expose its log, and missed deletes or polling lag are acceptable
Polling outbox relayYou need reliable event publishing now, without CDC infrastructure

Trade-offs#

OptionProsConsPick when
Dual writes from the applicationNo extra infrastructure; easy to startDrift from crashes, partial failures and races; misses writes from other pathsPrototypes, or best-effort side data you can rebuild
Query-based capture (polling updated_at)Works on any database; simpleMisses deletes and intermediate states; polling load; commit-order gapsThe log is not accessible and the consumer only needs eventual latest state
Trigger-based captureCaptures everything, inside the transactionAdds write latency and load to every transaction; triggers are hard to manageSmall databases, or older systems without log access
Log-based CDC (Debezium)Complete, ordered and low-latency; no application changes; little loadInfrastructure to run; slot or binlog management; exposes the internal schemaDerived copies of data at production scale
Transactional outbox with CDC relayAtomic business events; designed contract; ordered per aggregateNeeds CDC infrastructure plus outbox discipline in codeEvents other services act on
Outbox with polling relayAtomic events using only the databasePolling load and latency; ordering needs careReliable events now, CDC later
Event sourcing (log is the database)Events are the truth; full history and replayLarge change in programming model; querying needs projectionsDomains where history is the product (ledgers, workflows)
Managed CDC (DMS, Datastream, Fivetran)Little to operateLess control over format, latency and cost at volumeWarehouse loading and migrations, small platform teams

Common Pitfalls#

  • Forgetting the replication slot. A stalled or abandoned Postgres slot retains WAL until the primary's disk fills. Alert on retained WAL and set max_slot_wal_keep_size.
  • Treating CDC events as business events. Sending emails or charging cards from row changes fires on backfills, repairs and re-snapshots. Publish intent through an outbox.
  • Non-idempotent consumers. CDC is at-least-once. Restarts re-emit events. Upsert by key, and guard with the source LSN or version.
  • Overwriting newer data with older events. Replays and rebalances can apply older changes after newer ones. Use external versions (Elasticsearch version_type=external) or a "last applied LSN per key" check.
  • Assuming cross-table order. Changes to different tables or rows arrive in arbitrary relative order. Buffer by transaction, or make consumers tolerate missing parents.
  • Breaking consumers with DDL. Renames and type changes break every reader of the topic. Use expand and contract plus registry compatibility checks.
  • Unannounced bulk updates. One UPDATE touching 50 million rows becomes 50 million events and an hour of lag downstream. Batch and schedule backfills.
  • Ignoring unchanged TOAST values and missing before-images. Postgres may omit unchanged large columns. Indexers that treat missing as null wipe fields.
  • Too few partitions. Adding partitions later breaks per-key order during the transition. Size partitions for several years of growth.
  • No end-to-end check. A pipeline can be "running" while silently dropping or misrouting data. Use heartbeat rows and periodic reconciliation.

Real-World Examples#

  • LinkedIn built Databus, a change-capture system that streamed changes from its primary databases to search indexes, caches and other derived stores. It was described in "All Aboard the Databus! LinkedIn's Scalable Consistent Change Data Capture Platform" (Shirshanka Das and colleagues, ACM SoCC 2012). LinkedIn also created Kafka. Jay Kreps's 2013 essay "The Log: What Every Software Engineer Should Know About Real-Time Data's Unifying Abstraction" laid out the idea that a database's change log can feed every other system.
  • Netflix built DBLog to capture changes from MySQL and Postgres. It introduced the watermark-based incremental snapshot technique described above, published in 2020 by Andreas Andreakis and Ioannis Papapanagiotou.
  • Airbnb described SpinalTap, its CDC system for streaming MySQL binlog changes to the services that depend on them, in a 2018 engineering post.
  • Debezium grew out of Red Hat and is the basis of many companies' CDC pipelines and of several managed offerings. The outbox event router is a first-class part of the project.

Typical scenario: an e-commerce team moves product search from SQL LIKE queries to Elasticsearch. They stream the products, brands and inventory tables through Debezium into Kafka. A Kafka Streams job joins them into search documents, and an indexer writes them with external versions. Search is about 1 to 2 seconds behind the database, and a nightly reconciliation finds a few dozen mismatches per 100 million documents, all from indexer bugs that were then fixed.

In the Interview#

Deep Dive: The log as the unifying abstractionShow

CDC is one instance of a deeper idea: a table is the result of applying a log of changes, and a log of changes can be derived from a table. Kafka Streams calls this the stream-table duality, and it explains why CDC works and where its limits are.

State machine replication. Feed a deterministic state machine the same ordered sequence of inputs, and it reaches the same state. Database replicas rely on this: apply the primary's log in order and you reproduce the primary. CDC consumers are state machines too. The difference is that they compute a different state from the same log: an inverted index instead of a B-tree, a cache entry instead of a row, an aggregate instead of a table. Formally, if S(n) = apply(S(n-1), e(n)), every derived store is just a different apply. That is why the order of e(n) matters, and why "same order for the same key" is the minimum guarantee most derived stores need. Most derived stores are per-key: the state for key k depends only on events for key k. For those, per-key order is sufficient. Stores that join keys, like a document combining a product and its brand, need either per-key order on the join key, or a processor that keeps state per key and recomputes on any input change.

Idempotence from monotonic versions. If each event carries a position that increases for each key, then applying "upsert if the incoming version is newer" is idempotent and commutative over any set of events for that key. Any delivery order and any number of duplicates converge on the state given by the highest version. This is the same reasoning as a last-writer-wins register, but safe, because the versions come from a single totally ordered log instead of from wall clocks. It is the main reason CDC consumers can be made correct far more easily than consumers of arbitrary events.

Compaction is a table. A compacted Kafka topic keeps the latest value for every key. Reading it from the beginning yields the current table, and continuing to read yields its changes. This lets a new consumer bootstrap without touching the source database, which matters when you have twenty consumers and one primary. Compaction runs in the background, so a consumer may still see several older versions of a key before the latest one. With version-guarded upserts, that is harmless.

CDC, event sourcing and "listen to yourself" compared. All three make one log the single source of truth and derive everything else from it. They differ in which log, and in who designs its contents.

ApproachThe logWho designs the recordsSynchronous validationTypical use
Table CDCDatabase WAL or binlogNobody; records are row changesYes, by the databaseDerived copies of data
OutboxOutbox rows inside the database logThe service team, deliberatelyYes, in the same transactionBusiness events between services
Event sourcingAn event storeThe domain modelYes, via optimistic concurrency on streamsHistory-centric domains
Listen to yourselfA broker topicThe service teamNo; validation happens after acceptanceRare; high-throughput pipelines that accept async validation

Martin Kleppmann popularised this view in "Designing Data-Intensive Applications" (2017) and in his talk "Turning the Database Inside Out". The database's log is the real primary data, and tables, caches and indexes are materialised views over it. CDC is the practical way to adopt that view without rewriting the application.

Where the abstraction leaks. Logs are finite. WAL is recycled, binlogs expire, and Kafka retention runs out. A consumer that falls behind retention must re-snapshot. Snapshots are expensive and, without the watermark technique, block live changes. And the log records effects, not causes. That is the final reason intent must be published separately, as outbox events.

Deep Dive: Proving a CDC pipeline is correct in productionShow

A pipeline can be "green" on every dashboard and still be wrong. Here is a production checklist, organised by what can fail.

FailureEffect without protectionProtection
Connector crashRe-emits events since the last committed offsetIdempotent, version-guarded consumers
Kafka broker failureLost events if produce acks are weakacks=all, replication factor 3, min.insync.replicas=2 on CDC topics
Consumer crash after applying, before committingRe-applies a batchIdempotent writes; commit offsets after applying
Source primary failoverSlot missing on the new primary (Postgres before 17)Failover-synchronised slots, or a planned re-snapshot runbook
Slot invalidated by max_slot_wal_keep_sizeGap in the streamAlert first; then re-snapshot (incremental) and reconcile
Binlog purged before it was readGap in the streamRetention longer than the worst outage; alert on connector downtime
Indexer bug drops some updatesSilent driftReconciliation and canary checks
Schema change breaks deserialisationConsumer stuck or dead-lettering everythingRegistry compatibility in CI; alert on dead-letter rate

End-to-end freshness canaries. Write a heartbeat row to a small table in the source every 10 seconds, containing the current time. Each sink (search index, cache, warehouse) exposes the latest heartbeat it has applied. "Now minus the latest heartbeat" is end-to-end freshness, measured the way users experience it. Alert when it exceeds the SLO, for example 30 seconds for search or 15 minutes for the warehouse. This catches every failure in the table above that stops data flowing, including ones no component reports.

Reconciliation without full scans. Comparing 500 million rows across two stores every night is expensive. Instead, split the key space into ranges (for example 4,096 ranges by hash of the primary key) and compute a checksum per range on both sides, such as the XOR or sum of per-row hashes of the relevant columns. Compare the 4,096 checksums and re-scan only the ranges that differ. This is the same idea as the Merkle-tree anti-entropy used by Dynamo-style databases (see Quorums and Leaderless Replication). Run it against a replica of the source and a snapshot of the sink, and tolerate rows changed in the last few minutes, which are still in flight.

Quantifying "rare drift". Suppose an indexer has a bug affecting 1 in 10 million updates, and the system processes 2,000 updates per second. That is 172.8 million updates per day, so about 17 documents drift each day, and about 6,000 per year if nothing corrects them. No dashboard shows that, but users searching for a renamed product do notice. Reconciliation converts it from permanent drift into, at worst, one day of drift.

Replay as a feature. Because the CDC topic or the source can always rebuild a sink, treat every derived store as disposable. Create a new index, replay into it from the compacted topic or an incremental snapshot, verify it, then switch an alias to it. Elasticsearch index aliases make that switch atomic. That turns index mapping changes, reindexing after an indexer bug fix, and cluster migrations into routine, low-risk operations rather than emergencies.

Key Takeaways#

  • Never dual write: write synchronously to one system, and derive every other copy from that system's log.
  • Log-based CDC reads the Postgres WAL or MySQL binlog, so it captures every committed change, including deletes, in commit order, with almost no load on the write path.
  • Debezium on Kafka Connect publishes one topic per table, keyed by primary key, which keeps each row's changes in order. It delivers at least once, so consumers must be idempotent.
  • Guard every derived store with the source position (LSN or version) so that replays, duplicates and reordering cannot overwrite newer data.
  • Use table CDC when consumers need a copy of the data, and a transactional outbox when they need to know what happened and why.
  • CDC is ideal for search indexing, warehouse loading, zero-downtime migrations and data sharing; it is only a backstop for cache invalidation that must be immediately visible.
  • Replication slots and binlog retention are the operational heart of CDC: monitor retained WAL, cap it, and keep a re-snapshot runbook.
  • Change captured tables with expand and contract and schema-registry compatibility checks, because every DDL change reaches every consumer.