Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Lab · 30 min · revision 2

Lab: PostgreSQL to Kafka with Debezium

Run PostgreSQL, a KRaft Kafka broker and a Kafka Connect worker with the Debezium PostgreSQL connector, register the connector over REST, and read real snapshot, create, update and delete events and tombstones from the topic, before and after changing the replica identity and restarting the connector.

Contentsand lesson path

What you will learn

  • Configure log-based CDC from PostgreSQL (logical replication slot and Debezium on Kafka Connect) and interpret create, update, delete and tombstone events.

Prerequisites: Messaging & Event Streaming

01. Goal and setup

In this lab you build the pipeline that the rest of this skill uses: changes to an orders table in PostgreSQL become events in a Kafka topic. Debezium is a set of open-source CDC connectors. Its PostgreSQL connector reads a logical replication slot with the pgoutput plugin, as in the previous lesson, and turns each change into an event. It runs inside Kafka Connect, the framework that ships with Kafka for moving data between Kafka and other systems. A Connect worker is a Java process that runs connectors, keeps their configuration and positions in Kafka topics, and offers a REST API.

The lab was run with the versions below. Debezium 3.7 is tested with Java 17 or later, Kafka Connect 3.1 or later and PostgreSQL 14 to 18.

  • apache/kafka:3.7.2 for the broker and the Connect worker. Java (Temurin 21.0.5) is inside the image, so you do not need Java on your machine.
  • postgres:17-alpine (PostgreSQL 17.11).
  • The Debezium PostgreSQL connector 3.7.1.Final, from Maven Central.
  • curl and jq (1.6) on your machine.

Kafka 4.x runs only in KRaft mode, without ZooKeeper. This lab already uses KRaft, so the same settings should work on 4.x images, although only 3.7.2 was tested here.

The three containers share one network namespace, like the containers of a Kubernetes pod: PostgreSQL and the worker join the Kafka container with --network container:cdc-kafka. Every service is then on localhost for the others, and the Kafka container publishes all three ports (Kafka 29092, PostgreSQL 25432, Connect REST 28083). PostgreSQL keeps its data in memory (--tmpfs).

Folder layout at the end of the lab
cdc-lab/
├── plugins/debezium-connector-postgres/   step 1: the connector jars
├── shop.sql                       step 3: table, CDC role, publication
├── connect-distributed.properties step 4: the Connect worker
├── orders-connector.json          step 5: the connector
├── events.sh                      step 6: prints the topic, one line per record
├── changes.sql                    step 7
├── identity-full.sql              step 8
└── while-down.sql                 step 9

02. Step 1: Download the connector

A Connect plugin is a folder of jar files. The worker looks for plugins in the folders listed in its plugin.path setting and loads each one separately, so plugin libraries cannot clash.

Terminal
mkdir cdc-lab && cd cdc-lab
mkdir plugins
curl -sSL https://repo1.maven.org/maven2/io/debezium/debezium-connector-postgres/\
3.7.1.Final/debezium-connector-postgres-3.7.1.Final-plugin.tar.gz | tar xz -C plugins
ls plugins/debezium-connector-postgres | grep -E "^(debezium-connector|postgresql)"
Expected output
debezium-connector-common-3.7.1.Final.jar
debezium-connector-postgres-3.7.1.Final.jar
postgresql-42.7.13.jar

03. Step 2: Start Kafka

A single node is both broker and controller. The KAFKA_ variables become broker settings. The advertised listener localhost:29092 works from your machine and from the other two containers, because they share this one's network.

