AlgoViz

Change data capture

medium 28 min

Change 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

0:00 / 3:33

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

  1. 2013

    On 26 February LinkedIn open-sources Databus, its low-latency change data capture system.

  2. 2014

    PostgreSQL 9.4 adds logical decoding, which streams database changes out of the write-ahead log in a format that can be chosen.

  3. 2016

    Debezium publishes its early releases, among them 0.3.3 in October, with connectors for MySQL and MongoDB on Kafka Connect.

  4. 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.

Step 1 of 3

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?

Following the field log
NoorFIELD LOG1 robin arrives

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

An application writes to a database. A Debezium connector reads the database's log and publishes change events to Kafka. Three consumers read from Kafka: one updates a search index, one updates a cache and one loads a warehouse.
The application writes once. Dashed orange arrows are asynchronous.

One update on its way

The application got its answer long before the index changed. Search is eventually consistent.

The parts

StagePartIts job
SourceDatabaseCommits transactions
LogWAL, binlog or oplogRecords them in order
CaptureConnector, such as DebeziumTurns log records into events
DeliverStream, such as KafkaKeeps events and lets many read them
ConsumeYour code or a sink connectorApplies them somewhere else

The problem it solves

Why not write to both?

A dual write that goes wrong

The database says 12 and search says 10. Nothing failed, so no retry will ever repair it.

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-basedTrigger-basedTimestamp-based
HowRead the transaction logA trigger writes to a shadow tablePoll rows with a newer updated_at
DeletesYesYesNo, unless rows are only marked as deleted
Every step betweenYesYesNo, only the latest state
Cost to writesSmallExtra write in each transactionNone, but polling queries
NeedsLog access and rightsTriggers on each tableA reliable, indexed column
DelayUsually shortUntil the table is readThe polling interval
Timestamps have a quieter trap too: a long transaction can commit a row whose timestamp is older than your last check. Read again with an overlap, and make the consumer idempotent.

Which pattern?

How much does polling waste?

86,4005=17,280 polls a day for each tableaverage delay=52=2.5 s\frac{86{,}400}{5} = 17{,}280 \text{ polls a day for each table} \qquad \text{average delay} = \tfrac{5}{2} = 2.5 \text{ s}
Polling every 5 seconds. With 40 tables that is 691,200 queries a day, whether anything changed or not.

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.

JSON
{  "op": "u",  "before": { "id": 1, "name": "Old" },  "after":  { "id": 1, "name": "New" },  "source": { "table": "users", "lsn": 24023128 },  "ts_ms": 1559033904863}
A shortened update event. The operation is c for create, u for update, d for delete, r for a row read by a snapshot and t for truncate.

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.

JSON
{  "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"  }}
A connector setting. The password comes from a secret store, never from the file itself.

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. 1

    Remember the position

    Note the current log position, and keep the log from here on.

  2. 2

    Read the tables

    In one consistent snapshot, or in chunks while streaming goes on (an incremental snapshot).

  3. 3

    Publish rows as reads

    They have operation r and no before.

  4. 4

    Follow the log

    From the remembered position.

How long does a snapshot take?

200,000,000 rows20,000 rows/s=10,000 s≈2.8 h\frac{200{,}000{,}000 \text{ rows}}{20{,}000 \text{ rows/s}} = 10{,}000 \text{ s} \approx 2.8 \text{ h}
Assumed rates. Changes pile up meanwhile, so the log must be kept for at least this long, plus the time needed to catch up.

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. 1

    Upsert, do not insert

    Write by primary key, so twice is the same as once.

  2. 2

    Compare positions

    Store the event's log position with the row and ignore older ones.

  3. 3

    Remember deletes

    Keep a marker for a while, or a late update brings the row back.

  4. 4

    Work first, bookmark second

    Otherwise a crash loses the event.

Python
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)
The same events, twice and out of order, give the same result
Edit and run it in your browser

When things go wrong

ProblemWhat you seeWhat to do
An event that cannot be processedOne partition stands stillRetry a few times, then park it in a dead-letter topic and alert
A consumer is too slowIts lag growsMore partitions and members, batch writes
The connector is stoppedThe database keeps its logAlert on retained log, set a limit, restart
Away longer than the log is keptThe offset no longer existsTake a new snapshot
A column is renamedConsumers breakAdd, 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

Both rows commit or neither does.

Uses

What people build with it

UseWhat the consumer doesWatch out for
Search indexUpserts and deletes documentsOrder per document, rebuild by replay
Cache invalidationDeletes or refreshes the keyA short time with an old value
WarehouseAppends all changes or merges the latestDeletes and schema changes
Between servicesKeeps a local read-only copyPrefer the outbox to raw tables
NotificationsSends email or SMSDuplicates and replays
Audit logStores who, what and whenWho is not in the row unless the application adds it
An audit by CDC shows what changed, not why or by which user. Put the user's id into the row or the outbox.

In an interview

  1. Interviewer

    Products live in PostgreSQL and search is a separate index. How do they stay in step?

  2. 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.

  3. Interviewer

    The index is corrupted.

  4. 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.

Sources