Change data capture
medium 28 minChange data capture (CDC) turns every insert, update and delete in a database into an ordered stream of events that other systems follow: search indexes, caches, warehouses and services.
Video lesson · Chapter 1 of 5
One committed change reaches the search box
One database, many followers, in 80 seconds
1:20Reel coming soon
Theory
Read or listen first. About 2 min.
What it is
Change data capture identifies the changes made to data in a database and delivers them, in order and soon after they happen, to other systems.
Each change becomes an event: which row, what kind of change, how the row looked before and after. Consumers read the events at their own speed and keep a bookmark of how far they have come.
It is close to replication. A replica follows the log to become the same database. A CDC consumer follows the log to build something different: an index, a cache, a report. How the log itself works is in replication fundamentals.
Why it exists
Data is needed in more than one place. Search wants an index, the home page wants a cache, analysts want a warehouse. Copying everything each night is simple, but it is a day old and heavy.
Letting the application write to all of these places, called a dual write, looks easy and is wrong: if the second write fails, or two requests arrive in different orders, the copies disagree for ever and nobody is told.
CDC removes the second write. The application commits once, to its database. Everything else is derived from the log of what was committed, so nothing that was committed is forgotten.
A short history
2013
On 26 February LinkedIn open-sources Databus, its low-latency change data capture system.
2014
PostgreSQL 9.4 adds logical decoding, which streams database changes out of the write-ahead log in a format that can be chosen.
2016
Debezium publishes its early releases, among them 0.3.3 in October, with connectors for MySQL and MongoDB on Kafka Connect.
2022
Debezium 2.0 is released on 14 October.
Words to know
- Change event
- One insert, update or delete, with the row before and after.
- Connector
- The program that reads a database log and publishes events.
- Offset
- A consumer's bookmark: the position it has processed.
- Snapshot
- The first full read of the existing rows, before following changes.
- Tombstone
- A message with a key and no value, which tells a compacted topic to forget that key.
- Idempotent
- Processing the same event twice has the same result as once.
- Outbox
- A table into which the application writes the event in the same transaction as the data.
How it works
Step through the idea, or press Play.
Capture. Read committed changes from the log
Understand it
Start here
The birdwatcher's log
Noor watches birds and writes each change in a log, numbered and in order. Three friends need the news for different reasons. Must they ask all day, or can they simply follow the log?
Nobody changed how Noor works. The log was there anyway: that is why log-based capture is light.
The pipeline
Capture, deliver, consume
One write, three followers
One update on its way
The parts
| Stage | Part | Its job |
|---|---|---|
| Source | Database | Commits transactions |
| Log | WAL, binlog or oplog | Records them in order |
| Capture | Connector, such as Debezium | Turns log records into events |
| Deliver | Stream, such as Kafka | Keeps events and lets many read them |
| Consume | Your code or a sink connector | Applies them somewhere else |
The problem it solves
Why not write to both?
A dual write that goes wrong
With CDC
- One commit, in the database
- Events follow commit order
- A consumer that was down catches up
- New consumers need no change in the application
With dual writes
- Two systems without a common transaction
- A crash between them loses one
- Concurrent requests may arrive in different orders
- Every new target changes the application
Pattern 1
Log-based capture
Read the database's own transaction log: the PostgreSQL WAL, the MySQL binlog or the MongoDB oplog. It sees every committed change, including deletes and the states between two reads. It needs no change to your tables.
Patterns 2 and 3
Triggers and timestamps
| Log-based | Trigger-based | Timestamp-based | |
|---|---|---|---|
| How | Read the transaction log | A trigger writes to a shadow table | Poll rows with a newer updated_at |
| Deletes | Yes | Yes | No, unless rows are only marked as deleted |
| Every step between | Yes | Yes | No, only the latest state |
| Cost to writes | Small | Extra write in each transaction | None, but polling queries |
| Needs | Log access and rights | Triggers on each table | A reliable, indexed column |
| Delay | Usually short | Until the table is read | The polling interval |
Which pattern?
How much does polling waste?
A tool
Debezium and its events
Debezium is an open-source platform for CDC. Its connectors cover, among others, PostgreSQL, MySQL, MariaDB, MongoDB, SQL Server, Oracle, Db2 and Cassandra. It commonly runs on Kafka Connect, and it can also run as a standalone server or inside an application.
{ "op": "u", "before": { "id": 1, "name": "Old" }, "after": { "id": 1, "name": "New" }, "source": { "table": "users", "lsn": 24023128 }, "ts_ms": 1559033904863}Four details people miss
before may be incomplete
In PostgreSQL it depends on the table's replica identity. The full old row needs REPLICA IDENTITY FULL.
A delete is two messages
First the delete event, then a tombstone with the same key and no value. Consumers must accept the empty one.
Flattening changes the shape
The ExtractNewRecordState transform sends only the new row. Code that expects op and before then breaks.
A changed key is a delete and a create
The connector sends a delete for the old key and a create for the new one.
{ "name": "shop-cdc", "config": { "connector.class": "io.debezium.connector.postgresql.PostgresConnector", "plugin.name": "pgoutput", "database.hostname": "postgres", "database.port": "5432", "database.user": "cdc_reader", "database.password": "FROM_YOUR_SECRET_STORE", "database.dbname": "shop", "topic.prefix": "shop", "table.include.list": "public.users,public.orders", "slot.name": "shop_cdc", "publication.name": "shop_publication" }}Delivery
Why a log such as Kafka sits in between
Durability
Events stay even while consumers are down, for as long as you configure.
Order
Within one partition, events are read in the order they were written. Events with the same key go to the same partition.
Scale
Many consumer groups read independently, and one group splits partitions among its members.
Replay
A consumer can go back and process again, within the kept history.
Debezium's PostgreSQL topics are named after prefix, schema and table, for example shop.public.users. With the row's primary key as the message key, all changes to one row stay in order. Order across rows and tables is not kept, so an order line may arrive before its order. A compacted topic keeps at least the latest value per key, so a new consumer can rebuild the current state from it. Queues and delivery guarantees in general are in asynchronous communication.
The beginning
Snapshot, then stream
The log does not go back to the first day. A new pipeline therefore reads all existing rows once, as a snapshot, and then follows the log from the position at which the snapshot was taken. No gap, and any overlap is harmless if consumers are idempotent.
- 1
Remember the position
Note the current log position, and keep the log from here on.
- 2
Read the tables
In one consistent snapshot, or in chunks while streaming goes on (an incremental snapshot).
- 3
Publish rows as reads
They have operation r and no before.
- 4
Follow the log
From the remembered position.
How long does a snapshot take?
Consume safely
Duplicates, order and deletes
Delivery is normally at least once. A connector or a consumer that crashes after doing the work, and before saving its bookmark, does that work again. The same event can arrive twice, and after a replay an old event can arrive after a newer one.
Four rules for a consumer
- 1
Upsert, do not insert
Write by primary key, so twice is the same as once.
- 2
Compare positions
Store the event's log position with the row and ignore older ones.
- 3
Remember deletes
Keep a marker for a while, or a late update brings the row back.
- 4
Work first, bookmark second
Otherwise a crash loses the event.
index, seen = {}, {}def apply(event): key, position = event["key"], event["position"] if position <= seen.get(key, 0): return "ignored" seen[key] = position # also remembered for deletes if event["op"] == "d": index.pop(key, None) else: index[key] = event["after"] return "applied"a = {"key": 1, "position": 10, "op": "c", "after": "Old"}b = {"key": 1, "position": 11, "op": "u", "after": "New"}c = {"key": 1, "position": 12, "op": "d", "after": None}for e in (a, b, b, c, b): print(e["op"], e["position"], apply(e))print(index)When things go wrong
| Problem | What you see | What to do |
|---|---|---|
| An event that cannot be processed | One partition stands still | Retry a few times, then park it in a dead-letter topic and alert |
| A consumer is too slow | Its lag grows | More partitions and members, batch writes |
| The connector is stopped | The database keeps its log | Alert on retained log, set a limit, restart |
| Away longer than the log is kept | The offset no longer exists | Take a new snapshot |
| A column is renamed | Consumers break | Add, copy, switch, then remove. Use a schema registry |
Public events
Row changes or business events?
Raw CDC exposes your tables: rename a column and you break every reader. For events that other teams rely on, use the outbox: in the same transaction as the data, the application inserts a row such as OrderPlaced into an outbox table. CDC then publishes that table. You get one transaction and an event whose shape you choose. Debezium has an outbox event router for this.
The outbox with CDC
Uses
What people build with it
| Use | What the consumer does | Watch out for |
|---|---|---|
| Search index | Upserts and deletes documents | Order per document, rebuild by replay |
| Cache invalidation | Deletes or refreshes the key | A short time with an old value |
| Warehouse | Appends all changes or merges the latest | Deletes and schema changes |
| Between services | Keeps a local read-only copy | Prefer the outbox to raw tables |
| Notifications | Sends email or SMS | Duplicates and replays |
| Audit log | Stores who, what and when | Who is not in the row unless the application adds it |
In an interview
Interviewer
Products live in PostgreSQL and search is a separate index. How do they stay in step?
You
The application writes only to PostgreSQL. A log-based connector publishes changes keyed by product id, and an indexer upserts them, ignoring positions older than the one it stored. Search is a second or so behind, which I would confirm is fine.
Interviewer
The index is corrupted.
You
I build a new index beside it, from a snapshot or a compacted topic, let it follow until its lag is near zero, and then switch the alias. Users notice nothing.
Decide
When not to use it
Good fit
- Several systems need the same changes
- Seconds of delay are fine
- You cannot or will not change the application
- Deletes and history matter
Poor fit
- The reader needs its answer in the same transaction
- One nightly report is enough
- Nobody will operate the connector and the stream
- A read replica would do: same database, only for reads
Summary
The whole topic in one minute.
CDC turns a database's log into a stream of change events. It avoids dual writes: commit once, and derive everything else from what was committed.
Log-based capture sees every change, including deletes, with little load. Delivery is normally at least once, so consumers must be idempotent and must keep events for one key in order. Plan the first snapshot, schema changes, and what happens when a consumer stays away too long.
- CDC: Capture, Deliver, Consume.
- It replaces dual writes. Commit once and derive the rest.
- Log-based sees every change, deletes included. Timestamps miss deletes.
- At least once: upsert by key, compare positions, remember deletes.
- Order is kept per key, not across tables. Snapshot first, then stream.