Terminal
docker run -d --name cdc-kafka \
  -p 29092:29092 -p 25432:5432 -p 28083:8083 \
  -e KAFKA_NODE_ID=1 -e KAFKA_PROCESS_ROLES=broker,controller \
  -e KAFKA_LISTENERS=PLAINTEXT://:29092,CONTROLLER://:29093 \
  -e KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://localhost:29092 \
  -e KAFKA_CONTROLLER_LISTENER_NAMES=CONTROLLER \
  -e KAFKA_LISTENER_SECURITY_PROTOCOL_MAP=CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT \
  -e KAFKA_CONTROLLER_QUORUM_VOTERS=1@localhost:29093 \
  -e KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR=1 \
  -e KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR=1 \
  -e KAFKA_TRANSACTION_STATE_LOG_MIN_ISR=1 \
  -e KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS=0 \
  apache/kafka:3.7.2
Terminal
until docker exec cdc-kafka /opt/kafka/bin/kafka-metadata-quorum.sh \
    --bootstrap-server localhost:29092 describe --status > quorum.txt 2>&1; do
  sleep 2
done
grep -E '^(LeaderId|CurrentVoters)' quorum.txt
Expected output
LeaderId:               1
CurrentVoters:          [1]

04. Step 3: Start PostgreSQL and prepare the source

PostgreSQL starts with wal_level=logical (> /dev/null only hides the container id). The script creates the table with three orders that exist before CDC starts, a debezium role with only LOGIN, REPLICATION and SELECT on the table, and a publication. Because the table owner creates the publication, the connector needs no right to create one; publication.autocreate.mode=disabled in step 5 tells it to use this one.

SQL · shop.sql
-- The source table and three orders that exist before CDC starts.
CREATE TABLE orders (
  id       int PRIMARY KEY,
  customer text NOT NULL,
  status   text NOT NULL,
  amount   numeric(8,2) NOT NULL
);
INSERT INTO orders VALUES
  (1, 'ana',  'placed', 20.00),
  (2, 'ben',  'placed', 35.00),
  (3, 'chen', 'placed', 12.50);

-- A login for Debezium: it may stream (REPLICATION) and read the table, no more.
CREATE ROLE debezium WITH LOGIN REPLICATION PASSWORD 'dbz';
GRANT SELECT ON orders TO debezium;

-- pgoutput sends only the tables in a publication. The owner creates it here,
-- so the connector does not need the right to create publications.
CREATE PUBLICATION dbz_publication FOR TABLE orders;
Terminal
docker run -d --name cdc-pg --network container:cdc-kafka \
  --tmpfs /var/lib/postgresql/data -e POSTGRES_PASSWORD=postgres \
  -e POSTGRES_DB=shop postgres:17-alpine -c wal_level=logical > /dev/null
until docker exec cdc-pg pg_isready -h 127.0.0.1 -U postgres >/dev/null; do
  sleep 1
done
docker exec -i cdc-pg psql -U postgres -d shop -X -q -v ON_ERROR_STOP=1 < shop.sql
docker exec cdc-pg psql -U postgres -d shop -X -q -At \
  -c "SHOW wal_level" -c "SELECT pubname, tablename FROM pg_publication_tables"
Expected output
logical
dbz_publication|orders

05. Step 4: Start the Kafka Connect worker

In distributed mode a worker keeps everything in three Kafka topics: connector configurations, source offsets (for Debezium, the LSN it has reached) and status. Workers with the same group.id share connectors and take over from each other. The JSON converter with schemas.enable=false writes only the data, without a description of the fields in every message.

Properties · connect-distributed.properties
# Kafka Connect worker, distributed mode, one worker.
bootstrap.servers=localhost:29092
group.id=cdc-connect
listeners=http://0.0.0.0:8083
# Connect keeps connector configs, source offsets and status in these topics.
config.storage.topic=connect-configs
offset.storage.topic=connect-offsets
status.storage.topic=connect-status
config.storage.replication.factor=1
offset.storage.replication.factor=1
status.storage.replication.factor=1
# Plain JSON without an embedded schema, so events are easy to read.
key.converter=org.apache.kafka.connect.json.JsonConverter
value.converter=org.apache.kafka.connect.json.JsonConverter
key.converter.schemas.enable=false
value.converter.schemas.enable=false
# Where the worker looks for connector plugins (mounted from ./plugins).
plugin.path=/opt/connect-plugins
Terminal
docker run -d --name cdc-connect --network container:cdc-kafka \
  -v "$PWD/plugins:/opt/connect-plugins:ro" \
  -v "$PWD/connect-distributed.properties:/opt/cdc/worker.properties:ro" \
  apache/kafka:3.7.2 /opt/kafka/bin/connect-distributed.sh /opt/cdc/worker.properties \
  > /dev/null
