Change Data Capture with Debezium and Postgres

data-engineering
tutorial
Hands-on tutorial: stream every INSERT, UPDATE and DELETE from Postgres into Kafka using Debezium, without touching your application code.
Author

WillzWayn

Published

February 28, 2026

What we are building

Your application writes to Postgres. Something else — a search index, a cache, a data warehouse, another service — needs to know about those writes. The usual answers are polling (WHERE updated_at > ?, slow and lossy) or dual writes (the app writes to the DB and publishes an event, which silently drifts out of sync the first time a transaction rolls back).

Change Data Capture takes a third route: read the database’s own replication log. Postgres already writes every committed change to the WAL so replicas can follow along. Debezium pretends to be a replica, decodes the WAL, and publishes one Kafka message per row change. Nothing in your application changes, and you cannot miss an event, because the source of truth is the same log the database uses to stay consistent with itself.

By the end of this tutorial you will have:

Postgres writes to its WAL; Debezium decodes the WAL via a replication slot and publishes one message per row change to a Kafka topic.

and you will have read the actual JSON events for an insert, an update and a delete.

Every command and every output in this tutorial was run end to end against Debezium 2.6.2, Kafka 7.5.0 and Postgres 16; the JSON below is captured, not illustrative.

Prerequisites: Docker with Compose v2 (docker compose version), curl, and roughly 3 GB of free RAM. Everything runs locally; no cloud account needed.

Step 1 — The stack

Create a docker-compose.yml:

services:
  zookeeper:
    image: confluentinc/cp-zookeeper:7.5.0
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000

  kafka:
    image: confluentinc/cp-kafka:7.5.0
    depends_on:
      - zookeeper
    ports:
      - "9092:9092"
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092,PLAINTEXT_INTERNAL://kafka:29092
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_INTERNAL:PLAINTEXT
      KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT_INTERNAL
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1

  postgres:
    image: debezium/postgres:16-alpine
    ports:
      - "5432:5432"
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgrespassword
      POSTGRES_DB: app_db
    # The debezium/postgres image already ships with wal_level=logical

  debezium:
    image: debezium/connect:2.6
    ports:
      - "8083:8083"
    depends_on:
      - kafka
      - postgres
    environment:
      BOOTSTRAP_SERVERS: kafka:29092
      GROUP_ID: 1
      CONFIG_STORAGE_TOPIC: connect_configs
      OFFSET_STORAGE_TOPIC: connect_offsets
      STATUS_STORAGE_TOPIC: connect_statuses
      KEY_CONVERTER: org.apache.kafka.connect.json.JsonConverter
      VALUE_CONVERTER: org.apache.kafka.connect.json.JsonConverter
      ENABLE_DEBEZIUM_SCRIPTING: "false"

Two details that are easy to get wrong:

  • Two Kafka listeners. localhost:9092 is what your laptop uses, kafka:29092 is what other containers use. A single listener means either your host tools or Debezium will fail to connect, and the error message (Connection to node -1 could not be established) will not tell you which.
  • wal_level=logical. Without it Postgres does not put enough information in the WAL to reconstruct row changes. The debezium/postgres image sets it for you; on a real database you set it in postgresql.conf and restart.

Bring it up:

docker compose up -d

Kafka Connect takes 30–60 seconds to boot. Wait for the REST API to answer:

until curl -sf http://localhost:8083/ > /dev/null; do sleep 2; done
echo "Connect is up"

Step 2 — The table

docker compose exec postgres psql -U postgres -d app_db -c "
CREATE TABLE orders (
    id SERIAL PRIMARY KEY,
    customer_id INT,
    amount NUMERIC(10, 2),
    status VARCHAR(50)
);
"

The primary key matters: Debezium uses it as the Kafka message key, which is what gives you per-row ordering and lets log compaction keep the latest state of every row.

Insert one row before registering the connector — we will use it to see the initial snapshot:

docker compose exec postgres psql -U postgres -d app_db -c "
INSERT INTO orders (customer_id, amount, status) VALUES (1, 150.00, 'PENDING');
"

Step 3 — Register the connector

Kafka Connect is configured over HTTP. Posting this JSON creates the replication slot in Postgres and starts streaming:

curl -i -X POST -H "Accept:application/json" -H "Content-Type:application/json" \
  http://localhost:8083/connectors/ \
  -d '{
    "name": "orders-connector",
    "config": {
      "connector.class": "io.debezium.connector.postgresql.PostgresConnector",
      "tasks.max": "1",
      "plugin.name": "pgoutput",
      "database.hostname": "postgres",
      "database.port": "5432",
      "database.user": "postgres",
      "database.password": "postgrespassword",
      "database.dbname": "app_db",
      "topic.prefix": "pg_cdc",
      "table.include.list": "public.orders"
    }
  }'

