# Change Data Capture

**Also known as:** CDC · Log-based CDC  
**Category:** Data & Storage (Where the data lives)  
**Complexity:** 4/5  
**Guide:** https://layra4.dev/architectures/data-storage/change-data-capture

*Turn every committed change in a database into an event, in commit order, without touching the app.*

Data rarely stays in one store. The same orders feed a search index, a cache, a warehouse and other services. Writing to each one from the app is a dual write: a crash or a failed call between two writes leaves them out of step for good, and nothing notices. Change data capture (CDC) avoids it by treating the database as the only place the app writes.

Every database keeps a log of committed changes for its own recovery and replication: the WAL in Postgres, the binlog in MySQL, the oplog in MongoDB. A CDC connector, such as Debezium, reads that log like a replica would and publishes each row change as an event, usually to a topic in a log like Kafka. Consumers rebuild whatever they need from those events.

> **In one sentence.** The database already writes every change to a log. CDC reads that log and publishes it, so other systems follow the database without the app writing to them twice.

## Origin

Commercial replication tools read database logs for decades before the name stuck. LinkedIn's Databus, described in 2012, read the source database's change log to feed caches and search indexes. Debezium, started at Red Hat around 2016, made log-based CDC open source and paired it with Kafka, which is how most teams meet it today.

## Key concepts

### Log-based CDC

The connector reads the database's replication log and turns each committed row change into an event with the old and new values. It sees every change, including deletes, in commit order, and adds almost no load to the write path.

- Postgres: logical decoding through a replication slot
- MySQL: the binlog in row format
- Needs log settings and permissions a normal app user does not have

### Trigger and polling CDC

Without access to the log, a trigger copies each change into a changes table, or a job polls for rows where updated_at is newer than the last run. Both work on any database, and both have gaps.

- Triggers add cost to every write, inside the transaction
- Polling misses deletes and changes overwritten between polls
- Polling by timestamp skips a transaction that commits late with an early time

### Snapshot, then stream

The log only holds recent changes, so a new consumer first needs the existing rows. The connector reads a consistent snapshot, notes the log position it matches, then streams from that position. Newer tools snapshot in chunks while streaming, so a large table does not hold the log back. A change can show up in both the snapshot and the stream, which idempotent consumers absorb.

### Ordering per key

Changes to one row must arrive in order, or an old update lands after a new one. Connectors partition events by primary key, which keeps each row in order but gives no order across rows or partitions.

> topic orders, partition = hash(order_id)

### Change event

One row change: the operation, the row before and after, the source table and the log position. A delete often adds a tombstone, an event with a key and no value, so compacted topics can forget the row.

> { "op": "u", "before": {...}, "after": {...}, "source": { "lsn": 4127 } }

## Design rules

### Publish an outbox, not your tables, to other teams

Raw row changes expose your internal schema, so every column rename breaks a consumer. For events other services use, write an explicit event to an outbox table in the same transaction and let CDC publish that table. Keep raw table CDC for your own caches and indexes.

### Make every consumer idempotent

Connectors deliver at least once: after a restart they replay from the last confirmed position. Apply changes as upserts keyed by primary key, and skip an event whose log position is older than the one already applied.

### Watch the slot, not only the connector

The database keeps log segments until the consumer confirms them. A stopped connector means the log grows until the disk is full. Alert on retained log size, and cap it where the database allows.

### Plan schema changes with the consumers

A dropped or renamed column changes every event after it. Use expand/contract on captured tables, and carry the schema with each event through a registry so consumers can tell versions apart.

## Examples

### Preparing Postgres for log-based CDC

```sql
-- Let the WAL carry row-level changes, not only physical pages (needs a restart).
alter system set wal_level = 'logical';

-- Send the old row on update and delete, not only its primary key.
alter table orders replica identity full;

-- The tables a connector may read.
create publication orders_cdc for table orders, order_lines;

-- A slot remembers how far the consumer has read. WAL is kept until it confirms.
select pg_create_logical_replication_slot('orders_cdc_slot', 'pgoutput');

-- How much WAL each slot is holding back. Alert when this 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;

-- Postgres 13+: past this size the slot is invalidated instead of filling the disk.
alter system set max_slot_wal_keep_size = '50GB';
select pg_reload_conf();
```

A connector such as Debezium usually creates the slot and publication itself; this is what it relies on. The last two statements are the ones teams forget: the lag query belongs on a dashboard, and the cap stops a dead connector from filling the disk.

## When to use

- Keeping a search index, cache or warehouse in step with a database
- Publishing events reliably, together with an outbox table
- Moving data to a new store while the old one stays live

## When not to use

- One consumer that can simply query the database on demand
- Sharing raw tables with other teams as a public contract
- A managed database that does not expose its change log

## Benefits

- No dual writes: the database commit is the only source of truth
- Every change, including deletes, in commit order per row
- New consumers can be added later and replay from a snapshot

## Costs

- A connector, a log and a topic to run and monitor
- Consumers are eventually consistent, usually seconds behind
- Source schema changes ripple out to every consumer

## Pitfalls

- Leaving an unused replication slot behind, so the database keeps WAL until the disk fills and writes stop.
- Assuming events arrive in one global order. Only changes to the same key are ordered.
- Expecting a transaction to arrive as one unit. A multi-row commit becomes several events that consumers see one by one.
- Losing old values on update and delete because the table only logs its primary key.

## Related patterns

- [Outbox](https://layra4.dev/architectures/infrastructure/outbox) — an explicit event table that CDC can publish
- [Event Sourcing](https://layra4.dev/architectures/architectural/event-sourcing) — events as the source of truth, instead of derived from rows
- [Search Index](https://layra4.dev/architectures/data-storage/search-index) — the classic consumer kept in sync by CDC
- [Idempotent Consumer](https://layra4.dev/architectures/infrastructure/idempotent-consumer) — how a consumer survives replayed changes
- [Schema Evolution](https://layra4.dev/architectures/data-storage/schema-evolution) — changing captured tables without breaking consumers

## Further reading

- *Designing Data-Intensive Applications, ch. 11* — Martin Kleppmann (2017) — Stream processing, with change data capture and log compaction.
- *Making Sense of Stream Processing* — Martin Kleppmann (2016) — Turning the database inside out: the log as the source of every derived store.
- *DBLog: A Watermark Based Change-Data-Capture Framework* — Andreas Andreakis, Ioannis Papapanagiotou (2020) — Taking chunked snapshots while streaming the log, without locks.
