SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
  • Batch vs Stream Processing
  • Change Data Capture (CDC)
  • MapReduce
  • ETL Pipelines
  • Data Lakes
  • Data Warehousing
  • Data Lakehouse
  • Lambda Architecture
  • Kappa Architecture
  • Streaming Engines
  • Spark and Hadoop
  • Workflow Orchestration (Airflow)
  • Parquet and Columnar File Formats
  • Data Governance and Feature Stores
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Advanced Data Topics/Big Data Processing

Change Data Capture (CDC)

Read every change made in a database and send it on to other systems.

⏱ 13 min readIntermediateInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Change Data Capture (CDC) means watching a database and turning every insert, update and delete into an event that other systems can read.

  • The main database stays the source of truth. Other systems (a search index, a cache, a warehouse) get a copy that follows it.
  • The best way is log-based: read the log the database already writes for its own safety, so the tables are not queried at all.
  • The events arrive in order, and nothing is missed, not even deletes.

02Concept: What is it?

Most systems keep the same data in more than one place. The orders live in a database, but the website also needs them in a search index, the analysts need them in a warehouse, and a cache must not show old prices. The question is: how do these copies find out that something changed?

One way is to ask the database again and again: "What is new since last time?" (polling). Another is to change the application so it also writes to every other system (a dual write). CDC offers a third way: let the database tell you, by reading its own record of changes.

Databases already keep such a record. PostgreSQL has the write-ahead log (WAL), MySQL has the binlog. Before a change is made to a table, it is first written to this log, so the database can recover after a crash. A CDC tool such as Debezium reads this log like a reader following a diary, and publishes one event per change, often to a message system such as Kafka.

Log-based CDC
🖥️Appwrites as usual
→↓insert / update / delete
🗄️Databasetables + log
→↓log entries
🔌CDC readere.g. Debezium
→↓events
📬Event streame.g. Kafka
The app only talks to its database. A separate reader turns the database log into events for everyone else.
🧠One event per change
A CDC event says what happened to a row: the operation (create, update or delete), the row before and the row after. A consumer can rebuild the copy, or react to the change, from this alone.

03Real-Life Example

🍵The Shop Ledger and the Branch Offices
A shop keeps one main ledger. Every sale, change and cancellation is first written in it. Three branch offices need to stay up to date: one sends invoices, one tracks stock, one makes reports. In the first way, each office phones the shop every hour and asks "what changed?". In the second way, the shop clerk also phones all three offices after every sale, and sometimes forgets one. In the CDC way, a messenger sits next to the ledger and copies each new line the moment it is written, then delivers it to every office in order.
Shop
CDC
The main ledger
The source database
Each new line written in the ledger
An entry in the database log (WAL, binlog)
The messenger who copies lines
The CDC reader (Debezium and similar)
The messenger's delivery bag
The event stream (Kafka or another queue)
Branch offices
Consumers: search index, cache, warehouse
Phoning every hour to ask
Polling with a timestamp query
The clerk phoning each office
Dual write from the application
The messenger's bookmark in the ledger
The log position (offset) that lets him resume
Three ways to find out what changed
Polling
⏰Ask every N minutes
😕Misses deletes and in-between versions
Triggers
🪝Copy each change into an audit table
🐢Slows every write
Log-based
📖Read the database log
✅Complete, ordered, light

04Why Do We Need It?

🔄Keep copies in sync
A search index, a cache and a warehouse can follow the main database without changes to the application.
🎯Nothing is missed
Deletes and every step of a row's history are seen. Polling cannot promise this.
⚡Low delay
Events arrive soon after the commit, often within a second, not at the next hourly job.
🪶Light on the database
The reader uses a log the database writes anyway, so no heavy queries run on the tables.
🧩Decoupling
The app does not need to know who needs the data. New consumers just subscribe to the stream.
🚚Safer migrations
Copy a live database to a new one without stopping it, by replaying changes until they catch up.
Do not ask the database "what changed?" again and again. Read the record it already keeps, and turn it into events.

05Where Do We Use It?

🔎Search indexes
Update Elasticsearch or OpenSearch when a product row changes.
🧠Cache invalidation
Remove or refresh a cache entry when the row behind it changes.
🏢Data warehouses and lakes
Stream changes into analytics storage instead of copying whole tables each night.
📬Event-driven systems
Turn database changes into events that other services react to.
🔁Database migration
Move to a new database or a new engine with almost no downtime.
🧾Audit and history
Keep a record of who changed what and when, built from the change stream.

06Types / Parts / How It Works