What the important keys do:

Key Meaning
plugin.name: pgoutput Use the logical decoding plugin built into Postgres 10+. No extension to install.
topic.prefix First segment of the topic name and the logical identity of this server. Changing it later creates new topics and re-snapshots.
table.include.list Whitelist of schema.table. Omit it and you capture the whole database — rarely what you want.
tasks.max: 1 Postgres CDC is inherently single-threaded per connector: one replication slot, one ordered stream. Anything above 1 is ignored.

Check it actually started — a 201 Created only means the config was accepted, not that the task is running:

curl -s http://localhost:8083/connectors/orders-connector/status | jq

You want "state": "RUNNING" for both the connector and the task. If the task is FAILED, the trace field in that same JSON has the stack trace; the most common cause is a typo in the database credentials.

Step 4 — Read the events

Debezium publishes to <topic.prefix>.<schema>.<table>, so here: pg_cdc.public.orders. Open a consumer in a second terminal and leave it running:

docker compose exec kafka kafka-console-consumer \
  --bootstrap-server kafka:29092 \
  --topic pg_cdc.public.orders \
  --from-beginning

You should already see one event: the snapshot of the row inserted in step 2. Debezium’s first act on a new connector is to read the current contents of the table, so consumers start from a complete picture rather than from “whatever happens next”.

Now, in the first terminal, generate the three kinds of change:

docker compose exec postgres psql -U postgres -d app_db -c "
INSERT INTO orders (customer_id, amount, status) VALUES (2, 99.90, 'PENDING');
UPDATE orders SET status = 'PAID' WHERE id = 2;
DELETE FROM orders WHERE id = 2;
"

Three more events appear in the consumer — four, actually. Reduced to the fields that matter, the topic now holds:

msg 0: op=r  after={"id":1,...,"status":"PENDING"}   <- snapshot
msg 1: op=c  after={"id":2,...,"status":"PENDING"}
msg 2: op=u  after={"id":2,...,"status":"PAID"}
msg 3: op=d  before={"id":2,...}  after=null
msg 4: TOMBSTONE (value=null)

Step 5 — Read the envelope

Every event has the same shape (the schema block is omitted here; it is large and repetitive — see the cleanup section for how to turn it off):

{
  "payload": {
    "before": null,
    "after": {
      "id": 2,
      "customer_id": 2,
      "amount": "JwY=",
      "status": "PENDING"
    },
    "source": {
      "version": "2.6.2.Final",
      "connector": "postgresql",
      "name": "pg_cdc",
      "db": "app_db",
      "schema": "public",
      "table": "orders",
      "snapshot": "false",
      "txId": 747,
      "lsn": 27577384
    },
    "op": "c",
    "ts_ms": 1789914921440
  }
}

The whole model is in four fields:

  • op — c create, u update, d delete, r read (snapshot).
  • before — row state before the change. null for inserts.
  • after — row state after the change. null for deletes.
  • source.lsn — the WAL position. This is your ordering key and your idempotency key: replay the same event twice and a consumer that tracks the highest LSN per row can discard the duplicate. Debezium guarantees at-least-once delivery, not exactly-once, so you will need this eventually.

Two surprises worth knowing now, because both look like bugs:

amount is "JwY=", not 99.90. Postgres NUMERIC is arbitrary precision, so the default JSON encoding is a base64 two’s-complement integer plus a scale, which is lossless but unreadable. If you would rather have a string, add to the connector config:

"decimal.handling.mode": "string"

(double is also available, and lossy — fine for analytics, not for money.)

On the DELETE, before is mostly null — you get {"id":2,"customer_id":null,"amount":null,"status":null}. By default Postgres only puts the primary key of the deleted row in the WAL. To get the full previous row you have to tell Postgres to log it:

docker compose exec postgres psql -U postgres -d app_db -c "
ALTER TABLE orders REPLICA IDENTITY FULL;
"

Repeat the update/delete after running that and before is now complete:

op=u before={"id":3,"customer_id":9,"amount":"HhQ=","status":"PENDING"}
     after ={"id":3,"customer_id":9,"amount":"HhQ=","status":"PAID"}
op=d before={"id":3,"customer_id":9,"amount":"HhQ=","status":"PAID"}
     after =null

