Your application writes an order to Postgres. Three other systems need to know: search, billing, an analytics pipeline. The obvious move is to call Kafka right after the INSERT, and an earlier post on this site spent a section proving why that is a trap: two systems, two commits, nothing that makes both happen or neither. Change data capture takes the opposite approach. Do not tell Kafka anything from the application. Let Postgres tell you, because Postgres already writes every committed change into its write-ahead log, in order, and a tool called Debezium can read that log and turn each row change into a Kafka message.
This post builds that against a real Postgres 18 and a real Kafka 4.4 broker, two ways: with Kafka Connect (the standard route) and with the Debezium embedded engine running inside a Spring Boot 4.2 application. Then it does the things the happy-path tutorials skip: it reads the event format byte by byte, finds out what ordering you really get, kills the JVM mid-stream to watch events arrive twice, and fills a replication slot until it pins WAL on disk. It ends on the question in the title: when the better answer is not to capture your business tables at all, but to capture an outbox table.
Versions used in this post. Debezium 3.7.1.Final (the newest GA release on Maven Central, published 6 Nov 2026; 3.8.0.Alpha2 is newer but is an alpha) · Spring Boot 4.2.0 · Spring for Apache Kafka 4.2.0 · kafka-clients 4.4.0 (from the Boot BOM) · Kafka brokerapache/kafka:4.4.0in KRaft mode · PostgreSQL 18.7 (quay.io/debezium/postgres:18) · Debezium Connect image 3.7.1.Final, which bundles a Kafka Connect 4.3.1 runtime · JDK Temurin 25.0.5.1. Everything in the console blocks below is from a real run of the companion module, regenerated by one script.
Postgres already keeps a perfect, ordered list of every change
Before any Debezium, the mechanism it relies on. Every committed change in Postgres is first written to the write-ahead log (WAL), a sequential file that exists so the database can recover after a crash. With wal_level=logical the WAL carries enough detail that Postgres can decode it back into row-level changes: this row was inserted, that column was updated. Three Postgres objects turn that into something a program can consume:
- a replication slot: a named bookmark. Postgres promises not to delete any WAL the slot has not yet confirmed as consumed;
- an output plugin that formats the decoded changes. Debezium uses
pgoutput, which ships with Postgres; - a publication: the list of tables whose changes
pgoutputshould send.
The diagram is the whole architecture. Anything that changes a row, whether your service, a migration script or someone in psql, ends up in the WAL, so CDC captures it. That is the main reason to choose CDC over writing to Kafka from the application. You can see the raw material without Debezium at all: create a throwaway slot with the built-in test_decoding plugin, change a row, and read the decoded stream.
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)
Full transcript: output/01-logical-replication.txt — script: 01-logical-replication.sh
Two details in that output matter later. Each transaction is wrapped in BEGIN/COMMIT with a number, which Debezium surfaces as txId. And the DELETE line carries only id, not the old payload. By default Postgres logs only the primary key for deletes, and that decision shapes the event format in a few sections.
Going deeper: what the server needs, and what it did here
The Debezium Postgres image presets wal_level=logical; on a stock Postgres you set it yourself and restart. This run reported:
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)Full transcript: output/01-logical-replication.txt
Each slot uses one of max_replication_slots and each active consumer one of max_wal_senders. Four of each was plenty here: one Connect connector, a second for the outbox, one embedded engine. Output plugins other than pgoutput exist (decoderbufs, wal2json); this post uses only pgoutput and does not test the others.
Run it with Kafka Connect: one JSON file
The standard way to run Debezium is as a connector on a Kafka Connect cluster. You do not write code. You POST a JSON description to Connect’s REST API and it starts a task that opens the replication connection, creates the slot and publication if they are missing, takes an initial snapshot of the existing rows, and then streams changes. The module’s docker-compose.yml brings up Postgres, Kafka and Connect; the connector for the business table is this:
{
"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"
}
}
Most keys are plumbing. The ones worth understanding: topic.prefix plus the schema and table name decide the topic (shop.public.orders); table.include.list decides what is captured; slot.name names the bookmark, which you want to choose yourself because you will meet it again when it fills a disk; the two schemas.enable=false lines strip the self-describing schema Kafka Connect’s JSON converter would otherwise wrap around every message, which keeps the events readable here. After registering it, Postgres contains what the connector created:
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)
Full transcript: output/01-logical-replication.txt
One slot, one publication that covers exactly public.orders. The connector is now a long-lived replication client, and the rest of this post is about living with that fact.
Going deeper: startup on a small machine
Kafka Connect scans every connector plugin in the Debezium image at start, and on the 2-vCPU sandbox used here the REST port did not answer for roughly a minute and a half after the container reported “Up”. scripts/up.sh therefore starts Postgres, then Kafka, then Connect one after another and polls each for readiness instead of trusting docker compose up. On a first attempt to start everything at once, Kafka and Connect were both stopped within half a minute; starting them one by one fixed it, and I did not dig into why.
What an event looks like, and the two surprises in it
Every change becomes a Kafka message with a key and a value. The key is the row’s primary key. The value is an envelope: before (the row as it was), after (the row as it is), op (c create, u update, d delete, r snapshot read), and a source block that says where in the WAL this came from. Here is the real insert for order 3, straight from the topic:
{
"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
}
Full transcript: output/02-event-format.txt — script: 02-event-format.sh
source.lsn is the position in the WAL and source.txId the Postgres transaction. Those two fields are what let a consumer reason about order, and they are the reason the ordering section can show anything useful. Now four statements against the table, each in its own transaction, and the topic read back in WAL order. The first two lines are the initial snapshot of the two seed rows (op=r):
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)
Full transcript: output/02-event-format.txt
Surprise one: the update hasbefore=null. Order 3 changed fromNEWtoPAIDand the event says nothing about what it was. Postgres only logs the old row when the table’s replica identity says to, and the default (d, primary key only) logs nothing for an update that leaves the key alone. A consumer that wants to compute “what changed” cannot, from this event alone.
Surprise two: the delete has abefore, but it is partly made up. Look at theop=dline:before={"id":3,"customer":"","status":"","amount_cents":0}. The row wasmeera / PAID / 1099. Only the key column is real; the threeNOT NULLcolumns were filled with an empty string and zero. Anyone who readsbefore.statuson a delete under the default identity will treat""as data. After the delete comes a tombstone, a message with the same key and anullvalue, which exists so a compacted Kafka topic can forget the key. Consumers must tolerate a null value.
The fix is one statement, and the transcript shows it. After ALTER TABLE orders REPLICA IDENTITY FULL the same three operations on a new row (order 5) look like this:
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)
Full transcript: output/03-replica-identity.txt — script: 03-replica-identity.sh
Now before is complete on both the update and the delete. The Debezium reference says the same thing in words: with FULL the events for updates and deletes “contain the previous values of all columns in the table”. I did not measure the extra WAL volume this causes, so I will not put a number on it; Postgres writes the old row to the log, so it is more than before, and on a wide, heavily updated table that is worth measuring before you flip it.
Going deeper: adding a column to a live connector
The same script runs ALTER TABLE orders ADD COLUMN note text while the connector is running, then updates a row. The very next event already carries the new field in both before and after, with no restart:
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"}That is the friendly case, an added nullable column. This post did not try renames, type changes or dropped columns, and consumers deserialising into a fixed class need a plan for each.
- PostgreSQL 18: ALTER TABLE … REPLICA IDENTITY
- ChangeEvent.java: the small parser every transcript line goes through
Run it inside Spring Boot: the embedded engine
Kafka Connect is a cluster to operate. Debezium also ships its connector as a library, the embedded engine, so a Spring Boot application can run the same Postgres connector in its own JVM and receive each change as a Java callback. This is where “Debezium with Spring Boot” literally happens. The module wraps the engine as a Spring lifecycle bean that starts with the context, hands every record to a method, and forwards it to Kafka with KafkaTemplate:
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");
The properties are the connector’s own, the same ones as in the JSON file, plus two the engine needs: offset.storage (where it remembers how far it got; a local file here) and offset.flush.interval.ms. The callback runs on the engine’s thread, one record at a time, in WAL order:
private void handle(ChangeEvent<String, String> 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);
}
Note the tombstone branch: the engine delivers it like any record, and forwarding it as-is is what keeps the downstream topic honest. My first version skipped null values, which silently dropped every delete’s tombstone; the listener transcript below is from the corrected code. The consuming side is an ordinary @KafkaListener on the topic the engine writes (embedded.public.orders):
@KafkaListener(topics = "${cdc.listener.topic}")
public void on(ConsumerRecord<String, String> 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());
}
Run against the same database, with an insert, an update and a delete of order 30, the two halves of the app report the same story: EMBEDDED lines come from the engine callback and LISTENER lines from the Kafka consumer, including the tombstone the listener ignores:
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)
Full transcript: output/07-embedded.txt — script: 07-embedded.sh
Is the embedded event the same as the one Kafka Connect produced? The script updates order 2 once and compares both topics’ value for that statement after removing the timestamps. The diff is the answer:
5c5
< "name": "shop",
---
> "name": "embedded",
Full transcript: output/07-embedded.txt
Only source.name differs, and that is just the topic.prefix I gave each. The envelope is identical, so a consumer cannot tell which one produced it. (On an earlier, uncommitted run the diff also showed a difference in the first element of source.sequence; I did not chase it.)
So which one? A direct comparison. The rows about offsets and your handler come from what ran here and from the Debezium reference; the rows about scaling and failover are general Kafka Connect behaviour that I did not exercise:
| Kafka Connect | Embedded engine in Spring Boot | |
|---|---|---|
| What you operate | A Connect cluster plus the connector JSON | Your application, nothing else |
| Where offsets live | A Kafka topic, managed by Connect | Whatever you configure; a file in this module |
| Scaling and failover | Connect restarts the task on another worker | You must make sure only one instance holds the slot |
| Where your code can run | Only as SMTs inside Connect | Right in the callback, with Spring beans |
| Failure in your handler | Connect retries or fails the task | Yours to handle; the docs say the handler should not throw |
The Debezium reference makes the same trade: embedding suits applications that do not need Kafka Connect’s fault tolerance and would rather not depend on an external cluster, and it recommends the full platform when you need stronger guarantees. One more thing from that page, and from reading my own code against it: the handler is not supposed to throw, because a record that failed cannot be retried and “your application might become inconsistent with the database”. My send() throws an IllegalStateException when Kafka does not acknowledge within ten seconds, which is the conservative choice (stop rather than skip), but I did not test what the engine does after that exception, so treat that path as unverified.
Going deeper: the third option, Debezium Server, and what this post did not run
Debezium also has a standalone server that runs the engine as a process and sends events to sinks (Kafka, Pulsar, Kinesis and others) with no Kafka Connect and no application code. I did not run it for this post, so I will not describe its behaviour beyond that. I also did not run Avro or a schema registry (the events here are plain JSON), a Postgres failover, a snapshot mode other than the default initial, or the decoderbufs and wal2json plugins.
- Debezium reference: the embedded engine
- README.md: how to run every scenario
Ordering: per key yes, per transaction no
Kafka orders messages only within a partition, and a topic here has three, with the row’s primary key deciding the partition. That gives one guarantee and takes away two. The script inserts six orders, updates each of them four times in separate transactions, then runs one transaction that updates orders 10, 12 and 13 in that order, and reads the topic back:
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
Full transcript: output/04-ordering.txt — script: 04-ordering.sh
Per key, order holds. Every key stays in one partition and its LSNs increase in offset order. A consumer that processes a partition in order sees each row’s history in the order it happened, which is what “apply the changes to a read model” needs.
Across keys, nothing holds. The transcript’s second block reads partition 0, then 1, then 2 and asks whether the LSN sequence is globally increasing. It is not. Inside one transaction, the events are split. The diagram above is the real result: three statements, one txId, three partitions. If two rows must be processed together, route them to the same partition or use the txId to regroup them on the consumer side. The Debezium reference states it plainly: “Ordering is guaranteed only for topics that use a single partition.” A single partition gives you total order and costs you parallelism.
Going deeper: what the script checks, exactly
The Python in the script reads the topic with the console consumer, groups events by partition in the order Kafka returned them (which is offset order inside a partition), and asserts three things: each key appears in exactly one partition, LSNs strictly increase inside each key, and the concatenation of the partitions is not globally sorted. The third being false is not proof of any particular reordering, only that no global order exists to rely on. The partition for a key comes from Kafka’s default partitioner hashing the serialised key, so the exact placement (10 and 11 together in partition 1, and so on) is deterministic for these keys but means nothing in itself.
Events arrive twice after a crash
Debezium remembers how far it has read by storing an offset (an LSN), and it does not store it after every event. Kafka Connect and the embedded engine both flush offsets on an interval, and the Debezium reference gives the default as one minute. Anything delivered since the last flush is delivered again after a crash. The reference is direct about it: applications must “be tolerant of receiving duplicate events immediately following a restart after a crash.” This is at-least-once delivery, and the way to see it is to cause it.
The script starts the Spring Boot app with the default 60-second flush, waits 65 seconds, then updates order 1 three times (A0, A1, A2) and kill -9s the JVM. My reading of the engine’s periodic commit policy is that the first update after the wait is the batch that triggers the flush; the transcript shows the outcome, not the mechanism. The first run delivered all three:
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
Full transcript: output/07-embedded.txt
Restart the app with the same offset file and the same slot, and the second run delivers two of them again:
EMBEDDED events in the second run (anything here is a redelivery):
lsn=99385008 status set to A1
lsn=99385192 status set to A2
A0 is gone from the second run because its offset was committed. A1 and A2 were not, so the engine asked Postgres for everything after the committed position and got them again, and because the engine had already forwarded the first copies to Kafka, the topic now holds both:
1 status=A0 lsn=99384632
2 status=A1 lsn=99385008
2 status=A2 lsn=99385192
Full transcript: output/07-embedded.txt
Two copies of A1 and of A2, one copy of A0, each with the same LSN. That LSN is the thing to deduplicate on. The module’s listener keeps the last LSN it applied per key and skips anything at or below it; that is the lastLsnApplied check in the code block earlier, and it is only enough because per-key order holds. The transcript does not show that check firing, because the restart also wipes the listener’s in-memory map; it is the shape of the fix, not a tested one. A real consumer needs that state to be durable (a column next to the row it updates, say), not a HashMap.
A clean shutdown is not covered by this test. The transcript is a hard kill. The Debezium reference tells applications to stop the engine properly and not to rely on shutting down the executor;EmbeddedDebezium.stop()callsengine.close()first. I did not run a graceful-stop-then-restart comparison, so I make no claim about how many duplicates that path leaves.
The slot can fill your disk
Back to the bookmark. Postgres keeps every WAL segment from the slot’s restart_lsn forward, and the slot only moves when the consumer confirms an LSN. Three ways that goes wrong, all reproduced. Throughout, the transcript reads the slot view and prints how much WAL each slot is holding back. The safety valve, max_slot_wal_keep_size, is set to -1, which means unlimited:
max_slot_wal_keep_size
------------------------
-1
(1 row)
Full transcript: output/06-wal-retention.txt — script: 06-wal-retention.sh
Failure one: a quiet slot on a busy database. Both connectors are healthy and running. The script writes 100,000 rows to a noise table that neither connector captures. Neither connector has a single new event to deliver, yet:
slot_name | active | wal_kept_for_slot | unconfirmed
----------------+--------+-------------------+-------------
connect_orders | t | 33 MB | 33 MB
connect_outbox | t | 33 MB | 33 MB
(2 rows)
Full transcript: output/06-wal-retention.txt
Both slots are active and both sit 33 MB behind. The connectors only confirm an LSN when they process something in a captured table, so changes in other tables of the same database pile up as unconfirmed WAL. In real life that table is not called noise; it is the rest of your application’s data.
Failure two: a deleted connector leaves its slot behind. Deleting the outbox connector from Kafka Connect does not drop its slot, and the slot keeps holding WAL with nobody reading it:
slot_name | active | wal_kept_for_slot | unconfirmed
----------------+--------+-------------------+-------------
connect_orders | t | 65 MB | 65 MB
connect_outbox | f | 65 MB | 65 MB
(2 rows)
Full transcript: output/06-wal-retention.txt
connect_outbox is now active = f and holds 65 MB that no consumer will ever confirm. Fixing it is deliberate and manual: select pg_drop_replication_slot('connect_outbox'), after which the slot is gone from the list:
slot_name | active | wal_kept_for_slot | unconfirmed
----------------+--------+-------------------+-------------
connect_orders | t | 65 MB | 65 MB
(1 row)
Full transcript: output/06-wal-retention.txt
The bars are the orders slot from the transcript (connect_orders). The fix for the quiet slot is a heartbeat: heartbeat.interval.ms makes the connector emit a periodic message, and heartbeat.action.query makes it run a small write against a table that is in the publication, so there is always something to confirm. The script applies it with Connect’s config API:
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
slot_name | active | wal_kept_for_slot | unconfirmed
----------------+--------+-------------------+-------------
connect_orders | t | 656 bytes | 656 bytes
(1 row)
Full transcript: output/06-wal-retention.txt
Sixty seconds later the slot holds 656 bytes. That is not a guess, but part of the evidence is exploratory and not committed: in an earlier run of the same experiment the heartbeat query did nothing while the heartbeat table was not in table.include.list, and the slot only collapsed after I added it. My explanation is that the write is then never decoded and so never confirmed, which I did not verify further. The Debezium reference describes this scenario, a database with many changes to tables the connector does not capture, and recommends exactly this setting. The Connect log from that exploratory run said it too, on connector startup: “consider using heartbeat.action.query to prevent WAL growth”.
Set a ceiling and an alert before you need them.max_slot_wal_keep_sizedefaults to unlimited, so a stuck slot grows until the disk is full and the database stops. Setting it caps the damage at the price of invalidating the slot (the connector must then re-snapshot). I did not exercise that limit in this module. Whatever you choose, alert on the query in the transcript (pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)per slot) and drop slots you no longer use.
- Debezium PostgreSQL: heartbeat.interval.ms and heartbeat.action.query
- init.sql: the
noiseandheartbeattables
When to prefer the outbox
Everything so far captures the orders table, and that has a cost you have already seen in the transcripts. The event is the table row: its columns, its key, its delete behaviour, its replica identity. Rename a column and every consumer sees it. Delete a row and consumers receive a half-empty before and a tombstone. A single business action that touches three tables arrives as three unrelated events in three topics with no ordering between them (previous section). The events are a mirror of your storage, not a statement of what happened.
The outbox pattern fixes this at the source. The application writes the business row and a purpose-built event row into an outbox table in the same transaction, so the two are atomic. Debezium captures only the outbox table. The event row has the shape you want to publish: aggregate type, aggregate id, event type, and a payload. A Debezium transform, the EventRouter, turns each row into a Kafka message with the aggregate id as the key. The connector for it differs from the first one in a few lines:
"table.include.list": "public.outbox",
"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"
The script writes an order and its outbox row in one transaction, and the router’s output on the topic outbox.event.Order looks like this, headers first, then key, then value:
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}
Full transcript: output/05-outbox.txt — script: 05-outbox.sh
Compare this with the table events earlier: the key is the aggregate id (20), the event type travels as a header (eventType) next to the event id, and the value is just the payload object, no envelope, no before/after, no op. Consumers get a message that says “OrderCreated” instead of a row diff.
Look at the first message, 21. It is the product of the script’s second transaction, which inserts an outbox row and deletes it before committing, the common habit of cleaning the table as you go to stop it growing. The delete did not cancel the event: the transcript shows the table ends with one row (order 20’s), yet both events reached Kafka, so in this setup the insert was captured even though the row no longer existed when the transaction committed. I did not look inside the router to explain why, so run the same test against your own configuration before you rely on deleting rows immediately to keep the table small. (The two messages appear in the opposite order to the writes because they have different keys and landed in different partitions, which is the previous section again.)
Going deeper: the outbox in the same post series, and where this module differs
The Spring Modulith event publication registry post uses an outbox too: the registry row is written in the business transaction, and the application’s own event machinery delivers it to Kafka afterwards, with a resubmission call for rows that failed. You need no Debezium and no replication slot, and the relay is code running inside your own service. Here the relay is Debezium: nothing in your code publishes, which is attractive when several services or languages write to the same database, and costs you everything in the previous section (a slot to monitor, offsets, redelivery). The two are alternatives for the relay; the outbox table is the same idea in both.
- Debezium: outbox event router
- Transactional Outbox with the Spring Modulith Event Publication Registry on this site
- microservices.io: Transactional outbox
So which should you pick?
| Situation | Reasonable choice |
|---|---|
| Replicate tables to a search index or warehouse, and you accept consumers seeing your schema | CDC on the business tables, replica identity FULL if you need before |
| Publish domain events other teams depend on | Outbox table, captured by Debezium or read by your own relay |
| Several writers or languages share the database, and you cannot change them all | CDC: it sees every writer. An outbox only works if every writer writes the event row |
| One Spring service, already on Modulith | The registry outbox from the earlier post; no slot to run |
| Nobody on the team will watch slot lag | Neither CDC route yet: set up the alert first |
Should you even do this? CDC is worth it when the writers are many, the consumers are many, or the history matters, and it earns its cost by making the database the single source of truth for “what changed”. It is not free: you take on a replication slot that can fill a disk, at-least-once delivery that every consumer must tolerate, ordering that stops at the partition, and an event format that exposes your schema. If one service owns its table and one consumer needs to hear about changes, an outbox relayed by that service, or a plain transactional publish with the failure modes understood, is less to run. The honest test is the one in the WAL section: can you say who gets paged whenconnect_outboxshowsactive = f?
Reproduce everything: commands, files and what each transcript came from
You need JDK 25, Maven, Docker with the compose plugin, curl, jq and python3. From the module directory:
export JDK25_HOME=/path/to/jdk-25
./scripts/run-all.shThat builds the stack from nothing, runs the unit test, and rewrites every file under output/, about twelve minutes on a 2-vCPU machine. Scenario scripts: 01-logical-replication.sh, 02-event-format.sh, 03-replica-identity.sh, 04-ordering.sh, 05-outbox.sh, 06-wal-retention.sh, 07-embedded.sh. Transcripts: 01-logical-replication.txt, 02-event-format.txt, 03-replica-identity.txt, 04-ordering.txt, 05-outbox.txt, 06-wal-retention.txt, 07-embedded.txt.
Two notes on how the numbers were produced. LSNs, transaction ids and timestamps differ on every run, so only the shapes and the relative sizes are meant to be reproducible. Kafka Connect’s offset flush interval was set to 10 seconds in docker-compose.yml (its default is 60 seconds) so the WAL scenario does not need minute-long waits; the embedded scenario keeps Debezium’s 60-second default on purpose.
The module’s only automated test is ChangeEventTest.java, which pins how the envelope is parsed. The scenarios are scripts, not tests: they drive Docker containers and are not asserted, so the transcripts show what happened rather than failing the build when behaviour changes.
Further reading
- debezium-cdc companion module in the spring-messaging-demo repository: versions, layout and output index
- Transactional Outbox with the Spring Modulith Event Publication Registry: the in-application alternative to a Debezium relay
- Debezium PostgreSQL connector
- Debezium embedded engine
- Debezium outbox event router
- PostgreSQL 18: logical decoding
No Comments yet!