Add debezium-cdc module: Debezium 3.7.1 CDC from Postgres 18 to Kafka, Connect vs embedded engine vs outbox

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b5uEyg58znuchZ8C8i
This commit is contained in:
asmhatre
2026-11-29 13:36:01 +05:30
co-authored by Claude Sonnet 5.5
parent e2c42dc268
commit 95e75d0101
32 changed files with 1200 additions and 0 deletions
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env bash
# What "logical replication" gives Debezium: a replication slot, a publication, and a decoded stream of row changes.
set -eu
. "$(dirname "$0")/lib.sh"
OUT=output/01-logical-replication.txt
mkdir -p output
{
echo "### Server settings that make CDC possible"
sqlp -c "select split_part(version(), ',', 1) as postgres" -c "show wal_level" -c "show max_replication_slots" -c "show max_wal_senders"
echo
echo "### Before any connector: no slots, no publications"
sqlp -c "select count(*) as slots from pg_replication_slots" -c "select count(*) as publications from pg_publication"
echo
echo "### What logical decoding produces, read with the built-in test_decoding plugin on a throwaway slot"
sql -c "select pg_create_logical_replication_slot('peek', 'test_decoding')" >/dev/null
sql -c "insert into noise(payload) values ('hello')" -c "update noise set payload = 'hello again' where payload = 'hello'" -c "delete from noise where payload = 'hello again'"
sqlp -c "select data from pg_logical_slot_get_changes('peek', null, null)"
sql -c "select pg_drop_replication_slot('peek')" >/dev/null
echo
echo "### Register the Debezium connector (Kafka Connect, pgoutput) and wait for it"
register connect/orders-connector.json
wait_running orders-connector
echo "connector: $(connector_state orders-connector)"
echo
echo "### What the connector created inside Postgres"
sqlp -c "select slot_name, plugin, slot_type, active from pg_replication_slots"
sqlp -c "select pubname, puballtables, pubinsert, pubupdate, pubdelete, pubtruncate from pg_publication"
sqlp -c "select pubname, schemaname, tablename from pg_publication_tables"
} 2>&1 | tee "$OUT"
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env bash
# The change-event envelope: snapshot reads, then insert, update, delete (and the tombstone) with the default replica identity.
set -eu
. "$(dirname "$0")/lib.sh"
OUT=output/02-event-format.txt
mkdir -p output
{
echo "### Replica identity of orders (d = default, primary key only)"
sqlp -c "select relname, relreplident from pg_class where relname = 'orders'"
echo
echo "### Four statements, one transaction each"
sql -c "insert into orders values (3, 'meera', 'NEW', 999)"
sql -c "update orders set status = 'PAID' where id = 3"
sql -c "update orders set amount_cents = 1099 where id = 3"
sql -c "delete from orders where id = 3"
sleep 4
echo
echo "### Topic shop.public.orders in WAL order (p = partition). The two op=r records are the initial snapshot."
kafka_consume shop.public.orders 6000 | summarize --sort-lsn
echo
echo "### The raw insert envelope for id 3, exactly as Kafka stores it (value, pretty-printed with jq)"
kafka_consume shop.public.orders 6000 | awk -F'|' '$2 == "{\"id\":3}" && $3 ~ /"op":"c"/ {print $3}' | jq .
} 2>&1 | tee "$OUT"
+35
View File
@@ -0,0 +1,35 @@
#!/usr/bin/env bash
# Why an update has before=null, why a delete has placeholder values, and what REPLICA IDENTITY FULL changes.
set -eu
. "$(dirname "$0")/lib.sh"
OUT=output/03-replica-identity.txt
mkdir -p output
latest() { # latest <key-id> <n> : last n events for an order id, in WAL order
kafka_consume shop.public.orders 6000 | grep -F "|{\"id\":$1}|" | summarize --sort-lsn | tail -"$2"
}
{
sql -c "insert into orders values (4, 'dev', 'NEW', 500)"
echo "### REPLICA IDENTITY DEFAULT: update and delete of order 4"
sql -c "update orders set status = 'PAID' where id = 4"
sql -c "delete from orders where id = 4"
sleep 4
latest 4 4
echo
echo "### Switch the table to REPLICA IDENTITY FULL"
sql -c "alter table orders replica identity full"
sqlp -c "select relname, relreplident from pg_class where relname = 'orders'"
sql -c "insert into orders values (5, 'kiran', 'NEW', 700)"
sql -c "update orders set status = 'PAID' where id = 5"
sql -c "delete from orders where id = 5"
sleep 4
echo "### Same three statements for order 5"
latest 5 4
echo
echo "### Add a column while the connector is running; the next event carries it, no restart needed"
sql -c "alter table orders add column note text"
sql -c "update orders set note = 'gift wrap' where id = 1"
sleep 4
latest 1 1
} 2>&1 | tee "$OUT"
+58
View File
@@ -0,0 +1,58 @@
#!/usr/bin/env bash
# What ordering does CDC to Kafka really guarantee? Per key, yes. Across keys, no. Inside one transaction, only in the WAL.
set -eu
. "$(dirname "$0")/lib.sh"
OUT=output/04-ordering.txt
mkdir -p output
{
echo "### Topic layout"
docker compose exec -T kafka $KT/kafka-topics.sh --bootstrap-server kafka:19092 --describe --topic shop.public.orders 2>/dev/null | head -1 | tr '\t' ' '
echo
echo "### Write: 6 orders (ids 10..15), then 4 rounds of single-row updates, then one transaction that updates 10, then 12, then 13"
for id in 10 11 12 13 14 15; do sql -c "insert into orders(id, customer, status, amount_cents) values ($id, 'c$id', 'NEW', 100)"; done
for round in 1 2 3 4; do
for id in 10 11 12 13 14 15; do sql -c "update orders set status = 'R$round' where id = $id"; done
done
sql <<'SQL'
begin;
update orders set status = 'TX-A' where id = 10;
update orders set status = 'TX-B' where id = 12;
update orders set status = 'TX-C' where id = 13;
commit;
SQL
sleep 5
kafka_consume shop.public.orders 8000 | grep -E '\|\{"id":1[0-5]\}\|' > /tmp/cdc04.txt
python3 -I - <<'PY'
import json, collections
by_part = collections.OrderedDict((p, []) for p in "012")
for line in open("/tmp/cdc04.txt"):
part, key, value = line.rstrip("\n").split("|", 2)
if value == "null": continue
v = json.loads(value)
by_part[part].append((json.loads(key)["id"], v["op"], v["source"]["lsn"], v["source"]["txId"], v["after"]["status"] if v["after"] else None))
print("### Which partition each key landed on, and whether its events stayed in WAL order inside that partition")
keys = collections.defaultdict(list)
for part, evs in by_part.items():
for e in evs: keys[e[0]].append((part, e[2]))
for k in sorted(keys):
parts = {p for p, _ in keys[k]}
lsns = [l for _, l in keys[k]]
print(f"key {k}: partitions={sorted(parts)} events={len(lsns)} lsn strictly increasing in offset order={lsns == sorted(lsns) and len(set(lsns)) == len(lsns)}")
print()
print("### Reading partition 0, then 1, then 2 (what the broker stores): is the LSN sequence globally increasing?")
seq = [e[2] for evs in by_part.values() for e in evs]
print("lsn sequence head:", seq[:8])
print("globally increasing across partitions:", seq == sorted(seq))
print("events per partition:", {p: len(e) for p, e in by_part.items()})
print()
print("### The multi-statement transaction (statuses TX-A, TX-B, TX-C): one txId, increasing lsn, three different keys")
tx_rows = [(lsn, st, k, part, tx) for part, evs in by_part.items() for k, op, lsn, tx, st in evs if st and st.startswith("TX-")]
for lsn, st, k, part, tx in sorted(tx_rows): # sorted by LSN: the order Postgres committed the statements in
print(f"status={st} key={k} partition={part} lsn={lsn} txId={tx}")
PY
} 2>&1 | tee "$OUT"
+46
View File
@@ -0,0 +1,46 @@
#!/usr/bin/env bash
# The same connector technology, pointed at an outbox table instead of the business table, with the EventRouter SMT.
set -eu
. "$(dirname "$0")/lib.sh"
OUT=output/05-outbox.txt
mkdir -p output
{
echo "### Register the outbox connector (EventRouter single message transform)"
register connect/outbox-connector.json
wait_running outbox-connector
echo
echo "### One transaction writes the business row AND the outbox row"
sql <<'SQL'
begin;
insert into orders(id, customer, status, amount_cents) values (20, 'zoya', 'NEW', 4200);
insert into outbox(id, aggregatetype, aggregateid, type, payload)
values ('00000000-0000-0000-0000-000000000020', 'Order', '20', 'OrderCreated',
'{"orderId":20,"customer":"zoya","amountCents":4200}');
commit;
SQL
echo
echo "### A second transaction inserts an outbox row and deletes it before committing (the 'clean up as you go' habit)"
sql <<'SQL'
begin;
insert into outbox(id, aggregatetype, aggregateid, type, payload)
values ('00000000-0000-0000-0000-000000000021', 'Order', '21', 'OrderCreated',
'{"orderId":21,"customer":"omkar","amountCents":100}');
delete from outbox where id = '00000000-0000-0000-0000-000000000021';
commit;
SQL
echo "outbox rows left in the table: $(sql -t -A -c 'select count(*) from outbox')"
sleep 5
echo
echo "### Topic outbox.event.Order (headers | key | value; the four __debezium.context.* headers are trimmed with sed)"
docker compose exec -T kafka $KT/kafka-console-consumer.sh --bootstrap-server kafka:19092 --topic outbox.event.Order \
--from-beginning --timeout-ms 8000 --formatter-property print.headers=true --formatter-property print.key=true \
--formatter-property key.separator=' | ' --formatter-property headers.separator=',' --formatter-property headers.deserializer=org.apache.kafka.common.serialization.StringDeserializer 2>/dev/null \
| sed -e 's/__debezium\.context\.[A-Za-z]*:[^,]*,//g'
echo
echo "### Topics that exist for this connector"
docker compose exec -T kafka $KT/kafka-topics.sh --bootstrap-server kafka:19092 --list 2>/dev/null | grep -E '^(outbox|shopoutbox)' || true
} 2>&1 | tee "$OUT"
+46
View File
@@ -0,0 +1,46 @@
#!/usr/bin/env bash
# A replication slot makes Postgres keep WAL until the consumer confirms it. Three ways that goes wrong, and the fixes.
set -eu
. "$(dirname "$0")/lib.sh"
OUT=output/06-wal-retention.txt
mkdir -p output
slots() {
sqlp -c "select slot_name, active,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) as wal_kept_for_slot,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), confirmed_flush_lsn)) as unconfirmed
from pg_replication_slots order by slot_name"
}
burst() { sql -c "insert into noise(payload) select repeat('x', 200) from generate_series(1, 100000)"; }
{
echo "### Safety valve: the default cap on WAL a slot may pin (-1 = unlimited)"
sqlp -c "show max_slot_wal_keep_size"
echo
echo "### Baseline: both connectors running, nothing unusual written"
slots
echo
echo "### Failure 1: healthy connectors, but all the writes go to a table nobody captures (100,000 rows, about 33 MB of WAL)"
burst
sleep 15
slots
echo
echo "### Failure 2: delete the outbox connector. Kafka Connect does not drop its slot."
curl -s -X DELETE $CONNECT/connectors/outbox-connector -o /dev/null
sleep 5
burst
slots
echo
echo "### Fix for 2: drop the orphaned slot by hand"
sql -c "select pg_drop_replication_slot('connect_outbox')" >/dev/null
slots
echo
echo "### Fix for 1: heartbeat.interval.ms plus a heartbeat.action.query that writes to a captured table (public.heartbeat)"
curl -s -X PUT -H 'Content-Type: application/json' $CONNECT/connectors/orders-connector/config \
--data "$(jq '.config + {"table.include.list":"public.orders,public.heartbeat","heartbeat.interval.ms":"5000","heartbeat.action.query":"INSERT INTO heartbeat (id, ts) VALUES (1, now()) ON CONFLICT (id) DO UPDATE SET ts = EXCLUDED.ts"}' connect/orders-connector.json)" -o /dev/null
sleep 60
slots
} 2>&1 | tee "$OUT"
+77
View File
@@ -0,0 +1,77 @@
#!/usr/bin/env bash
# The embedded engine: same connector, same envelope, running inside the Spring Boot JVM. Then the at-least-once proof.
set -eu
. "$(dirname "$0")/lib.sh"
OUT=output/07-embedded.txt
mkdir -p output target
JAR=target/debezium-cdc-1.0.jar
[ -f "$JAR" ] || mvn -B -q package -DskipTests >/dev/null 2>&1
rm -f target/embedded-offsets.dat target/run1.log target/run2.log
start_app() { # start_app <logfile> -> sets APP_PID
java -jar "$JAR" --cdc.embedded.enabled=true --cdc.listener.enabled=true \
--cdc.listener.topic=embedded.public.orders --cdc.embedded.show-raw=true \
> "$1" 2>&1 &
APP_PID=$!
}
wait_for() { # wait_for <logfile> <regex> <seconds>
for i in $(seq 1 "$3"); do grep -q -E "$2" "$1" 2>/dev/null && return 0; sleep 1; done
echo "timed out waiting for $2"; return 1
}
status_lines() { # one line per update of order 1 to A0..A2: its LSN and the status it set
grep -E '^EMBEDDED op=u key=\{"id":1\}' "$1" | sed -E 's/^EMBEDDED op=u key=\{"id":1\} lsn=([0-9]+) .*after=.*"status":"(A[0-9])".*/lsn=\1 status set to \2/' | grep 'status set to A'
}
events() { grep -E '^(EMBEDDED|LISTENER) ' "$1" | sed -e 's/ txId=[0-9]*//'; }
{
echo "### Start the Spring Boot app with the embedded engine (slot embedded_orders, topic prefix embedded)"
start_app target/run1.log
wait_for target/run1.log '^EMBEDDED op=r' 90
sleep 8
echo "snapshot rows delivered by the engine: $(grep -c '^EMBEDDED op=r' target/run1.log)"
sqlp -c "select slot_name, plugin, active from pg_replication_slots where slot_name = 'embedded_orders'"
echo
echo "### Insert, update and delete order 30, and the app's own view of them (EMBEDDED = engine callback, LISTENER = @KafkaListener on embedded.public.orders)"
sql -c "insert into orders(id, customer, status, amount_cents) values (30, 'tara', 'NEW', 300)"
sql -c "update orders set status = 'PAID' where id = 30"
sql -c "delete from orders where id = 30"
wait_for target/run1.log 'LISTENER .*TOMBSTONE' 30
sleep 2
events target/run1.log | grep -E 'key=\{"id":30\}' | cut -c1-230
echo
echo "### Same UPDATE, seen by Kafka Connect (topic shop.public.orders) and by the embedded engine (topic embedded.public.orders): what differs?"
sql -c "update orders set status = 'SHIPPED' where id = 2"
sleep 6
norm='del(.ts_ms,.ts_us,.ts_ns,.source.ts_ms,.source.ts_us,.source.ts_ns) | .source'
kafka_consume shop.public.orders 8000 | awk -F'|' '$2 == "{\"id\":2}" && $3 ~ /SHIPPED/ {print $3}' | jq -S "$norm" > /tmp/connect-src.json
grep '^EMBEDDED-RAW' target/run1.log | sed 's/^EMBEDDED-RAW //' | grep SHIPPED | jq -S "$norm" > /tmp/embedded-src.json
diff /tmp/connect-src.json /tmp/embedded-src.json || true
echo
echo "### At-least-once: offsets are flushed every 60 s (Debezium's default). Wait 65 s, then three updates, then kill -9 the JVM"
sleep 65
sql -c "update orders set status = 'A0' where id = 1"
sleep 2
sql -c "update orders set status = 'A1' where id = 1"
sql -c "update orders set status = 'A2' where id = 1"
wait_for target/run1.log 'LISTENER .*status":"A2"' 30
kill -9 "$APP_PID"; wait "$APP_PID" 2>/dev/null || true
echo "killed. Events the first run delivered for key id=1 after the wait:"
status_lines target/run1.log
echo
echo "### Restart the app (same offset file, same slot)"
start_app target/run2.log
wait_for target/run2.log '^EMBEDDED ' 90
sleep 10
echo "EMBEDDED events in the second run (anything here is a redelivery):"
status_lines target/run2.log
kill "$APP_PID"; wait "$APP_PID" 2>/dev/null || true
echo
echo "### What a downstream consumer sees on embedded.public.orders: records per (key, lsn) for the three A updates"
kafka_consume embedded.public.orders 8000 | summarize | grep -E 'after=\{"id":1,.*"status":"A[012]"' \
| sed -E 's/.* lsn=([0-9]+) .*"status":"(A[012])".*/status=\2 lsn=\1/' | sort | uniq -c
} 2>&1 | tee "$OUT"
+27
View File
@@ -0,0 +1,27 @@
# Sourced by every scenario script. Needs Docker, the compose stack from ../docker-compose.yml, curl, python3.
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT"
export JAVA_HOME="${JDK25_HOME:-/tmp/tools/jdk-25.0.5.1+2}"
export PATH="$JAVA_HOME/bin:$PATH"
CONNECT=http://localhost:8083
KT=/opt/kafka/bin
sql() { docker compose exec -T postgres psql -U demo -d shop -X -q -v ON_ERROR_STOP=1 "$@"; }
sqlp() { sql -P pager=off "$@"; }
# kafka_consume <topic> [idle-timeout-ms] -> "partition|key|value" lines
kafka_consume() {
docker compose exec -T kafka $KT/kafka-console-consumer.sh --bootstrap-server kafka:19092 --topic "$1" \
--from-beginning --timeout-ms "${2:-6000}" \
--formatter-property print.partition=true --formatter-property print.key=true \
--formatter-property key.separator='|' --formatter-property print.headers=false 2>/dev/null \
| sed -e 's/^Partition:\([0-9]*\)|/\1|/'
}
summarize() { python3 -I "$ROOT/scripts/summarize.py" "$@"; }
register() { # register <connector-json-file>
curl -s -o /dev/null -w "register %{http_code}\n" -X POST -H 'Content-Type: application/json' --data @"$1" $CONNECT/connectors
}
connector_state() { curl -s $CONNECT/connectors/"$1"/status | python3 -I -c 'import json,sys; d=json.load(sys.stdin); print(d["connector"]["state"], [t["state"] for t in d["tasks"]])'; }
wait_running() { for i in $(seq 1 60); do s=$(connector_state "$1" 2>/dev/null || true); case "$s" in "RUNNING ['RUNNING']") return 0;; esac; sleep 1; done; echo "connector $1 not running: $s"; return 1; }
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env bash
# Rebuilds the whole environment from nothing and regenerates every file in output/. Takes about 12 minutes.
# Needs: JDK 25, Maven, Docker (with the compose plugin), curl, jq, python3.
set -eu
cd "$(dirname "$0")/.."
mkdir -p output
# JDK 25 is required (java.version=25). Set JDK25_HOME to one; the default below is this sandbox's.
export JAVA_HOME="${JDK25_HOME:-/tmp/tools/jdk-25.0.5.1+2}"
export PATH="$JAVA_HOME/bin:$PATH"
[ "${SKIP_UP:-}" = 1 ] || ./scripts/up.sh # SKIP_UP=1 reuses a stack that was just created by up.sh
mvn -B -q package # compiles, runs ChangeEventTest, builds the jar the embedded scenario starts
for s in 01-logical-replication 02-event-format 03-replica-identity 04-ordering 05-outbox 06-wal-retention 07-embedded; do
echo "== $s"
./scripts/$s.sh > /dev/null
done
# Machine-specific values do not belong in committed output.
ls -1 output
+29
View File
@@ -0,0 +1,29 @@
"""Reads 'partition|key|value' lines from stdin, prints one compact line per Debezium event.
--sort-lsn : print in WAL order instead of Kafka arrival order. Partitions are read in no particular
order, so this is for display only; a tombstone takes the LSN of the delete before it.
"""
import json, sys
def short(o):
return "null" if o is None else json.dumps(o, separators=(",", ":"))
rows, last_lsn = [], {}
for line in sys.stdin:
line = line.rstrip("\n")
if not line.strip():
continue
part, key, value = line.split("|", 2)
if value == "null":
lsn = last_lsn.get(part, 0)
rows.append((lsn, 1, f"p={part} key={key} TOMBSTONE (null value)"))
continue
v = json.loads(value)
s = v["source"]
last_lsn[part] = s["lsn"]
rows.append((s["lsn"], 0, f"p={part} op={v['op']} key={key} lsn={s['lsn']} txId={s['txId']} snapshot={s['snapshot']} before={short(v['before'])} after={short(v['after'])}"))
if "--sort-lsn" in sys.argv:
rows.sort(key=lambda r: (r[0], r[1]))
for _, _, text in rows:
print(text)
+13
View File
@@ -0,0 +1,13 @@
#!/usr/bin/env bash
# Fresh stack: Postgres 18 + Kafka 4.4 + Kafka Connect (Debezium 3.7.1). Start services one at a time and wait,
# because starting Connect before Kafka is ready only produces noisy restarts.
set -eu
. "$(dirname "$0")/lib.sh"
docker compose down -v >/dev/null 2>&1 || true
docker compose up -d postgres >/dev/null 2>&1
for i in $(seq 1 60); do sql -c 'select 1' >/dev/null 2>&1 && break; sleep 1; done
docker compose up -d kafka >/dev/null 2>&1
for i in $(seq 1 90); do docker compose exec -T kafka $KT/kafka-topics.sh --bootstrap-server kafka:19092 --list >/dev/null 2>&1 && break; sleep 1; done
docker compose up -d connect >/dev/null 2>&1
for i in $(seq 1 180); do curl -s -f $CONNECT/ >/dev/null 2>&1 && break; sleep 2; done
echo "stack is up"