until curl -sf localhost:28083/connector-plugins > /dev/null; do sleep 2; done
curl -s localhost:28083/connector-plugins | jq -r '.[] | "\(.class) \(.version)"'
Expected output
io.debezium.connector.postgresql.PostgresConnector 3.7.1.Final
org.apache.kafka.connect.mirror.MirrorCheckpointConnector 3.7.2
org.apache.kafka.connect.mirror.MirrorHeartbeatConnector 3.7.2
org.apache.kafka.connect.mirror.MirrorSourceConnector 3.7.2

The worker found the Debezium connector in plugin.path, next to the MirrorMaker connectors that ship with Kafka.

06. Step 5: Register the connector

The configuration names the database, the login, the plugin, the publication and the slot. Set plugin.name to pgoutput: Debezium's default, decoderbufs, must be compiled into the server and is not in this image. topic.prefix starts every topic name, so this table's events go to shop.public.orders. decimal.handling.mode=string writes numeric values as text such as "20.00" instead of encoded bytes. PUT .../config creates the connector or updates it, so it is safe to repeat.

JSON · orders-connector.json
{
  "connector.class": "io.debezium.connector.postgresql.PostgresConnector",
  "database.hostname": "localhost",
  "database.port": "5432",
  "database.user": "debezium",
  "database.password": "dbz",
  "database.dbname": "shop",
  "topic.prefix": "shop",
  "table.include.list": "public.orders",
  "plugin.name": "pgoutput",
  "publication.name": "dbz_publication",
  "publication.autocreate.mode": "disabled",
  "slot.name": "debezium_orders",
  "decimal.handling.mode": "string",
  "tasks.max": "1"
}
Terminal
curl -s -X PUT -H 'Content-Type: application/json' --data @orders-connector.json \
  localhost:28083/connectors/orders-cdc/config | jq -r '.name'
until curl -s localhost:28083/connectors/orders-cdc/status \
    | grep -q '"tasks":\[{"id":0,"state":"RUNNING"'; do sleep 2; done
curl -s localhost:28083/connectors/orders-cdc/status \
  | jq -c '{connector: .connector.state, task: .tasks[0].state}'
docker exec cdc-pg psql -U postgres -d shop -X -q -At \
  -c "SELECT slot_name, plugin, active FROM pg_replication_slots"
Expected output
orders-cdc
{"connector":"RUNNING","task":"RUNNING"}
debezium_orders|pgoutput|t

On its first start the connector created the slot debezium_orders and took an initial snapshot: it read the current rows in one consistent transaction and noted the LSN of that view. Then it started streaming from that LSN. The snapshot is needed because the WAL holds only recent changes, not the history that built the existing rows.

07. Step 6: Read the snapshot events

Every record has a key and a value. The key is the row's primary key, {"id":1}. Records with the same key go to the same partition, so the events of one row stay in order. The value is the change event envelope: before and after (the row before and after the change), op (r snapshot read, c create, u update, d delete), source (transaction id, LSN and more) and timestamps. events.sh prints one short line per record, without times or LSNs, so its output is repeatable.

Bash · events.sh
#!/usr/bin/env bash
# Print each record of the orders topic on one line: offset, key, op, before, after.
docker exec cdc-kafka /opt/kafka/bin/kafka-console-consumer.sh \
  --bootstrap-server localhost:29092 --topic shop.public.orders \
  --from-beginning --timeout-ms 5000 \
  --property print.offset=true --property print.key=true 2>/dev/null |
