Change data capture
Part of the free LogicWiz Data Engineering course, Module 6: Batch pipelines. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is Monday, 10:15. Tess is building the catalogue report and two things do not add up. The warehouse still lists the Smart Watch, which the store stopped selling months ago. And nobody can say when the Coffee Mug went from $11.50 to $12.50. You open the store's products table. It has no updated_at. And when the catalogue team removes a product, its row is gone. Your watermark load sees neither.
You'll learn to
- Name four ways to capture changes, and what each one misses
- Find inserts, updates and deletes by comparing two snapshots
- Read a change event, including a delete and its tombstone
- Apply a change feed per key, in LSN order, with MERGE
Learn
Three things a watermark cannot see
Finding out which rows in a source were inserted, updated or deleted, so that you copy only those, has a name: change data capture, or CDC. The watermark on updated_at from Lesson 6.2 is the simplest CDC there is. Tess has just found its blind spots:
- Deletes. A deleted row is gone. No query on the table can return it. That is the Smart Watch.
- No
updated_at. Many tables do not have one, or some code forgets to set it. That is the wholeproductstable. - Versions in between. If an order goes placed, shipped, delivered between two runs, you only ever see "delivered".
There are three other ways to capture changes. This lesson takes them in turn.
No updated_at? Compare two snapshots
The first way needs nothing from the source. Copy the whole table every night. Each copy is a snapshot. Then compare tonight's snapshot with last night's, on the key.
Think of two photos of the same shelf, taken a day apart. Put them side by side and you can see what was added, what was removed and what changed.
- The key is only in today's snapshot: an insert.
- The key is only in yesterday's: a delete.
- The key is in both, but some value differs: an update.
This is snapshot comparison. It reads the whole table every night, so it suits small and medium tables, like SwiftKart's catalogue of 20 products.
Two snapshots of the catalogue, compared
Yesterday's and today's snapshots of the 20 products side by side: product 121 exists only today, product 119 only yesterday, products 105 and 117 changed, and 17 products are the same.
Two snapshots. Last night's copy of the catalogue and tonight's, 20 products each. Match the rows by
product_id.A key only in today. Product 121 has no row in yesterday's snapshot. It is an insert.
A key only in yesterday. Product 119, the Smart Watch, has no row today. It is a delete: the change no watermark could see.
A key in both, with different values. The mug's price changed, and the gift card's empty category was filled in. Two updates. The other 17 products match exactly.
Each step colours one kind of change. By the last step every row has a colour: one insert, one delete, two updates, 17 unchanged.
Diff two snapshots of the catalogue
SELECT COALESCE(t.product_id, y.product_id) AS product_id,
CASE
WHEN y.product_id IS NULL THEN 'insert'
WHEN t.product_id IS NULL THEN 'delete'
ELSE 'update'
END AS change
FROM staging.products_yesterday AS y
FULL OUTER JOIN staging.products_today AS t ON t.product_id = y.product_id
WHERE y.product_id IS NULL
OR t.product_id IS NULL
OR (t.name, t.category, t.price, t.active) IS DISTINCT FROM (y.name, y.category, y.price, y.active)
ORDER BY product_id;
One FULL OUTER JOIN on the key finds all three kinds in one pass: it keeps rows from both sides, with NULLs where a side has no match. IS DISTINCT FROM compares NULL like a value, so product 117 counts as a change. With many columns, teams often compare one row hash instead: md5(ROW(name, category, price, active)::text) is a short fingerprint that changes when any value changes.
The database already keeps a diary
A snapshot sees the day's end result. It cannot say at what time the mug's price changed, or how often. For that you need every change, as it happens.
The database already writes them down. Before it applies any change, it appends the change to a log file, so it can recover after a crash and feed its replicas. Postgres calls it the write-ahead log (WAL); MySQL calls it the binlog.
Log-based CDC reads that log. A tool such as Debezium turns every insert, update and delete into an event: the operation, the row before, the row after, and a position in the log. The position is an LSN (log sequence number), and it puts the events in order.
It sees deletes and every version in between, and adds almost no load to the source.
Log-based CDC, from Postgres to the lake
The store application writes to Postgres; its write-ahead log is read through a replication slot by Debezium on Kafka Connect, which publishes keyed change events to a Kafka topic per table; a sink job merges them into the lake table.
Follow the arrows from the store's app. The two amber boxes are bookmarks. A replication slot is Postgres's bookmark for one reader of its log, and the Connect offsets are the same bookmark on the Kafka side, so a restart carries on where it stopped. The catch: you need the tool, permissions on the database, and somewhere for the events to go. Lesson 6.7 goes inside the WAL and the slot.
One Debezium update event (the value, trimmed)
Runs on a Kafka cluster:
{
"before": { "customer_id": 18, "name": "Jonas Weber", "city": "Berlin", "country": "Germany" },
"after": { "customer_id": 18, "name": "Jonas Weber", "city": "Munich", "country": "Germany" },
"source": {
"connector": "postgresql", "db": "shop", "schema": "public", "table": "customers",
"snapshot": "false", "txId": 7731, "lsn": 24023128,
"sequence": "[\"24023064\",\"24023128\"]"
},
"op": "u",
"ts_ms": 1749457800000
}
Customer 18 moved from Berlin to Munich: before and after hold both rows. op is c (create), u (update), d (delete) or r (a row read during the first copy). lsn is the change's position in the WAL. A full before like this one needs a table setting, REPLICA IDENTITY FULL: the next card explains.
A delete arrives twice
Two details of these events catch people out.
The row before. By default Postgres logs only the primary key of the old row, so before is usually empty for an update. ALTER TABLE customers REPLICA IDENTITY FULL logs the whole old row, at the price of more WAL for every change. With it, a consumer can see which columns changed.
The delete. A delete puts two records on the Kafka topic. First the d event: before is set, after is null. Then a record with the same key and a null value, called a tombstone. The tombstone tells Kafka it may forget every earlier message for that key. Your code must expect a null value and skip it, not crash on it.
Deleting customer 29, on the topic
| Offset | Key | Value |
|---|---|---|
| 411 | {"customerid": 29} | {"op": "d", "before": {"customerid": 29, ...}, "after": null, "source": {"lsn": 24030512}} |
| 412 | {"customerid": 29} | null (the tombstone) |
| after compaction | {"customerid": 29} | every message for key 29 can go, the tombstone last |
Read it top to bottom. Kafka can tidy a topic so it keeps only the latest value per key: that is log compaction. The tombstone is how "this key no longer exists" survives compaction long enough for every consumer to see it.
The feed repeats itself and arrives out of order
Now you have a stream of change events to apply to the warehouse copy. Before you write the apply step, know what the stream promises.
- Postgres hands out transactions in the order they committed. A rolled-back transaction never appears.
- Kafka keeps order only within one partition. Debezium keys events by primary key, so the changes of one row stay in order. Across rows, partitions and tables there is no order, and the rows of one transaction can land in different partitions.
- Delivery is at least once (Lesson 6.3). After a connector restart, the events since the last saved position are sent again.
So the same event can arrive twice, and two events can arrive in the wrong order.
Latest event per key, by LSN
The apply step therefore works per key, by LSN:
- Keep only the event with the highest LSN for each key.
- Skip any event whose LSN is at or below the one already applied for that key.
- Treat
das a delete: remove the row (a hard delete), or keep it and setis_deleted = true(a soft delete). - Merge the rest on the key.
Then a replay changes nothing, and an old event can never undo a newer one. It is the newer-wins rule of Lesson 6.4, with the LSN as the clock.
Apply a change log with MERGE
MERGE INTO dw.customers AS t
USING (
-- the latest event per customer
SELECT * FROM (
SELECT c.*, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY lsn DESC) AS rn
FROM staging.customer_changes AS c
) AS ranked
WHERE rn = 1
) AS s
ON t.customer_id = s.customer_id
WHEN MATCHED AND s.op = 'd' THEN
DELETE
WHEN MATCHED THEN
UPDATE SET name = s.name, email = s.email, city = s.city, country = s.country
WHEN NOT MATCHED AND s.op <> 'd' THEN
INSERT (customer_id, name, email, city, country)
VALUES (s.customer_id, s.name, s.email, s.city, s.country);
SELECT customer_id, name, email, city
FROM dw.customers
WHERE customer_id IN (4, 18, 29, 31)
ORDER BY customer_id;
Customer 31 was created, then updated: only the later event (lsn 104) is applied. Customer 29, one of Maya Chen's duplicate sign-ups, is deleted. WHEN branches are checked in order, so the delete branch comes first.
The same rules in Python
copy = {
4: {'name': 'Ken Watanabe', 'city': 'Tokyo'},
18: {'name': 'Jonas Weber', 'city': 'Berlin'},
29: {'name': 'Maya Chen', 'city': 'Toronto'},
}
# The events reached us out of order: 104 came before 102
log = [
{'lsn': 104, 'op': 'u', 'id': 31, 'row': {'name': 'Rosa Diaz', 'city': 'Lima'}},
{'lsn': 101, 'op': 'u', 'id': 18, 'row': {'name': 'Jonas Weber', 'city': 'Munich'}},
{'lsn': 102, 'op': 'c', 'id': 31, 'row': {'name': 'Rosa Diaz', 'city': 'Cusco'}},
{'lsn': 103, 'op': 'd', 'id': 29, 'row': None},
]
def apply_changes(copy, log):
for change in sorted(log, key=lambda c: c['lsn']): # log order, not arrival order
if change['op'] == 'd':
copy.pop(change['id'], None) # deleting twice is harmless
else:
copy[change['id']] = change['row'] # insert or update
return copy
apply_changes(copy, log)
apply_changes(copy, log) # replaying the batch changes nothing
for key in sorted(copy):
print(key, copy[key]['city'])
The events are listed out of order on purpose. Sorting by lsn makes Lima win, as in the database. pop(key, None) does not fail on a row that is already gone, so applying the batch twice is safe.
Remember: the latest event per key, in LSN order, with a branch for deletes. Then replays and reordering cannot change the result.
The first copy, with no gap
A new connector has a problem on day one. The log holds only recent changes, so the rows that already exist must be copied first. But the store keeps writing while the copy runs. How do you avoid a gap between the copy and the stream?
Debezium pins a position in the log before it reads. It notes the current LSN, copies every table, then starts streaming from the LSN it noted. Anything committed during the copy is in the log after that position, so it is replayed.
A row changed during the copy may arrive twice: once from the copy, once from the stream. A merge by key and LSN absorbs that.
How Debezium copies, then streams
Debezium opens a repeatable read transaction on Postgres, reads the current WAL position, scans the tables into read events, commits, then starts streaming changes from that same position and acknowledges how far it has got.
Pin the position. Debezium opens one transaction that sees the database frozen at this moment, and notes the current position in the log: LSN X.
Copy what exists. It scans each table and sends every row to Kafka as an
r(read) event, then commits. The store keeps writing meanwhile: those changes land in the log after X.Stream from X. Debezium reads the log from the position it pinned, so nothing committed during the copy is missed. As events reach Kafka, it tells Postgres how far it has got, and the slot moves on.
Read each step top to bottom. The whole trick is the second arrow of step 1: the position is read before the copy starts.
When you cannot read the log: the outbox
Sometimes the log is out of reach: a managed database you do not control. Or you want events that mean something to the business, "order shipped", not "row 1012, column status changed".
Then the app can write the events itself. In the same transaction as its normal write, it inserts a row describing the change into a table called outbox. A relay (often Debezium reading the outbox table) publishes those rows in order. This is the outbox pattern.
Both writes commit together, so an event is never lost and never invented. The relay can still send one twice, so consumers dedupe on the event id. The cost: the app team has to build it, and it only covers changes made through the app.
The outbox: the change and its event commit together
The store app updates the orders table and inserts an event row into the outbox table in one transaction; a relay reads the outbox and publishes the events to a topic, where consumers dedupe on the event id.
Look at the two violet boxes: both rows commit, or neither does. Dana's team owns everything up to the outbox table. Your pipeline starts at the relay.
The trap: a hard delete is invisible to updated_at. If a watermark is your only CDC, deleted customers live in the warehouse forever. That is a correctness bug and, under privacy laws such as GDPR, a legal one. Use a method that sees deletes, ask the source team for soft deletes (a deleted_at column, which turns a delete into an update), or run a regular full comparison of the keys.
Four ways to capture changes, side by side
| Method | How it works | Sees deletes? | The catch |
|---|---|---|---|
| Query on updatedat | WHERE updatedat watermark | No | Needs a column every write sets |
| Snapshot comparison | Copy the whole table each night and compare with the last copy | Yes | Reads everything; sees only end-of-day state |
| Log-based CDC | Read the database's own change log (Postgres WAL, MySQL binlog) | Yes, and every version | Needs a tool such as Debezium and access to the database |
| Outbox | The app writes a change event to an outbox table in the same transaction | Yes, if the app writes them | The app team must build it |
Most teams mix them: watermarks for big tables, snapshots for small ones, log-based CDC where every change counts.
Numbers to remember
| Name | Value | What it is |
|---|---|---|
| Debezium op codes | c, u, d, r, t, m | Create, update, delete, read (during a snapshot), truncate, and a message |
| sequence in source | the last committed LSN and this event's LSN | A sink can use it to drop replayed events |
| REPLICA IDENTITY DEFAULT | the default | Update and delete events carry only the primary key columns of the old row (for an update, only key columns that changed), so before is usually null for an update |
| REPLICA IDENTITY FULL | set per table | Logs the whole old row: a full before image, and more WAL per change. A sink can check that its copy matched the old row |
| tombstones.on.delete | default true | After each d event, send a null-valued record for the same key so log compaction can remove the key |
| snapshot.mode | initial, the default | Copy every table once in a REPEATABLE READ transaction (rows arrive as r events), then stream from the pinned position |
| Incremental snapshot | chunks of 1,024 rows by default | Triggered through a signal table; reads primary-key chunks between watermarks while streaming carries on. It avoids one transaction over a 2 TB table running for hours and holding back VACUUM (Lesson 6.7) |
| Databricks AUTO CDC INTO | formerly APPLY CHANGES INTO | Lakeflow Declarative Pipelines (formerly Delta Live Tables) apply a CDC feed for you: SEQUENCE BY lsn gives the order, APPLY AS DELETE WHEN op = 'd' handles deletes |
| Debezium and its managed cousins | AWS DMS, Fivetran | Debezium (open source, usually on Kafka Connect) is the standard for log-based CDC from Postgres, MySQL, SQL Server and others |
None of these are needed to follow the story. They are the settings that decide what your events look like.
What changed at SwiftKart
The catalogue is small, so it gets a nightly snapshot and a diff. The Smart Watch is now flagged as deleted in the warehouse, and each night's price changes are on record.
For orders and customers, Dana gives you a replication slot. Debezium reads the WAL, and a merge applies the latest event per key in LSN order, deletes included.
So far every source has been a tidy table. The next one is an API that returns nested JSON and grows new fields without telling you. Lesson 6.6 writes a loader for it.
In one line
A watermark misses deletes; snapshot diffs and log-based CDC see them, and a change feed is applied as the latest event per key in LSN order, with a branch for deletes.
Interview corner
What is change data capture, and what are the main approaches?
CDC is how you find what changed in a source so you copy only that. The approaches: querying an updated_at column (simple, misses deletes), comparing full snapshots (sees deletes, reads everything), log-based CDC such as Debezium reading the WAL or binlog (sees every change with low load), and the outbox pattern, where the app writes change events in the same transaction.
How does a CDC tool take its first full copy without missing changes made during the copy?
It pins a position in the log before it reads. Debezium on Postgres opens a REPEATABLE READ transaction, reads the current WAL position, scans every table as read events, commits, then streams from that position, so everything committed during the scan is replayed from the log. Rows changed mid-scan arrive twice, which the sink absorbs by merging on key and LSN. For very large tables I would use incremental snapshots, which read primary-key chunks between watermarks so no transaction runs for hours and holds back vacuum.
How do you capture deletes?
Not with updated_at, because a deleted row cannot be queried. Options: log-based CDC, which emits delete events; a snapshot or key comparison that finds keys that disappeared; or soft deletes in the source (deleted_at), which turn a delete into an update the watermark can see. In the warehouse I then hard-delete or flag the row.
How do you apply a CDC feed to a target table correctly?
Dedupe to the latest event per key by LSN, then MERGE: delete (or flag) when the latest op is a delete, update when matched, insert when not matched and not a delete. Applying in log order and keeping only the latest event makes the step idempotent, so a replayed batch gives the same table.