The ways to capture changes

MethodHow it worksGoodBad
Polling (query-based)A job runs a query such as WHERE updated_at > last runSimple, works on any databaseMisses deletes, merges changes between polls, adds load, needs a reliable timestamp column
TriggersA database trigger copies each change into an audit tableSees all changes, including deletesEvery write does extra work in the same transaction, so writes slow down
Log-basedRead the WAL or binlog and turn entries into eventsComplete, ordered, very light on the tables, low delayNeeds database settings and permissions, depends on the database's log format
Dual write (not CDC)The app writes to the database and to another systemNo extra toolCan leave the two out of step if one write fails (see Outbox Pattern)

What a change event holds

One update, as an event
Before
📄Order 1status: paid
Event
🏷️operation: update
🔢log position + time
🗄️table: orders, key: 1
After
📄Order 1status: shipped
Old row Event details New row
The exact field names depend on the tool. The idea is the same everywhere.

The two phases of a CDC tool

PhaseWhat happensWhy
SnapshotRead all existing rows once and emit them as eventsA new consumer needs the data that was there before the first log entry it sees
StreamingFollow the log and emit each new changeKeeps the copy up to date from then on, starting from a saved log position
VisualizerPolling vs triggers vs log-based CDCRun the same eight changes under each method. Use polling with a long interval and watch changes get merged, and the deleted row stay in the copy. Then switch to log-based.
How do we find out what changed?

A job runs SELECT ... WHERE updated_at > last_run every few changes. It only sees the rows that exist at that moment.

Source table: orders
#1 Book shipped
#3 Lamp paid
#4 Mug new
What polling saw
row #1 is now Book (paid)
row #2 is now Pen (new)
row #1 is now Book (shipped)
row #3 is now Lamp (new)
Copy (search index, cache or warehouse)
#1 Book shipped
#2 Pen new
#3 Lamp new
#4 missing in the copy
Changes made
8
on the source
Events delivered
4
to the copy
Never seen
2
lost between polls
Rows wrong in copy
3
stale, missing or ghost
Poll queries
2
run on the source table
Row #2 was deleted at the source, but the copy still has it. A poll only looks at rows that still exist, so it can never see a delete.

A small model with eight fixed changes and no random numbers. In a real system the log reader adds a little delay, and triggers and polling have more edge cases. The comparison of what each method can and cannot see is the part that carries over.

07How to Use It / Steps / Implementation

Setting up log-based CDC

  1. 1
    Turn on the log in a readable form
    For example, PostgreSQL needs logical decoding (wal_level = logical) and MySQL needs the binlog in row format. A DBA often has to do this.
  2. 2
    Give the reader a limited user
    Create a user that can read the log and the tables it must watch, and nothing else.
  3. 3
    Choose what to watch
    Pick the tables (and, if needed, the columns). Do not stream everything by default, especially not tables with sensitive data.
  4. 4
    Run the snapshot, then stream
    The tool copies the existing rows first, then follows the log from the position where the snapshot started.
  5. 5
    Send the events to a stream
    A common setup is Debezium running on Kafka Connect, publishing one topic per table. Use the row key as the message key, so changes to one row stay in order.
  6. 6
    Make consumers idempotent
    After a crash the reader may send some events again. A consumer should be able to apply the same event twice with the same result.
  7. 7
    Handle schema changes
    Plan for new or renamed columns. A schema registry and compatible changes keep consumers from breaking.
  8. 8
    Watch the lag and the log
    Track how far behind the reader is. A stuck reader makes the database keep old log files, which can fill the disk.
💡Save the position
The reader stores the last log position it handled. After a restart it continues from there, so it neither skips changes nor starts over. This is why a CDC consumer is usually "at least once", and why it must handle repeats.
⚠️A paused reader can hurt the database
The database keeps log files until the reader has read them. If the reader is stopped for days, the log can grow until the disk is full. Alert on lag, and drop unused connectors.

08Key Terms to Know

TermMeaning in easy words
CDCChange Data Capture: turning each database change into an event
WAL / binlogThe log a database writes before changing tables (PostgreSQL calls it WAL, MySQL calls it binlog)
Log-based CDCReading that log to find changes, without querying the tables
DebeziumA well-known open-source CDC tool, often run on Kafka Connect
Change eventA message with the operation, the row before and the row after
SnapshotThe first full copy of existing rows, before the stream of changes starts
Log position (offset)A marker saying how far in the log the reader has read
Replication slotA PostgreSQL feature that remembers the reader's place so the log is kept for it
TombstoneA special event used after a delete, so downstream stores can remove the key
Dual writeWriting to two systems from the app, which can leave them in disagreement
LagHow far the copy is behind the source, in time or in log position