jq -Rr '
  def row: if . == null then "null" else [.[] | tostring] | join(",") end;
  split("\t") as [$off, $key, $val]
  | ($off | ltrimstr("Offset:")) as $o
  | ($val | fromjson) as $e
  | if $e == null then "\($o) key=\($key) TOMBSTONE (value is null)"
    else "\($o) key=\($key) op=\($e.op) snapshot=\($e.source.snapshot)"
       + " before=\($e.before | row) after=\($e.after | row)"
    end'
Terminal
chmod +x events.sh
./events.sh
Expected output
0 key={"id":1} op=r snapshot=first before=null after=1,ana,placed,20.00
1 key={"id":2} op=r snapshot=true before=null after=2,ben,placed,35.00
2 key={"id":3} op=r snapshot=last before=null after=3,chen,placed,12.50

The three existing rows arrived as op=r with before=null. The snapshot field marks the first and last snapshot record (first, last) and the ones in between (true); streamed changes say false. A consumer that handles only c, u and d would skip every row that existed before CDC started, so treat r as an upsert. One complete record looks like this:

Terminal
docker exec cdc-kafka /opt/kafka/bin/kafka-console-consumer.sh \
  --bootstrap-server localhost:29092 --topic shop.public.orders \
  --from-beginning --max-messages 1 2>/dev/null | jq .
Illustrative output (times, ids and LSNs will differ)
{
  "before": null,
  "after": {
    "id": 1,
    "customer": "ana",
    "status": "placed",
    "amount": "20.00"
  },
  "source": {
    "version": "3.7.1.Final",
    "connector": "postgresql",
    "name": "shop",
    "ts_ms": 1794844950711,
    "snapshot": "first",
    "db": "shop",
    "sequence": "[null,\"26570000\"]",
    "ts_us": 1794844950711257,
    "ts_ns": 1794844950711257000,
    "schema": "public",
    "table": "orders",
    "txId": 745,
    "lsn": 26570000,
    "xmin": null,
    "origin": null,
    "origin_lsn": null
  },
  "transaction": null,
  "op": "r",
  "ts_ms": 1794844950973,
  "ts_us": 1794844950973995,
  "ts_ns": 1794844950973995500
}

source.lsn is the LSN as a plain number: 26570000 here, which PostgreSQL writes as 0/1956D10. source.ts_ms is when the change happened in the database and the outer ts_ms is when Debezium processed it, so their difference is the capture delay.

08. Step 7: Insert, update and delete

SQL · changes.sql
INSERT INTO orders VALUES (4, 'dina', 'placed', 80.00);
UPDATE orders SET status = 'paid' WHERE id = 2;
DELETE FROM orders WHERE id = 3;
Terminal
docker exec -i cdc-pg psql -U postgres -d shop -X -q < changes.sql
sleep 3
./events.sh | tail -n +4
Expected output
3 key={"id":4} op=c snapshot=false before=null after=4,dina,placed,80.00
4 key={"id":2} op=u snapshot=false before=null after=2,ben,paid,35.00
5 key={"id":3} op=d snapshot=false before=3,,,0.00 after=null
6 key={"id":3} TOMBSTONE (value is null)

Four records for three changes. The insert is op=c with only an after. The update is op=u with before=null: under REPLICA IDENTITY DEFAULT the WAL holds no old values for an update that keeps the key. The delete is op=d with after=null, and its before has the real key, 3, but empty strings and 0.00 for the other columns. The WAL had only the key, and Debezium fills the other NOT NULL fields with empty values. Never read them as the deleted row's data.

The fourth record is a tombstone: the same key with a null value. It exists for log compaction, a topic setting that keeps only the latest record for each key. When that record is a tombstone, compaction can remove every record of the key, and later the tombstone too. Debezium writes tombstones by default (tombstones.on.delete=true), so consumers must expect records without a value.

