Change Data Capture with Debezium and Kafka
Change Data Capture (CDC) turns every insert, update and delete in a database into an event in Kafka. Debezium is the most widely used open-source CDC platform: its connectors read the database’s own transaction log and publish each committed change to a Kafka topic, without changing application code and without polling tables.
This tutorial explains log-based CDC, how Debezium works on top of Kafka Connect, what a change event looks like, how to capture a PostgreSQL table step by step, and how to consume the events in Spring Boot. It finishes with the operational issues that matter in production, such as replication slots and snapshots.
1. What Is Change Data Capture?
CDC is the practice of detecting changes in a database and delivering them to other systems. There are two main approaches:
| Query-based CDC | Log-based CDC (Debezium) | |
|---|---|---|
| How changes are found | Periodic SELECT ... WHERE updated_at > ? | Reading the database’s transaction log (PostgreSQL WAL, MySQL binlog, and so on) |
| Deletes | Invisible unless rows are soft-deleted | Captured as delete events |
| Intermediate updates | Lost if a row changes twice between polls | Every committed change is captured |
| Load on the database | Repeated queries | Low; the log is written anyway |
| Schema requirements | A reliable “last modified” column | None in the tables; database-level log settings instead |
Debezium implements log-based CDC for PostgreSQL, MySQL, MariaDB, SQL Server, Oracle, MongoDB, Db2 and others. It most often runs as a set of source connectors in Kafka Connect; Debezium Server and an embedded engine exist for setups without Kafka Connect.
2. Why Use CDC Instead of Dual Writes or Polling?
Suppose an order service must keep a search index and a cache in sync with its orders table. Writing to the database and then publishing to Kafka from the same code (a dual write) fails whenever one of the two writes succeeds and the other does not: the database and the event stream drift apart. Polling avoids the dual write but misses deletes and intermediate updates and adds load. CDC reads changes from the log after they are committed, so Kafka sees exactly what the database committed, in commit order per row.
3. How Debezium Works
- Snapshot. On first start (with the default
snapshot.mode=initial), the connector reads the current content of the captured tables and emits a read event per row, so consumers start with a complete picture. - Streaming. It then reads the transaction log from the position where the snapshot was consistent. For PostgreSQL this happens through a logical replication slot using the built-in
pgoutputplugin. - Publishing. Each change becomes a record in a topic named
topicPrefix.schemaName.tableName, keyed by the row’s primary key, so all changes of one row land in the same partition and keep their order. - Offsets. Kafka Connect stores the connector’s log position (for PostgreSQL, the LSN) in its offsets topic and confirms it to the database, which lets PostgreSQL discard WAL that is no longer needed. After a restart, streaming resumes from the stored position.
4. Anatomy of a Change Event
The record key contains the primary key, for example {"id": 1001}. The value is an envelope describing the change:
{
"before": { "id": 1001, "status": "PLACED", "total": "249.90" },
"after": { "id": 1001, "status": "SHIPPED", "total": "249.90" },
"source": { "connector": "postgresql", "db": "shop", "schema": "public",
"table": "orders", "lsn": 24023128, "txId": 591, "ts_ms": 1764835200000 },
"op": "u",
"ts_ms": 1764835200412
}
| Field | Meaning |
|---|---|
op | c create, u update, d delete, r read (snapshot), t truncate |
before | Row state before the change; null for inserts. In PostgreSQL it contains all columns only if the table’s REPLICA IDENTITY is FULL, otherwise just the key columns |
after | Row state after the change; null for deletes |
source | Where the change came from: database, table, log position, transaction ID, commit time |
ts_ms | When Debezium processed the event (source.ts_ms is when the database made the change) |
A delete produces two records by default: a delete event (op = d) and then a tombstone, a record with the same key and a null value. The tombstone lets log compaction remove the row’s history from a compacted topic.
5. Example: Capturing a PostgreSQL Table
Run PostgreSQL with logical decoding enabled and a Kafka Connect worker with the Debezium connectors, next to the broker from the Kafka Docker setup:
postgres:
image: postgres:17
command: ["postgres", "-c", "wal_level=logical"]
environment:
POSTGRES_DB: shop
POSTGRES_USER: shop
POSTGRES_PASSWORD: shop-secret
ports:
- "5432:5432"
connect:
image: quay.io/debezium/connect:3.7
ports:
- "8083:8083"
environment:
BOOTSTRAP_SERVERS: broker:19092
GROUP_ID: cdc-connect
CONFIG_STORAGE_TOPIC: cdc_connect_configs
OFFSET_STORAGE_TOPIC: cdc_connect_offsets
STATUS_STORAGE_TOPIC: cdc_connect_statuses
CONFIG_STORAGE_REPLICATION_FACTOR: 1
OFFSET_STORAGE_REPLICATION_FACTOR: 1
STATUS_STORAGE_REPLICATION_FACTOR: 1
depends_on:
broker:
condition: service_healthy
postgres:
condition: service_started
Create a table and register the connector through the Kafka Connect REST API:
{
"name": "orders-cdc",
"config": {
"connector.class": "io.debezium.connector.postgresql.PostgresConnector",
"plugin.name": "pgoutput",
"database.hostname": "postgres",
"database.port": "5432",
"database.user": "shop",
"database.password": "shop-secret",
"database.dbname": "shop",
"topic.prefix": "shop",
"table.include.list": "public.orders",
"slot.name": "orders_cdc_slot",
"publication.autocreate.mode": "filtered",
"key.converter": "org.apache.kafka.connect.json.JsonConverter",
"key.converter.schemas.enable": "false",
"value.converter": "org.apache.kafka.connect.json.JsonConverter",
"value.converter.schemas.enable": "false",
"decimal.handling.mode": "string"
}
}
docker compose exec postgres psql -U shop -d shop -c \
"CREATE TABLE orders (id BIGINT PRIMARY KEY, status TEXT NOT NULL, total NUMERIC(12,2) NOT NULL);
ALTER TABLE orders REPLICA IDENTITY FULL;"
curl -s -X POST -H "Content-Type: application/json" \
--data @orders-cdc.json http://localhost:8083/connectors
curl -s http://localhost:8083/connectors/orders-cdc/status
# {"name":"orders-cdc","connector":{"state":"RUNNING",...},"tasks":[{"id":0,"state":"RUNNING",...}]}
docker compose exec postgres psql -U shop -d shop -c \
"INSERT INTO orders VALUES (1001, 'PLACED', 249.90); UPDATE orders SET status = 'SHIPPED' WHERE id = 1001;"
The topic shop.public.orders now contains a create event and an update event for order 1001, in that order. The JSON converter with schemas.enable=false keeps the example readable; in production, Avro or Protobuf with Schema Registry gives smaller records and managed schema evolution.
REPLICATION attribute and only the privileges Debezium needs, and create the publication yourself if the connector user should not own the tables.6. Simplifying Events with ExtractNewRecordState
Many consumers only need the new row, not the full envelope. Debezium’s ExtractNewRecordState single message transform (SMT) replaces the value with the after state and can add selected metadata as fields:
"transforms": "unwrap",
"transforms.unwrap.type": "io.debezium.transforms.ExtractNewRecordState",
"transforms.unwrap.add.fields": "op,table,lsn",
"transforms.unwrap.delete.tombstone.handling.mode": "rewrite"
With delete.tombstone.handling.mode=rewrite, a delete becomes a record with the deleted row’s fields and an added __deleted field set to true, which suits sinks that cannot handle null values. Keep the full envelope when consumers need the before state, for example for auditing.
7. Consuming Change Events in Spring Boot
A consumer that keeps a read-optimised view in sync must handle creates, updates, snapshot reads and deletes, and must tolerate duplicates, because Debezium delivers at least once by default:
package com.javabytechie.search;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.json.JsonMapper;
@Component
public class OrderChangeListener {
private final JsonMapper mapper = JsonMapper.builder().build();
private final OrderSearchIndex index; // your search or cache client
public OrderChangeListener(OrderSearchIndex index) {
this.index = index;
}
@KafkaListener(topics = "shop.public.orders", groupId = "order-search-indexer")
public void onChange(@Payload(required = false) String value) {
if (value == null) {
return; // tombstone after a delete: nothing more to do
}
JsonNode event = mapper.readTree(value);
String op = event.path("op").asString();
switch (op) {
case "c", "r", "u" -> {
JsonNode after = event.path("after");
// upsert by primary key: replaying the same event gives the same result
index.upsert(after.path("id").asLong(), after.path("status").asString(),
after.path("total").asString());
}
case "d" -> index.delete(event.path("before").path("id").asLong());
default -> { } // ignore truncate and other types here
}
}
}
@Payload(required = false) lets Spring pass a tombstone’s null value to the listener instead of failing on it. Upserts and deletes keyed by the primary key are naturally idempotent, so redelivered events after a connector restart do no harm.
8. Important Configuration
| Property | Default | What it does |
|---|---|---|
topic.prefix | none (required) | Logical name of the source; prefix of every topic. Never change it after go-live |
table.include.list | all tables | Regular expressions of schema.table names to capture |
snapshot.mode | initial | Whether and when to snapshot existing data; no_data captures only new changes |
slot.name | debezium | Replication slot; must be unique per connector |
publication.autocreate.mode | all_tables | filtered creates a publication only for the included tables |
heartbeat.interval.ms | 0 (off) | Emits heartbeats so the confirmed log position advances even when captured tables are quiet |
tombstones.on.delete | true | Emit a tombstone after each delete event |
decimal.handling.mode | precise | string or double make decimals readable without the Connect decimal type |
9. Real-World Use Cases
- Search and cache synchronisation: keep Elasticsearch, OpenSearch or Redis in sync with the system of record.
- Analytics pipelines: stream operational data into a data lake or warehouse without nightly batch exports.
- Strangler migrations: replicate a legacy database into a new service while traffic moves over gradually.
- Outbox publishing: capture an outbox table and route its rows as domain events.
- Audit trails: keep every before and after state of sensitive tables in a retained topic.
10. Advantages and Limitations
| Advantages | Limitations |
|---|---|
| No application changes and no dual writes | Requires database log settings and replication privileges |
| Captures deletes and every committed update, in order per row | Exposes the table structure to consumers unless you use an outbox |
| Low overhead on the database compared with polling | An inactive or stopped connector can make the database retain log files |
| Snapshots give consumers a complete starting state | Delivery is at least once by default; consumers must handle duplicates |
11. Common Mistakes
- Leaving a replication slot behind. If a connector is deleted or stopped for a long time, its slot still holds WAL and the database disk fills up. Drop unused slots and alert on slot lag.
- No heartbeats on quiet tables. When the captured tables rarely change but others change a lot, the confirmed position does not advance and WAL accumulates; set
heartbeat.interval.ms. - Expecting full before images. Without
REPLICA IDENTITY FULL, PostgreSQL logs only key columns as the old state, sobeforeis incomplete. - Changing
topic.prefixor the slot name. The connector then behaves like a new one: new topics, a new snapshot, and a forgotten old slot. - Treating events as exactly-once. After failures, events can be delivered again; write idempotent consumers.
- Coupling services to table columns. Renaming a column becomes a breaking change for every consumer; publish domain events through an outbox for inter-service communication.
12. Best Practices
- Capture only what you need with
table.include.list, and give each connector its own slot and publication. - Monitor slot lag and connector status together with broker metrics; see Kafka monitoring and metrics.
- Use Avro or Protobuf with Schema Registry so schema changes in the database are tracked and checked.
- Size topic partitions and compaction for the table: compacted topics with tombstones keep the latest state per key.
- Plan snapshots of large tables; incremental snapshots can be triggered later through signals without stopping streaming.
13. Summary
Change data capture streams every committed database change into Kafka. Debezium does it by reading the transaction log, through a replication slot in PostgreSQL, and publishing keyed events per table with before and after states and an operation code. Start with a snapshot, keep one slot per connector, enable heartbeats, make consumers idempotent, and use the outbox pattern when other services need stable domain events rather than table rows.
14. Related Reading
- Kafka Connect: workers, connectors, converters and SMTs
- Transactional outbox with Kafka: publishing domain events with Debezium’s outbox router
- Idempotent consumer: handling redelivered events safely
- Event sourcing and CQRS: CDC-fed read models vs event-sourced systems
15. References
Change Data Capture with Debezium Interview Questions and Answers
Common interview questions on Change Data Capture with Debezium, from basic to scenario-based, with short answers you can explain in your own words.
Basic questions
Q. What is the difference between log-based and query-based change data capture?
Answer: Query-based CDC polls tables with queries such as WHERE updated_at > ?; it misses deletes and intermediate updates between polls and adds load. Log-based CDC, which Debezium uses, reads the database’s transaction log (WAL, binlog and so on), so it sees every committed insert, update and delete in commit order, with little extra load and no changes to the tables.
Q. What does a Debezium change event contain?
Answer: The key holds the row’s primary key. The value is an envelope with before and after row states, source metadata (database, table, log position, transaction, commit time), an op code (c, u, d, r for snapshot reads, t for truncate) and a processing timestamp. Inserts have no before state and deletes have no after state.
Intermediate questions
Q. Why does Debezium emit a tombstone after a delete event?
Answer: The delete event tells consumers that the row was removed, but it still has a value. Log compaction only removes a key’s history when the latest record for that key has a null value. The following tombstone, same key and null value, lets a compacted topic eventually drop the deleted row completely. It can be disabled with tombstones.on.delete=false when topics are not compacted.
Q. What ordering guarantees do Debezium change events have?
Answer: Events are keyed by primary key, so all changes of one row go to the same partition and are read in commit order. There is no ordering across rows in different partitions or across tables in different topics. A consumer that needs to see a whole transaction can use Debezium’s optional transaction metadata topic, which marks transaction boundaries.
Q. What is the initial snapshot, and when would you skip it?
Answer: With the default snapshot.mode=initial, the connector first reads the existing rows of the captured tables and emits them as r events, then streams changes from a consistent log position. Consumers therefore start with a complete state. You might skip it (no_data) when only new changes matter, or when the data is loaded another way; very large tables are often snapshotted incrementally instead.
Tricky and scenario questions
Q. The PostgreSQL disk keeps filling up with WAL files after a Debezium connector was stopped for maintenance. What is happening?
Answer: The connector’s logical replication slot still exists, and PostgreSQL must keep all WAL from the slot’s confirmed position onwards until a consumer confirms it. With the connector stopped, the position never advances. Restart the connector or, if it is gone for good, drop the slot. The same effect appears with a running connector when its tables are quiet and other tables are busy; enable heartbeat.interval.ms and alert on slot lag.
Q. Three other services consume your orders table’s CDC topic, and now you need to split one column into two. What is the risk, and what would you change?
Answer: Raw CDC publishes the table structure, so the schema change breaks all three consumers at once. For a one-off, add the new columns, keep the old one until consumers migrate, and track the schemas in Schema Registry. The lasting fix is to stop sharing table rows: publish domain events through a transactional outbox, which Debezium can route with its outbox event router, so the table can change without breaking consumers.