09Pros, Cons and Trade-offs

✅ Pros
  • Sees every change, including deletes
  • Events keep the order of the database
  • Very low load on the source tables
  • Low delay compared to batch jobs
  • No changes needed in the application code
  • Many consumers can read the same stream
⚠️ Cons
  • Needs database configuration and permissions
  • Tied to the database's log format and version
  • Consumers see repeats and must be idempotent
  • Schema changes can break downstream systems
  • Extra moving parts to run and watch (reader, stream)
  • Row-level events do not carry business meaning by themselves

Trade-offs

ChoiceWe gainWe lose
Log-based instead of pollingComplete data, deletes, low delay and less loadMore set-up and a more complex stack
Triggers instead of log-basedWorks where the log is not availableSlower writes and more load on the database
CDC instead of dual writeNo chance that the two systems drift apart because of a failed second writeA new component to operate
Stream every tableEasy to start, flexible laterMore data, more cost, more privacy risk
CDC events as the public APIQuick to buildConsumers depend on your table design; changing it breaks them
Short retention of the logLess disk usedA consumer that is down too long must take a new snapshot

10Common Problems and Mistakes

Common mistakes

  1. Polling with updated_at and trusting it. Deletes are invisible, and rows updated by scripts that forget the timestamp are missed.
  2. Forgetting repeats. The same event can arrive twice after a restart. A non-idempotent consumer then double-counts.
  3. Ignoring ordering. If events for one row land in different partitions, an old update can be applied after a newer one. Use the row key as the partition key.
  4. Exposing the table design. Other teams build on your raw tables, and now you cannot rename a column.
  5. Leaving a stuck reader running. The database keeps its log and the disk fills up.
  6. Streaming secrets. Passwords or personal data in a table end up in the stream and in every consumer.
  7. No plan for a new consumer. A consumer that joins late has no old data unless there is a snapshot or a long enough log.

Things to watch

⏳Replication lag
The copy is behind. Show the lag on a dashboard and alert when it grows.
💽Growing log
A slow or dead reader makes the database keep log files. Watch the disk.
🧬Schema drift
A column is added or its type changes and a consumer fails. Use compatible changes.
🔀Failover
After a database failover the log position may change. Test that the reader resumes without gaps.

11Real-World Examples

🔌Debezium
An open-source tool that reads the logs of databases like PostgreSQL, MySQL and MongoDB and publishes events, commonly through Kafka.
☁️Managed services
Cloud providers offer migration and replication services that use the same log-reading idea (for example AWS DMS).
🔎Search and cache sync
Many companies keep a search index or cache current by consuming change events instead of writing to them from the app.
🏢Warehouse loading
Changes flow into analytics stores continuously, so reports are minutes old, not a day old.
🧱Outbox with CDC
The Outbox pattern often uses CDC to publish the rows of an outbox table as events.
🚚Live migrations
Teams move big databases to a new system by copying a snapshot and then following changes until the copy has caught up.
📝Note
Product names, settings and features change between versions. Check the current documentation of your database and CDC tool before you plan a rollout.
Mini case: keep a search index current
🛒Shop appupdates a product
→↓
🗄️PostgreSQLWAL
→↓log
🔌Debezium
→↓events
📬Kafka
→↓
🔎Search indexupdated in seconds
The shop app never calls the search engine. It only writes to its database.

12Related Topics to Read Next

Outbox Pattern→

Publishes events reliably, and is often built on CDC.

Replication→

CDC follows the same kind of log that replication uses.

Message Brokers→

Where CDC events are usually sent and stored.

Batch vs Stream Processing→

CDC turns a database into a stream you can process.

Cache Invalidation→

A change event is a clean signal to refresh a cache.

Idempotency→

Consumers must handle the same event twice.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: turn every database change into an event.
  • ✔Best way: log-based: read the WAL or binlog, do not query the tables.
  • ✔Polling: misses deletes and in-between versions. Triggers: slow every write.
  • ✔Event: operation, row before, row after, log position.
  • ✔Phases: snapshot first, then stream from a saved position.
  • ✔Delivery: at least once. Make consumers idempotent. Key by row to keep order.
  • ✔Watch: lag, the growing log on the source, schema changes.
  • ✔One line: “Do not ask the database what changed. Read the diary it already keeps.”
← Previous
Batch vs Stream Processing
Next →
MapReduce