Note that the update event gained a real before too — without REPLICA IDENTITY FULL you cannot tell what changed, only what the row looks like now. The cost is a bigger WAL, so turn it on per table, not globally.

You will also see a second, empty message right after each delete — a tombstone, with the same key and a null value. That is what tells Kafka’s log compaction to drop the key entirely. Consumers that do not care can set "tombstones.on.delete": "false".

Step 6 — Prove it survives a restart

This is the property that makes CDC worth the operational cost, so it is worth seeing directly. Stop Debezium, write while it is down, then bring it back:

docker compose stop debezium

docker compose exec postgres psql -U postgres -d app_db -c "
INSERT INTO orders (customer_id, amount, status) VALUES (3, 42.00, 'PENDING');
"

docker compose start debezium

The event for customer 3 shows up once Debezium reconnects. Postgres held the WAL for it, because the replication slot Debezium created is still there and the database refuses to discard WAL that a slot has not consumed.

That same mechanism is the main way CDC takes production down: a connector that stays offline makes Postgres accumulate WAL until the disk fills. Check for orphaned slots with:

docker compose exec postgres psql -U postgres -d app_db -c "
SELECT slot_name, active, pg_size_pretty(
  pg_wal_lsn_diff(pg_current_wal_lsn(), confirmed_flush_lsn)
) AS retained_wal FROM pg_replication_slots;
"

With Debezium stopped, the slot is still there and holding WAL:

 slot_name | active | retained_wal
-----------+--------+--------------
 debezium  | f      | 23 kB

23 kB is nothing; the point is that the number only goes up while active is f.

If you delete a connector for good, drop its slot too: SELECT pg_drop_replication_slot('debezium'); (debezium is the default slot name; override it with slot.name.)

Making the events usable

Two config additions turn the verbose default output into something you would actually feed to a downstream service. Update the connector in place with a PUT to its config endpoint:

curl -s -X PUT -H "Content-Type:application/json" \
  http://localhost:8083/connectors/orders-connector/config \
  -d '{
    "connector.class": "io.debezium.connector.postgresql.PostgresConnector",
    "tasks.max": "1",
    "plugin.name": "pgoutput",
    "database.hostname": "postgres",
    "database.port": "5432",
    "database.user": "postgres",
    "database.password": "postgrespassword",
    "database.dbname": "app_db",
    "topic.prefix": "pg_cdc",
    "table.include.list": "public.orders",
    "decimal.handling.mode": "string",
    "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",
    "transforms": "unwrap",
    "transforms.unwrap.type": "io.debezium.transforms.ExtractNewRecordState",
    "transforms.unwrap.add.fields": "op,ts_ms,lsn"
  }'

Note that PUT /config replaces the entire config, so you resend every key.

  • schemas.enable: false drops the schema block, which is about 80% of each message’s bytes. You must repeat key.converter / value.converter here even though the worker already sets them via KEY_CONVERTER / VALUE_CONVERTER. A per-connector *.converter.schemas.enable with no matching *.converter is silently ignored: the connector keeps reporting RUNNING and keeps emitting the schema block, with nothing in the log to say why.
  • ExtractNewRecordState flattens the envelope down to just the after row, with op/ts_ms/lsn kept as __op, __ts_ms, __lsn fields.

Insert another row and the consumer now shows:

{"id":6,"customer_id":5,"amount":"33.50","status":"PENDING","__op":"c","__ts_ms":1789915131545,"__lsn":27601936}

with the Kafka message key reduced to just {"id":6}.

That is the form most sinks want. Keep the full envelope only when you need the before image — auditing, or computing deltas.

Teardown

docker compose down -v

The -v matters: it removes the volumes, and with them the replication slot. Without it, the next up starts with a slot that has a stale LSN.

Where this goes next

The single-connector setup here is the whole idea; what production adds is mostly operational:

  • Schema changes. An ALTER TABLE ADD COLUMN flows through automatically; dropping or renaming a column breaks consumers that expect it. A schema registry with Avro instead of JSON turns that into a deploy-time failure rather than a 3am one.
  • Initial load of a large table. The blocking snapshot locks nothing but does hold a transaction open for its duration. For big tables use snapshot.mode: incremental, which chunks the read and interleaves it with live changes.
  • The outbox pattern. Streaming raw table rows couples consumers to your internal schema. Writing domain events to an outbox table in the same transaction and capturing that gives you CDC’s delivery guarantees with an API you control. Debezium ships an SMT for it.

The core thing to take away: the write-ahead log is already a perfectly ordered, durable, complete record of everything that happened to your data. CDC is just the decision to read it.