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
On this page
- Goal and setup
- Step 1: Download the connector
- Step 2: Start Kafka
- Step 3: Start PostgreSQL and prepare the source
- Step 4: Start the Kafka Connect worker
- Step 5: Register the connector
- Step 6: Read the snapshot events
- Step 7: Insert, update and delete
- Step 8: Full old values with REPLICA IDENTITY FULL
- Step 9: Stop the connector, change data, start again
- Check your understanding
- Apply it
- Review prompt
Lessons of Change Data Capture
- Three Ways to Detect That Data Changed Concept · 20 min
- Logical Decoding and the Write-Ahead Log Concept · 20 min
- Lab: PostgreSQL to Kafka with Debezium Lab · 30 min
- Worked Example: Applying Changes in Order with MERGE Worked example · 25 min
- Snapshots, Schema Changes and Slot Lag Concept · 20 min
- Check: CDC Failure Modes Knowledge check · 8 questions
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.2for 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.
curlandjq(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).
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 902. 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.
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)"debezium-connector-common-3.7.1.Final.jar
debezium-connector-postgres-3.7.1.Final.jar
postgresql-42.7.13.jar03. 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.
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.2until 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.txtLeaderId: 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.
-- 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;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"logical
dbz_publication|orders05. 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.
# 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-pluginsdocker 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)"'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.2The 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.
{
"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"
}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"orders-cdc
{"connector":"RUNNING","task":"RUNNING"}
debezium_orders|pgoutput|tOn 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.
#!/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'chmod +x events.sh
./events.sh0 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.50The 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:
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 .{
"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
INSERT INTO orders VALUES (4, 'dina', 'placed', 80.00);
UPDATE orders SET status = 'paid' WHERE id = 2;
DELETE FROM orders WHERE id = 3;docker exec -i cdc-pg psql -U postgres -d shop -X -q < changes.sql
sleep 3
./events.sh | tail -n +43 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
ALTER TABLE orders REPLICA IDENTITY FULL;
UPDATE orders SET amount = 22.00 WHERE id = 1;
DELETE FROM orders WHERE id = 4;docker exec -i cdc-pg psql -U postgres -d shop -X -q < identity-full.sql
sleep 3
./events.sh | tail -n +87 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.
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;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 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.00While 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
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.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.