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.
See it run
One committed change, followed by many systems: the pipeline, its traps and how a consumer stays correct.
Operations
The pipeline
An insert, an update and a delete travel from the database to the search index.
Step 1 of 6
Insert
Committed
The app commits user 1. Its work is finished.
Step 1: Insert
db.commit(change) # the app is done hereevent = connector.read_next(log) # capturetopic.publish(key=event.key, event) # deliverfor event in topic.after(offset): # consume index.apply(event) offset += 1- Delay
- Usually seconds
- Handle
- Duplicates
The application never talks to Kafka or to search. That is the point.
In the real world
The same change data capture doing real jobs. Pick one and step through it.
A stopped connector endangers the database, not only the index.
Step 1 of 3
Friday
Silent
The connector stops. The app works normally and nobody notices.
Step 1: Friday
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Writing to both systems
criticalThere is no shared transaction. A crash or a race leaves two different answers.
Wrongdb.save(product)search.index(product)Rightdb.save(product) # CDC does the restAssuming one delivery
criticalA restart repeats the last events. Counters drift and emails go out twice.
Wrongstats["orders"] += 1Rightif event.id not in processed: stats["orders"] += 1 processed.add(event.id) # same transactionCrashing on a tombstone
majorAfter a delete comes a message without a value. Parsing it fails and blocks the partition.
Wrongevent = json.loads(message.value)Rightif message.value is None: return # tombstoneevent = json.loads(message.value)Bookmark before work
majorIf the process dies in between, the event is never processed.
Wrongcommit(offset)apply(event)Rightapply(event) # idempotentcommit(offset)
Interview tips
How to explain it
- Every committed change becomes an event.
- Others follow with a bookmark.
- It replaces dual writes.
Memory trick: CDC
- Capture: read from the log.
- Deliver: publish to a stream.
- Consume: apply, then bookmark.
Reach for it when
- Search, cache or warehouse must follow.
- Deletes matter.
- New readers keep appearing.
Leave it when
- A read replica is enough.
- A nightly export is enough.
- The answer is needed inside the transaction.