09. Step 8: Full old values with REPLICA IDENTITY FULL

SQL · identity-full.sql
ALTER TABLE orders REPLICA IDENTITY FULL;
UPDATE orders SET amount = 22.00 WHERE id = 1;
DELETE FROM orders WHERE id = 4;
Terminal
docker exec -i cdc-pg psql -U postgres -d shop -X -q < identity-full.sql
sleep 3
./events.sh | tail -n +8
Expected output
7 key={"id":1} op=u snapshot=false before=1,ana,placed,20.00 after=1,ana,placed,22.00
8 key={"id":4} op=d snapshot=false before=4,dina,placed,80.00 after=null
9 key={"id":4} TOMBSTONE (value is null)

Now the update shows the amount going from 20.00 to 22.00, and the delete carries the real old row. The connector needed no change. The price is more WAL for every update and delete on this table.

10. Step 9: Stop the connector, change data, start again

Stop the worker as if for an upgrade, change two rows while it is down, look at the slot, and start the worker again.

SQL · while-down.sql
UPDATE orders SET status = 'shipped' WHERE id = 2;
INSERT INTO orders VALUES (5, 'eve', 'placed', 15.00);
SELECT slot_name, active,
       pg_wal_lsn_diff(pg_current_wal_lsn(), confirmed_flush_lsn) > 0 AS behind
  FROM pg_replication_slots;
Terminal
docker stop cdc-connect > /dev/null
docker exec -i cdc-pg psql -U postgres -d shop -X -q < while-down.sql
docker start cdc-connect > /dev/null
until curl -s localhost:28083/connectors/orders-cdc/status 2>/dev/null \
    | grep -q '"tasks":\[{"id":0,"state":"RUNNING"'; do sleep 2; done
sleep 3
./events.sh | tail -n +11
Expected output
    slot_name    | active | behind 
-----------------+--------+--------
 debezium_orders | f      | t
(1 row)

10 key={"id":2} op=u snapshot=false before=2,ben,paid,35.00 after=2,ben,shipped,35.00
11 key={"id":5} op=c snapshot=false before=null after=5,eve,placed,15.00

While the worker was down, the slot was inactive and behind, and PostgreSQL kept the WAL with both changes. On restart, the connector read its last offset from connect-offsets and continued from that LSN, without a new snapshot. A clean stop saves the latest offset first; after a crash, the connector restarts from the last saved offset and can send some events twice. The next lesson's apply step is built for that. Keep the three containers running for the next two lessons.

11. Check your understanding

Practice check · 3 questions

Reading Debezium events

Each question changes one detail of the lab. Pick the best answer.

Q1. With REPLICA IDENTITY DEFAULT, a consumer archives deleted orders by saving `before.customer` and `before.amount` from each `op=d` event. What does it store for order 3?
Q2. A new consumer of `shop.public.orders` handles `op` values `c`, `u` and `d` and ignores everything else. It starts from the beginning of the topic. What is wrong with its copy?
Q3. You set `tombstones.on.delete` to false and later enable log compaction on the topic. What remains in the topic for an order that was deleted long ago?
Practice only: not graded, not saved, not evidence.

12. Apply it

This lab is the first half of the skill practice. Extend it before the next lesson: add a second table, for example order_lines with a composite primary key, to the publication and to table.include.list, and check with events.sh (changing the topic name) what its keys look like. Then call GET localhost:28083/connectors/orders-cdc/offsets and write down the fields Debezium saves as its position. In the next lesson you apply the events of orders to a replica table with MERGE.

13. Review prompt

Without looking back, explain: what Kafka Connect stores in its three topics; why the connector takes an initial snapshot and how it knows where to start streaming; what op values r, c, u and d mean and what before contains for each under REPLICA IDENTITY DEFAULT; why Debezium writes a tombstone after a delete; and why a stopped connector loses nothing as long as its slot exists.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check