diff --git a/README.md b/README.md index d027f0d..70fdbe5 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,7 @@ directly under `output/` instead, with the equivalent depth in the article's own | [`kafka-streams/`](kafka-streams/README.md) | Kafka Streams with Spring Boot 4: Real-Time Fraud Detection with Vector Similarity | A fraud topology tested entirely under `TopologyTestDriver`: cosine-similarity scoring, a 5-minute windowed count that alerts exactly once, and a KTable blocklist join with a tombstone, plus the Spring wiring that needs no broker to load | | [`amqp10/`](amqp10/README.md) | AMQP 1.0 in Spring Boot 4.2 with RabbitMQ 4 | The generic AMQP 1.0 starter and RabbitMQ's own AMQP 1.0 client against a real RabbitMQ 4.4 broker: address forms and what a broker refusal looks like, a queue shared with AMQP 0-9-1, and a listener that kills its own consumer under Boot's defaults. Needs Docker (Testcontainers). Output lives in `output/`, no `docs/` folder | | [`cloud-stream/`](cloud-stream/README.md) | Spring Cloud Stream on Boot 4: Functional Kafka and RabbitMQ Binders | One set of `Supplier`/`Function`/`Consumer` beans on Kafka and on RabbitMQ: partitioning (and how each binder really does it), dead-letter queues, the test binder, and the wiring mistakes with their real error messages. Needs Docker (Testcontainers). Output lives in `output/`, no `docs/` folder | +| [`debezium-cdc/`](debezium-cdc/README.md) | Debezium CDC with Spring Boot: Stream Postgres Changes to Kafka (and When to Prefer the Outbox) | Debezium 3.7.1 against Postgres 18 and Kafka 4.4, run two ways: Kafka Connect and the embedded engine inside a Spring Boot 4.2 app. Event envelope and replica identity, per-key ordering, redelivery after `kill -9`, WAL pinned by a quiet or orphaned slot, and the outbox `EventRouter`. Needs Docker. Output lives in `output/`, no `docs/` folder | The brokers make an instructive set. Kafka's consumer holds an offset and the broker remembers nothing about individual records; RabbitMQ's broker owns the message until it is acknowledged and diff --git a/debezium-cdc/.gitignore b/debezium-cdc/.gitignore new file mode 100644 index 0000000..b1c13f4 --- /dev/null +++ b/debezium-cdc/.gitignore @@ -0,0 +1,2 @@ +target/ +*.log diff --git a/debezium-cdc/README.md b/debezium-cdc/README.md new file mode 100644 index 0000000..b397143 --- /dev/null +++ b/debezium-cdc/README.md @@ -0,0 +1,62 @@ +# debezium-cdc + +Companion code for the ankurm.com post *Debezium CDC with Spring Boot: Stream Postgres Changes to Kafka (and When to Prefer the Outbox)*. + +One Postgres 18 database, one Kafka 4.4 broker, and Debezium running two ways against the same tables: + +* **Kafka Connect** with the Debezium Postgres connector (`connect/*.json`, registered over REST). +* **The embedded engine** inside a Spring Boot app (`EmbeddedDebezium.java`), forwarding to Kafka with `KafkaTemplate`. + +No `docs/` folder: the explanations live in the post, every transcript lives in `output/`. + +## Versions (all read from Maven Central or the image, not from announcements) + +| Part | Version | +|---|---| +| JDK | Temurin 25.0.5.1 | +| Spring Boot | 4.2.0 (Spring for Apache Kafka 4.2.0, kafka-clients 4.4.0) | +| Debezium | 3.7.1.Final (engine and the `quay.io/debezium/connect` image; 3.8.0.Alpha2 exists but is not GA) | +| Postgres | 18.7 (`quay.io/debezium/postgres:18`, `wal_level=logical` preset) | +| Kafka broker | `apache/kafka:4.4.0`, KRaft, 3 partitions per auto-created topic | +| Kafka Connect runtime inside the Debezium image | 4.3.1 | + +## Run it + +```bash +export JDK25_HOME=/path/to/jdk-25 # defaults to this author's sandbox path +./scripts/run-all.sh # fresh stack, builds, runs every scenario, rewrites output/ (about 12 minutes) +``` + +or step by step: `./scripts/up.sh`, then `./scripts/01-logical-replication.sh` and so on in order. The scenarios +build on each other (01 registers the connector 02 to 04 read from). + +## Layout + +| Path | What it is | +|---|---| +| `docker-compose.yml` | Postgres, Kafka, Kafka Connect | +| `sql/init.sql` | `orders`, `outbox`, `noise`, `heartbeat` tables and two seed rows | +| `connect/orders-connector.json` | Connector for the business table | +| `connect/outbox-connector.json` | Connector for the outbox table with the `EventRouter` transform | +| `src/main/java/com/ankurm/cdc/EmbeddedDebezium.java` | The embedded engine as a Spring `SmartLifecycle` bean | +| `src/main/java/com/ankurm/cdc/OrderChangeListener.java` | A plain `@KafkaListener` that handles tombstones and duplicates | +| `src/main/java/com/ankurm/cdc/ChangeEvent.java` | Reads the envelope (same for embedded and Connect) | +| `src/test/java/com/ankurm/cdc/ChangeEventTest.java` | Pins the envelope parsing, no infrastructure needed | + +## Output index + +| File | Shows | +|---|---| +| `output/01-logical-replication.txt` | Server settings, a `test_decoding` peek at the raw logical stream, the slot and publication the connector creates | +| `output/02-event-format.txt` | Snapshot, insert, update, delete and tombstone envelopes under the default replica identity | +| `output/03-replica-identity.txt` | `REPLICA IDENTITY FULL`, and an `ALTER TABLE ADD COLUMN` on a live connector | +| `output/04-ordering.txt` | Per-key order, no global order, one transaction spread across partitions | +| `output/05-outbox.txt` | `EventRouter` output, including an outbox row inserted and deleted in one transaction | +| `output/06-wal-retention.txt` | WAL pinned by a quiet slot, by an orphaned slot, and the heartbeat fix | +| `output/07-embedded.txt` | The embedded engine, a diff against the Connect event, and a `kill -9` redelivery | + +## Things this module does not do + +* No schema registry or Avro: JSON without the schema wrapper, so the transcripts are readable. +* No exactly-once claim anywhere: the redelivery in `07` is the point. +* Nothing here is hardened for production (plaintext passwords in compose, one broker, replication factor 1). diff --git a/debezium-cdc/connect/orders-connector.json b/debezium-cdc/connect/orders-connector.json new file mode 100644 index 0000000..52d26e5 --- /dev/null +++ b/debezium-cdc/connect/orders-connector.json @@ -0,0 +1,21 @@ +{ + "name": "orders-connector", + "config": { + "connector.class": "io.debezium.connector.postgresql.PostgresConnector", + "database.hostname": "postgres", + "database.port": "5432", + "database.user": "demo", + "database.password": "demo", + "database.dbname": "shop", + "topic.prefix": "shop", + "table.include.list": "public.orders", + "plugin.name": "pgoutput", + "slot.name": "connect_orders", + "publication.name": "connect_orders_pub", + "publication.autocreate.mode": "filtered", + "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" + } +} diff --git a/debezium-cdc/connect/outbox-connector.json b/debezium-cdc/connect/outbox-connector.json new file mode 100644 index 0000000..c091d1e --- /dev/null +++ b/debezium-cdc/connect/outbox-connector.json @@ -0,0 +1,31 @@ +{ + "name": "outbox-connector", + "config": { + "connector.class": "io.debezium.connector.postgresql.PostgresConnector", + "database.hostname": "postgres", + "database.port": "5432", + "database.user": "demo", + "database.password": "demo", + "database.dbname": "shop", + "topic.prefix": "shopoutbox", + "table.include.list": "public.outbox", + "plugin.name": "pgoutput", + "slot.name": "connect_outbox", + "publication.name": "connect_outbox_pub", + "publication.autocreate.mode": "filtered", + "tombstones.on.delete": "false", + "key.converter": "org.apache.kafka.connect.storage.StringConverter", + "value.converter": "org.apache.kafka.connect.json.JsonConverter", + "value.converter.schemas.enable": "false", + "transforms": "outbox", + "transforms.outbox.type": "io.debezium.transforms.outbox.EventRouter", + "transforms.outbox.table.field.event.id": "id", + "transforms.outbox.table.field.event.key": "aggregateid", + "transforms.outbox.table.field.event.type": "type", + "transforms.outbox.table.field.event.payload": "payload", + "transforms.outbox.route.by.field": "aggregatetype", + "transforms.outbox.route.topic.replacement": "outbox.event.${routedByValue}", + "transforms.outbox.table.expand.json.payload": "true", + "transforms.outbox.table.fields.additional.placement": "type:header:eventType" + } +} diff --git a/debezium-cdc/docker-compose.yml b/debezium-cdc/docker-compose.yml new file mode 100644 index 0000000..1d9d1a1 --- /dev/null +++ b/debezium-cdc/docker-compose.yml @@ -0,0 +1,42 @@ +# Postgres 18 (wal_level=logical already set by the Debezium image), Kafka 4.4 in KRaft mode, Kafka Connect with Debezium 3.7.1. +services: + postgres: + image: quay.io/debezium/postgres:18 + environment: + POSTGRES_USER: demo + POSTGRES_PASSWORD: demo + POSTGRES_DB: shop + ports: ["5432:5432"] + volumes: + - ./sql/init.sql:/docker-entrypoint-initdb.d/init.sql:ro + kafka: + image: apache/kafka:4.4.0 + ports: ["9092:9092"] + environment: + KAFKA_NODE_ID: 1 + KAFKA_PROCESS_ROLES: broker,controller + KAFKA_LISTENERS: INTERNAL://:19092,EXTERNAL://:9092,CONTROLLER://:9093 + KAFKA_ADVERTISED_LISTENERS: INTERNAL://kafka:19092,EXTERNAL://localhost:9092 + KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INTERNAL:PLAINTEXT,EXTERNAL:PLAINTEXT,CONTROLLER:PLAINTEXT + KAFKA_INTER_BROKER_LISTENER_NAME: INTERNAL + KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER + KAFKA_CONTROLLER_QUORUM_VOTERS: 1@kafka:9093 + KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 + KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1 + KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1 + KAFKA_NUM_PARTITIONS: 3 + connect: + image: quay.io/debezium/connect:3.7.1.Final + depends_on: [kafka, postgres] + ports: ["8083:8083"] + environment: + BOOTSTRAP_SERVERS: kafka:19092 + GROUP_ID: cdc-connect + CONFIG_STORAGE_TOPIC: connect_configs + OFFSET_STORAGE_TOPIC: connect_offsets + STATUS_STORAGE_TOPIC: connect_statuses + CONFIG_STORAGE_REPLICATION_FACTOR: 1 + OFFSET_STORAGE_REPLICATION_FACTOR: 1 + STATUS_STORAGE_REPLICATION_FACTOR: 1 + # Kafka Connect's default is 60000. Shortened so the WAL-retention demo does not need minute-long waits. + OFFSET_FLUSH_INTERVAL_MS: 10000 diff --git a/debezium-cdc/output/01-logical-replication.txt b/debezium-cdc/output/01-logical-replication.txt new file mode 100644 index 0000000..fa1602c --- /dev/null +++ b/debezium-cdc/output/01-logical-replication.txt @@ -0,0 +1,69 @@ +### Server settings that make CDC possible + postgres +----------------------------------------------------------------- + PostgreSQL 18.7 (Debian 18.7-1.pgdg12+5) on x86_64-pc-linux-gnu +(1 row) + + wal_level +----------- + logical +(1 row) + + max_replication_slots +----------------------- + 4 +(1 row) + + max_wal_senders +----------------- + 4 +(1 row) + + +### Before any connector: no slots, no publications + slots +------- + 0 +(1 row) + + publications +-------------- + 0 +(1 row) + + +### What logical decoding produces, read with the built-in test_decoding plugin on a throwaway slot + data +---------------------------------------------------------------------- + BEGIN 770 + table public.noise: INSERT: id[bigint]:1 payload[text]:'hello' + COMMIT 770 + BEGIN 771 + table public.noise: UPDATE: id[bigint]:1 payload[text]:'hello again' + COMMIT 771 + BEGIN 772 + table public.noise: DELETE: id[bigint]:1 + COMMIT 772 +(9 rows) + + +### Register the Debezium connector (Kafka Connect, pgoutput) and wait for it +register 201 +connector: RUNNING ['RUNNING'] + +### What the connector created inside Postgres + slot_name | plugin | slot_type | active +----------------+----------+-----------+-------- + connect_orders | pgoutput | logical | t +(1 row) + + pubname | puballtables | pubinsert | pubupdate | pubdelete | pubtruncate +--------------------+--------------+-----------+-----------+-----------+------------- + connect_orders_pub | f | t | t | t | t +(1 row) + + pubname | schemaname | tablename +--------------------+------------+----------- + connect_orders_pub | public | orders +(1 row) + diff --git a/debezium-cdc/output/02-event-format.txt b/debezium-cdc/output/02-event-format.txt new file mode 100644 index 0000000..a8ae92e --- /dev/null +++ b/debezium-cdc/output/02-event-format.txt @@ -0,0 +1,51 @@ +### Replica identity of orders (d = default, primary key only) + relname | relreplident +---------+-------------- + orders | d +(1 row) + + +### Four statements, one transaction each + +### Topic shop.public.orders in WAL order (p = partition). The two op=r records are the initial snapshot. +p=1 op=r key={"id":2} lsn=30425656 txId=774 snapshot=last before=null after={"id":2,"customer":"ravi","status":"NEW","amount_cents":2500} +p=0 op=r key={"id":1} lsn=30425656 txId=774 snapshot=first before=null after={"id":1,"customer":"asha","status":"NEW","amount_cents":1500} +p=0 op=c key={"id":3} lsn=30425880 txId=775 snapshot=false before=null after={"id":3,"customer":"meera","status":"NEW","amount_cents":999} +p=0 op=u key={"id":3} lsn=30426168 txId=776 snapshot=false before=null after={"id":3,"customer":"meera","status":"PAID","amount_cents":999} +p=0 op=u key={"id":3} lsn=30426312 txId=777 snapshot=false before=null after={"id":3,"customer":"meera","status":"PAID","amount_cents":1099} +p=0 op=d key={"id":3} lsn=30426456 txId=778 snapshot=false before={"id":3,"customer":"","status":"","amount_cents":0} after=null +p=0 key={"id":3} TOMBSTONE (null value) + +### The raw insert envelope for id 3, exactly as Kafka stores it (value, pretty-printed with jq) +{ + "before": null, + "after": { + "id": 3, + "customer": "meera", + "status": "NEW", + "amount_cents": 999 + }, + "source": { + "version": "3.7.1.Final", + "connector": "postgresql", + "name": "shop", + "ts_ms": 1795939109105, + "snapshot": "false", + "db": "shop", + "sequence": "[null,\"30425880\"]", + "ts_us": 1795939109105717, + "ts_ns": 1795939109105717000, + "schema": "public", + "table": "orders", + "txId": 775, + "lsn": 30425880, + "xmin": null, + "origin": null, + "origin_lsn": null + }, + "transaction": null, + "op": "c", + "ts_ms": 1795939109620, + "ts_us": 1795939109620915, + "ts_ns": 1795939109620915228 +} diff --git a/debezium-cdc/output/03-replica-identity.txt b/debezium-cdc/output/03-replica-identity.txt new file mode 100644 index 0000000..4e61d27 --- /dev/null +++ b/debezium-cdc/output/03-replica-identity.txt @@ -0,0 +1,20 @@ +### REPLICA IDENTITY DEFAULT: update and delete of order 4 +p=2 op=c key={"id":4} lsn=30441152 txId=779 snapshot=false before=null after={"id":4,"customer":"dev","status":"NEW","amount_cents":500} +p=2 op=u key={"id":4} lsn=30441344 txId=780 snapshot=false before=null after={"id":4,"customer":"dev","status":"PAID","amount_cents":500} +p=2 op=d key={"id":4} lsn=30441512 txId=781 snapshot=false before={"id":4,"customer":"","status":"","amount_cents":0} after=null +p=2 key={"id":4} TOMBSTONE (null value) + +### Switch the table to REPLICA IDENTITY FULL + relname | relreplident +---------+-------------- + orders | f +(1 row) + +### Same three statements for order 5 +p=2 op=c key={"id":5} lsn=30442128 txId=783 snapshot=false before=null after={"id":5,"customer":"kiran","status":"NEW","amount_cents":700} +p=2 op=u key={"id":5} lsn=30442320 txId=784 snapshot=false before={"id":5,"customer":"kiran","status":"NEW","amount_cents":700} after={"id":5,"customer":"kiran","status":"PAID","amount_cents":700} +p=2 op=d key={"id":5} lsn=30442488 txId=785 snapshot=false before={"id":5,"customer":"kiran","status":"PAID","amount_cents":700} after=null +p=2 key={"id":5} TOMBSTONE (null value) + +### Add a column while the connector is running; the next event carries it, no restart needed +p=0 op=u key={"id":1} lsn=30454520 txId=787 snapshot=false before={"id":1,"customer":"asha","status":"NEW","amount_cents":1500,"note":null} after={"id":1,"customer":"asha","status":"NEW","amount_cents":1500,"note":"gift wrap"} diff --git a/debezium-cdc/output/04-ordering.txt b/debezium-cdc/output/04-ordering.txt new file mode 100644 index 0000000..b4d3a36 --- /dev/null +++ b/debezium-cdc/output/04-ordering.txt @@ -0,0 +1,21 @@ +### Topic layout +Topic: shop.public.orders TopicId: e8p9s2PcSK6mPO3bvQRmyA PartitionCount: 3 ReplicationFactor: 1 Configs: min.insync.replicas=1 + +### Write: 6 orders (ids 10..15), then 4 rounds of single-row updates, then one transaction that updates 10, then 12, then 13 +### Which partition each key landed on, and whether its events stayed in WAL order inside that partition +key 10: partitions=['1'] events=6 lsn strictly increasing in offset order=True +key 11: partitions=['1'] events=5 lsn strictly increasing in offset order=True +key 12: partitions=['2'] events=6 lsn strictly increasing in offset order=True +key 13: partitions=['0'] events=6 lsn strictly increasing in offset order=True +key 14: partitions=['0'] events=5 lsn strictly increasing in offset order=True +key 15: partitions=['0'] events=5 lsn strictly increasing in offset order=True + +### Reading partition 0, then 1, then 2 (what the broker stores): is the LSN sequence globally increasing? +lsn sequence head: [30455336, 30455528, 30455720, 30456392, 30456552, 30456712, 30457352, 30457512] +globally increasing across partitions: False +events per partition: {'0': 16, '1': 11, '2': 6} + +### The multi-statement transaction (statuses TX-A, TX-B, TX-C): one txId, increasing lsn, three different keys +status=TX-A key=10 partition=1 lsn=30459776 txId=818 +status=TX-B key=12 partition=2 lsn=30459896 txId=818 +status=TX-C key=13 partition=0 lsn=30460016 txId=818 diff --git a/debezium-cdc/output/05-outbox.txt b/debezium-cdc/output/05-outbox.txt new file mode 100644 index 0000000..ffff234 --- /dev/null +++ b/debezium-cdc/output/05-outbox.txt @@ -0,0 +1,14 @@ +### Register the outbox connector (EventRouter single message transform) +register 201 + +### One transaction writes the business row AND the outbox row + +### A second transaction inserts an outbox row and deletes it before committing (the 'clean up as you go' habit) +outbox rows left in the table: 1 + +### Topic outbox.event.Order (headers | key | value; the four __debezium.context.* headers are trimmed with sed) +id:00000000-0000-0000-0000-000000000021,eventType:OrderCreated | 21 | {"orderId":21,"customer":"omkar","amountCents":100} +id:00000000-0000-0000-0000-000000000020,eventType:OrderCreated | 20 | {"orderId":20,"customer":"zoya","amountCents":4200} + +### Topics that exist for this connector +outbox.event.Order diff --git a/debezium-cdc/output/06-wal-retention.txt b/debezium-cdc/output/06-wal-retention.txt new file mode 100644 index 0000000..8090e17 --- /dev/null +++ b/debezium-cdc/output/06-wal-retention.txt @@ -0,0 +1,44 @@ +### Safety valve: the default cap on WAL a slot may pin (-1 = unlimited) + max_slot_wal_keep_size +------------------------ + -1 +(1 row) + + +### Baseline: both connectors running, nothing unusual written + slot_name | active | wal_kept_for_slot | unconfirmed +----------------+--------+-------------------+------------- + connect_orders | t | 2752 bytes | 2752 bytes + connect_outbox | t | 1064 bytes | 432 bytes +(2 rows) + + +### Failure 1: healthy connectors, but all the writes go to a table nobody captures (100,000 rows, about 33 MB of WAL) + slot_name | active | wal_kept_for_slot | unconfirmed +----------------+--------+-------------------+------------- + connect_orders | t | 33 MB | 33 MB + connect_outbox | t | 33 MB | 33 MB +(2 rows) + + +### Failure 2: delete the outbox connector. Kafka Connect does not drop its slot. + slot_name | active | wal_kept_for_slot | unconfirmed +----------------+--------+-------------------+------------- + connect_orders | t | 65 MB | 65 MB + connect_outbox | f | 65 MB | 65 MB +(2 rows) + + +### Fix for 2: drop the orphaned slot by hand + slot_name | active | wal_kept_for_slot | unconfirmed +----------------+--------+-------------------+------------- + connect_orders | t | 65 MB | 65 MB +(1 row) + + +### Fix for 1: heartbeat.interval.ms plus a heartbeat.action.query that writes to a captured table (public.heartbeat) + slot_name | active | wal_kept_for_slot | unconfirmed +----------------+--------+-------------------+------------- + connect_orders | t | 656 bytes | 656 bytes +(1 row) + diff --git a/debezium-cdc/output/07-embedded.txt b/debezium-cdc/output/07-embedded.txt new file mode 100644 index 0000000..735089d --- /dev/null +++ b/debezium-cdc/output/07-embedded.txt @@ -0,0 +1,39 @@ +### Start the Spring Boot app with the embedded engine (slot embedded_orders, topic prefix embedded) +snapshot rows delivered by the engine: 9 + slot_name | plugin | active +-----------------+----------+-------- + embedded_orders | pgoutput | t +(1 row) + + +### Insert, update and delete order 30, and the app's own view of them (EMBEDDED = engine callback, LISTENER = @KafkaListener on embedded.public.orders) +EMBEDDED op=c key={"id":30} lsn=99363544 before=null after={"id":30,"customer":"tara","status":"NEW","amount_cents":300,"note":null} +LISTENER partition=0 offset=5 op=c key={"id":30} lsn=99363544 before=null after={"id":30,"customer":"tara","status":"NEW","amount_cents":300,"note":null} +EMBEDDED op=u key={"id":30} lsn=99363736 before={"id":30,"customer":"tara","status":"NEW","amount_cents":300,"note":null} after={"id":30,"customer":"tara","status":"PAID","amount_cents":300,"note":null} +LISTENER partition=0 offset=6 op=u key={"id":30} lsn=99363736 before={"id":30,"customer":"tara","status":"NEW","amount_cents":300,"note":null} after={"id":30,"customer":"tara","status":"PAID","amount_cents":300,"note":null} +EMBEDDED op=d key={"id":30} lsn=99363904 before={"id":30,"customer":"tara","status":"PAID","amount_cents":300,"note":null} after=null +EMBEDDED key={"id":30} TOMBSTONE (null value) +LISTENER partition=0 offset=7 op=d key={"id":30} lsn=99363904 before={"id":30,"customer":"tara","status":"PAID","amount_cents":300,"note":null} after=null +LISTENER partition=0 offset=8 key={"id":30} TOMBSTONE (ignored) + +### Same UPDATE, seen by Kafka Connect (topic shop.public.orders) and by the embedded engine (topic embedded.public.orders): what differs? +5c5 +< "name": "shop", +--- +> "name": "embedded", + +### At-least-once: offsets are flushed every 60 s (Debezium's default). Wait 65 s, then three updates, then kill -9 the JVM +killed. Events the first run delivered for key id=1 after the wait: +lsn=99384632 status set to A0 +lsn=99385008 status set to A1 +lsn=99385192 status set to A2 + +### Restart the app (same offset file, same slot) +EMBEDDED events in the second run (anything here is a redelivery): +lsn=99385008 status set to A1 +lsn=99385192 status set to A2 + +### What a downstream consumer sees on embedded.public.orders: records per (key, lsn) for the three A updates + 1 status=A0 lsn=99384632 + 2 status=A1 lsn=99385008 + 2 status=A2 lsn=99385192 diff --git a/debezium-cdc/pom.xml b/debezium-cdc/pom.xml new file mode 100644 index 0000000..523971e --- /dev/null +++ b/debezium-cdc/pom.xml @@ -0,0 +1,65 @@ + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.2.0 + + + + com.ankurm + debezium-cdc + 1.0 + jar + + + 25 + UTF-8 + + 3.7.1.Final + + + + + org.springframework.boot + spring-boot-starter-kafka + + + org.springframework.boot + spring-boot-starter-jackson + + + + + io.debezium + debezium-api + ${debezium.version} + + + io.debezium + debezium-embedded + ${debezium.version} + + + io.debezium + debezium-connector-postgres + ${debezium.version} + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/debezium-cdc/scripts/01-logical-replication.sh b/debezium-cdc/scripts/01-logical-replication.sh new file mode 100755 index 0000000..a3f7bda --- /dev/null +++ b/debezium-cdc/scripts/01-logical-replication.sh @@ -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" diff --git a/debezium-cdc/scripts/02-event-format.sh b/debezium-cdc/scripts/02-event-format.sh new file mode 100755 index 0000000..85bf608 --- /dev/null +++ b/debezium-cdc/scripts/02-event-format.sh @@ -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" diff --git a/debezium-cdc/scripts/03-replica-identity.sh b/debezium-cdc/scripts/03-replica-identity.sh new file mode 100755 index 0000000..e8109b0 --- /dev/null +++ b/debezium-cdc/scripts/03-replica-identity.sh @@ -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 : 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" diff --git a/debezium-cdc/scripts/04-ordering.sh b/debezium-cdc/scripts/04-ordering.sh new file mode 100755 index 0000000..1c7dc1d --- /dev/null +++ b/debezium-cdc/scripts/04-ordering.sh @@ -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" diff --git a/debezium-cdc/scripts/05-outbox.sh b/debezium-cdc/scripts/05-outbox.sh new file mode 100755 index 0000000..50bce9c --- /dev/null +++ b/debezium-cdc/scripts/05-outbox.sh @@ -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" diff --git a/debezium-cdc/scripts/06-wal-retention.sh b/debezium-cdc/scripts/06-wal-retention.sh new file mode 100755 index 0000000..0dd3dbd --- /dev/null +++ b/debezium-cdc/scripts/06-wal-retention.sh @@ -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" diff --git a/debezium-cdc/scripts/07-embedded.sh b/debezium-cdc/scripts/07-embedded.sh new file mode 100755 index 0000000..c261245 --- /dev/null +++ b/debezium-cdc/scripts/07-embedded.sh @@ -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 -> 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 + 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" diff --git a/debezium-cdc/scripts/lib.sh b/debezium-cdc/scripts/lib.sh new file mode 100755 index 0000000..9b607ea --- /dev/null +++ b/debezium-cdc/scripts/lib.sh @@ -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 [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 + 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; } diff --git a/debezium-cdc/scripts/run-all.sh b/debezium-cdc/scripts/run-all.sh new file mode 100755 index 0000000..94dd81f --- /dev/null +++ b/debezium-cdc/scripts/run-all.sh @@ -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 diff --git a/debezium-cdc/scripts/summarize.py b/debezium-cdc/scripts/summarize.py new file mode 100644 index 0000000..d3f9cce --- /dev/null +++ b/debezium-cdc/scripts/summarize.py @@ -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) diff --git a/debezium-cdc/scripts/up.sh b/debezium-cdc/scripts/up.sh new file mode 100755 index 0000000..129a440 --- /dev/null +++ b/debezium-cdc/scripts/up.sh @@ -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" diff --git a/debezium-cdc/sql/init.sql b/debezium-cdc/sql/init.sql new file mode 100644 index 0000000..9dd2884 --- /dev/null +++ b/debezium-cdc/sql/init.sql @@ -0,0 +1,30 @@ +-- Two tables: a plain business table, and an outbox table used in the last section. +CREATE TABLE orders ( + id bigint PRIMARY KEY, + customer text NOT NULL, + status text NOT NULL, + amount_cents integer NOT NULL +); + +CREATE TABLE outbox ( + id uuid PRIMARY KEY, + aggregatetype text NOT NULL, + aggregateid text NOT NULL, + type text NOT NULL, + payload jsonb NOT NULL +); + +-- Seed rows that exist BEFORE any connector starts, so the initial snapshot has something to read. +INSERT INTO orders VALUES (1, 'asha', 'NEW', 1500), (2, 'ravi', 'NEW', 2500); + +-- A table nobody captures. Writing to it still produces WAL, which matters in the "slot retains WAL" section. +CREATE TABLE noise ( + id bigserial PRIMARY KEY, + payload text NOT NULL +); + +-- Written by the connector's heartbeat.action.query so a quiet slot can still move forward (section on WAL retention). +CREATE TABLE heartbeat ( + id integer PRIMARY KEY, + ts timestamptz +); diff --git a/debezium-cdc/src/main/java/com/ankurm/cdc/CdcApplication.java b/debezium-cdc/src/main/java/com/ankurm/cdc/CdcApplication.java new file mode 100644 index 0000000..b7cfca6 --- /dev/null +++ b/debezium-cdc/src/main/java/com/ankurm/cdc/CdcApplication.java @@ -0,0 +1,11 @@ +package com.ankurm.cdc; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class CdcApplication { + public static void main(String[] args) { + SpringApplication.run(CdcApplication.class, args); + } +} diff --git a/debezium-cdc/src/main/java/com/ankurm/cdc/ChangeEvent.java b/debezium-cdc/src/main/java/com/ankurm/cdc/ChangeEvent.java new file mode 100644 index 0000000..fbf443f --- /dev/null +++ b/debezium-cdc/src/main/java/com/ankurm/cdc/ChangeEvent.java @@ -0,0 +1,34 @@ +package com.ankurm.cdc; + +import tools.jackson.databind.JsonNode; + +/** + * The part of a Debezium change-event envelope this module cares about, read from the JSON value. + * Works for both the embedded engine and Kafka Connect, because both emit the same envelope. + */ +public record ChangeEvent(String op, JsonNode key, JsonNode before, JsonNode after, long lsn, long txId, String snapshot) { + + public static ChangeEvent parse(tools.jackson.databind.ObjectMapper mapper, String key, String value) { + JsonNode k = key == null ? null : mapper.readTree(key); + JsonNode v = mapper.readTree(value); + // With schemas.enable=true the envelope is wrapped in {"schema":..., "payload":...}. + JsonNode p = v.has("payload") ? v.get("payload") : v; + JsonNode src = p.get("source"); + return new ChangeEvent( + p.get("op").asString(), + k != null && k.has("payload") ? k.get("payload") : k, + p.get("before"), p.get("after"), + src.get("lsn").asLong(), src.get("txId").asLong(), + src.has("snapshot") ? src.get("snapshot").asString() : "false"); + } + + /** One compact line, the same shape for every transcript in output/. */ + public String summary() { + return "op=%s key=%s lsn=%d txId=%d before=%s after=%s".formatted( + op, key, lsn, txId, nullable(before), nullable(after)); + } + + private static String nullable(JsonNode n) { + return n == null || n.isNull() ? "null" : n.toString(); + } +} diff --git a/debezium-cdc/src/main/java/com/ankurm/cdc/EmbeddedDebezium.java b/debezium-cdc/src/main/java/com/ankurm/cdc/EmbeddedDebezium.java new file mode 100644 index 0000000..8ed7f4f --- /dev/null +++ b/debezium-cdc/src/main/java/com/ankurm/cdc/EmbeddedDebezium.java @@ -0,0 +1,127 @@ +package com.ankurm.cdc; + +import io.debezium.engine.ChangeEvent; +import io.debezium.engine.DebeziumEngine; +import io.debezium.engine.format.Json; +import java.io.IOException; +import java.util.Properties; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.SmartLifecycle; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.stereotype.Component; +import tools.jackson.databind.ObjectMapper; + +/** + * Runs the Debezium PostgreSQL connector inside this JVM and forwards each change to Kafka. + * Compare with orders-connector.json, which asks a Kafka Connect cluster to do the same job. + */ +@Component +@ConditionalOnProperty(name = "cdc.embedded.enabled", havingValue = "true") +public class EmbeddedDebezium implements SmartLifecycle { + + private static final Logger log = LoggerFactory.getLogger("cdc"); + + private final KafkaTemplate kafka; + private final ObjectMapper mapper; + private final boolean showRaw; + private final Properties props = new Properties(); + private final String topicPrefix; + + private DebeziumEngine> engine; + private ExecutorService executor; + + public EmbeddedDebezium(KafkaTemplate kafka, ObjectMapper mapper, + @Value("${cdc.embedded.db-host}") String host, @Value("${cdc.embedded.db-port}") int port, + @Value("${cdc.embedded.db-name}") String db, @Value("${cdc.embedded.db-user}") String user, + @Value("${cdc.embedded.db-password}") String password, @Value("${cdc.embedded.slot}") String slot, + @Value("${cdc.embedded.topic-prefix}") String topicPrefix, + @Value("${cdc.embedded.offset-file}") String offsetFile, + @Value("${cdc.embedded.offset-flush-ms}") long flushMs, + @Value("${cdc.embedded.show-raw}") boolean showRaw) { + this.kafka = kafka; + this.mapper = mapper; + this.showRaw = showRaw; + this.topicPrefix = topicPrefix; + + props.setProperty("name", "embedded-orders"); + props.setProperty("connector.class", "io.debezium.connector.postgresql.PostgresConnector"); + // Where the engine remembers how far it got. A file is fine for a demo; production wants a durable store. + props.setProperty("offset.storage", "org.apache.kafka.connect.storage.FileOffsetBackingStore"); + props.setProperty("offset.storage.file.filename", offsetFile); + props.setProperty("offset.flush.interval.ms", Long.toString(flushMs)); + props.setProperty("database.hostname", host); + props.setProperty("database.port", Integer.toString(port)); + props.setProperty("database.dbname", db); + props.setProperty("database.user", user); + props.setProperty("database.password", password); + props.setProperty("topic.prefix", topicPrefix); + props.setProperty("table.include.list", "public.orders"); + props.setProperty("plugin.name", "pgoutput"); + props.setProperty("slot.name", slot); + props.setProperty("publication.name", slot + "_pub"); + props.setProperty("publication.autocreate.mode", "filtered"); + // Same envelope as the Connect connector: no schema wrapper. + props.setProperty("key.converter.schemas.enable", "false"); + props.setProperty("value.converter.schemas.enable", "false"); + } + + @Override + public void start() { + engine = DebeziumEngine.create(Json.class, Json.class) + .using(props) + .notifying(this::handle) + .build(); + executor = Executors.newSingleThreadExecutor(); + executor.execute(engine); + } + + /** Called on the engine thread, one record at a time, in WAL order. */ + private void handle(ChangeEvent record) { + if (record.value() == null) { + // The tombstone Debezium emits after a delete. Forward it as-is: it is what lets a compacted topic forget the key. + log.info("EMBEDDED key={} TOMBSTONE (null value)", record.key()); + send(record); + return; + } + var event = com.ankurm.cdc.ChangeEvent.parse(mapper, record.key(), record.value()); + log.info("EMBEDDED {}", event.summary()); + if (showRaw) { + log.info("EMBEDDED-RAW {}", record.value()); + } + send(record); + } + + private void send(ChangeEvent record) { + // Blocking send keeps the order and means an exception here stops the engine instead of skipping a change. + try { + kafka.send(record.destination(), record.key(), record.value()).get(10, TimeUnit.SECONDS); + } catch (Exception e) { + throw new IllegalStateException("could not forward " + record.destination(), e); + } + } + + @Override + public void stop() { + try { + if (engine != null) { + engine.close(); + } + } catch (IOException e) { + throw new IllegalStateException(e); + } + if (executor != null) { + executor.shutdown(); + } + } + + @Override + public boolean isRunning() { + return executor != null && !executor.isShutdown(); + } +} diff --git a/debezium-cdc/src/main/java/com/ankurm/cdc/OrderChangeListener.java b/debezium-cdc/src/main/java/com/ankurm/cdc/OrderChangeListener.java new file mode 100644 index 0000000..6a60c03 --- /dev/null +++ b/debezium-cdc/src/main/java/com/ankurm/cdc/OrderChangeListener.java @@ -0,0 +1,48 @@ +package com.ankurm.cdc; + +import java.util.HashMap; +import java.util.Map; +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.stereotype.Component; +import tools.jackson.databind.ObjectMapper; + +/** + * A plain consumer of the topic Kafka Connect writes. It keeps a tiny read model (order id to latest row) and + * shows the two things every CDC consumer has to handle: a null value (the tombstone after a delete) and a + * duplicate delivery (the same LSN seen twice). + */ +@Component +@ConditionalOnProperty(name = "cdc.listener.enabled", havingValue = "true") +public class OrderChangeListener { + + private static final Logger log = LoggerFactory.getLogger("cdc"); + + private final ObjectMapper mapper; + private final Map lastLsnApplied = new HashMap<>(); + + public OrderChangeListener(ObjectMapper mapper) { + this.mapper = mapper; + } + + @KafkaListener(topics = "${cdc.listener.topic}") + public void on(ConsumerRecord record) { + if (record.value() == null) { + log.info("LISTENER partition={} offset={} key={} TOMBSTONE (ignored)", record.partition(), record.offset(), record.key()); + return; + } + var event = ChangeEvent.parse(mapper, record.key(), record.value()); + long id = event.key().get("id").asLong(); + Long seen = lastLsnApplied.get(id); + if (seen != null && event.lsn() <= seen) { + log.info("LISTENER partition={} offset={} DUPLICATE or out of order for id={} (lsn {} <= {}), skipped", + record.partition(), record.offset(), id, event.lsn(), seen); + return; + } + lastLsnApplied.put(id, event.lsn()); + log.info("LISTENER partition={} offset={} {}", record.partition(), record.offset(), event.summary()); + } +} diff --git a/debezium-cdc/src/main/resources/application.properties b/debezium-cdc/src/main/resources/application.properties new file mode 100644 index 0000000..0e30604 --- /dev/null +++ b/debezium-cdc/src/main/resources/application.properties @@ -0,0 +1,26 @@ +spring.application.name=debezium-cdc +spring.main.banner-mode=off +spring.kafka.bootstrap-servers=localhost:9092 +spring.kafka.consumer.group-id=cdc-demo +spring.kafka.consumer.auto-offset-reset=earliest +logging.pattern.console=%msg%n +logging.level.root=WARN +logging.level.cdc=INFO + +# Embedded Debezium engine (the "no Kafka Connect cluster" option). Off unless a script turns it on. +cdc.embedded.enabled=false +cdc.embedded.db-host=localhost +cdc.embedded.db-port=5432 +cdc.embedded.db-name=shop +cdc.embedded.db-user=demo +cdc.embedded.db-password=demo +cdc.embedded.slot=embedded_orders +cdc.embedded.topic-prefix=embedded +cdc.embedded.offset-file=target/embedded-offsets.dat +# Debezium's own default is 60000. The restart demo leaves it there on purpose. +cdc.embedded.offset-flush-ms=60000 +cdc.embedded.show-raw=false + +# A plain @KafkaListener on the topic Kafka Connect writes. Off unless a script turns it on. +cdc.listener.enabled=false +cdc.listener.topic=shop.public.orders diff --git a/debezium-cdc/src/test/java/com/ankurm/cdc/ChangeEventTest.java b/debezium-cdc/src/test/java/com/ankurm/cdc/ChangeEventTest.java new file mode 100644 index 0000000..4043655 --- /dev/null +++ b/debezium-cdc/src/test/java/com/ankurm/cdc/ChangeEventTest.java @@ -0,0 +1,35 @@ +package com.ankurm.cdc; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +/** No database, no Kafka: pins how the envelope is read, so a change in Debezium's JSON shape fails the build. */ +class ChangeEventTest { + + private final JsonMapper mapper = JsonMapper.builder().build(); + + private static final String UPDATE = """ + {"before":null,"after":{"id":7,"status":"PAID"}, + "source":{"snapshot":"false","lsn":12345,"txId":99},"op":"u"}"""; + + @Test + void readsAnUpdateEnvelopeWithoutSchemaWrapper() { + var e = ChangeEvent.parse(mapper, "{\"id\":7}", UPDATE); + assertThat(e.op()).isEqualTo("u"); + assertThat(e.lsn()).isEqualTo(12345); + assertThat(e.txId()).isEqualTo(99); + assertThat(e.before().isNull()).isTrue(); + assertThat(e.summary()).isEqualTo( + "op=u key={\"id\":7} lsn=12345 txId=99 before=null after={\"id\":7,\"status\":\"PAID\"}"); + } + + @Test + void unwrapsTheSchemaEnvelopeWhenSchemasAreEnabled() { + var wrapped = "{\"schema\":{},\"payload\":" + UPDATE + "}"; + var e = ChangeEvent.parse(mapper, "{\"schema\":{},\"payload\":{\"id\":7}}", wrapped); + assertThat(e.key().toString()).isEqualTo("{\"id\":7}"); + assertThat(e.after().get("status").asString()).isEqualTo("PAID"); + } +}