00:00

Change Data Capture with Debezium and Kafka

Last updated:

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 CDCLog-based CDC (Debezium)
How changes are foundPeriodic SELECT ... WHERE updated_at > ?Reading the database’s transaction log (PostgreSQL WAL, MySQL binlog, and so on)
DeletesInvisible unless rows are soft-deletedCaptured as delete events
Intermediate updatesLost if a row changes twice between pollsEvery committed change is captured
Load on the databaseRepeated queriesLow; the log is written anyway
Schema requirementsA reliable “last modified” columnNone 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.

CDC vs outbox: plain CDC publishes your table rows, which exposes the internal data model to every consumer. The transactional outbox pattern uses the same Debezium machinery on a dedicated outbox table, so you publish deliberate domain events instead. Use plain CDC for replication, caches and analytics; prefer the outbox for events consumed by other services.

3. How Debezium Works

Debezium change data capture with Kafka ConnectAn application writes to PostgreSQL. PostgreSQL records committed changes in its write-ahead log, which the Debezium PostgreSQL connector reads through a logical replication slot. The connector runs inside a Kafka Connect worker and writes one topic per table, for example shop.public.orders and shop.public.customers, and stores its position, the log sequence number, in the Connect offsets topic. Consumers such as a search indexer and a cache updater read the change topics. Order service PostgreSQLtablesWAL (committed) INSERT / UPDATE Kafka Connect workerDebezium connectorsnapshot, then streamoffset = last LSN replication slot shop.public.orders shop.public.customers connect-offsets Kafka topics searchindexer cacheupdater
Debezium reads committed changes from the database log and writes one Kafka topic per captured table.
  1. 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.
  2. 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 pgoutput plugin.
  3. 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.
  4. 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:

Update event value (simplified, schemas disabled)
{
  "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
}
FieldMeaning
opc create, u update, d delete, r read (snapshot), t truncate
beforeRow 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
afterRow state after the change; null for deletes
sourceWhere the change came from: database, table, log position, transaction ID, commit time
ts_msWhen 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:

docker-compose.yml (additional services)
  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:

orders-cdc.json
{
  "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"
  }
}
Terminal
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.

Database user: the example uses the table owner for simplicity. In production, create a dedicated user with the 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:

Additional connector settings
"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:

OrderChangeListener.java
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

PropertyDefaultWhat it does
topic.prefixnone (required)Logical name of the source; prefix of every topic. Never change it after go-live
table.include.listall tablesRegular expressions of schema.table names to capture
snapshot.modeinitialWhether and when to snapshot existing data; no_data captures only new changes
slot.namedebeziumReplication slot; must be unique per connector
publication.autocreate.modeall_tablesfiltered creates a publication only for the included tables
heartbeat.interval.ms0 (off)Emits heartbeats so the confirmed log position advances even when captured tables are quiet
tombstones.on.deletetrueEmit a tombstone after each delete event
decimal.handling.modeprecisestring 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

AdvantagesLimitations
No application changes and no dual writesRequires database log settings and replication privileges
Captures deletes and every committed update, in order per rowExposes the table structure to consumers unless you use an outbox
Low overhead on the database compared with pollingAn inactive or stopped connector can make the database retain log files
Snapshots give consumers a complete starting stateDelivery 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, so before is incomplete.
  • Changing topic.prefix or 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.

15. References