The transactional outbox
Write the event in the same transaction as the row, relay it later, and accept at-least-once — then make the consumer idempotent.
Save the order, then publish OrderPlaced. Two lines, and between them is every failure that produces an order nobody knows about — or an event for an order that was rolled back. The transactional outbox is the pattern that makes "write the row and tell the world" one atomic act, at the price of a table, a relay, and a guarantee that is at-least-once rather than exactly-once.
The dual-write problem
@Transactional
public void place(Order order) {
orders.save(order); // in the transaction
kafka.send("orders", new OrderPlaced(order.id())); // NOT in the transaction
}Four things can happen, and two are wrong. The commit succeeds and the send succeeds: fine. The commit fails and the send was never reached: fine. The send happens and then the commit fails — Kafka has an event for an order that does not exist. Or, reorder the lines, the commit succeeds and the send fails — the network blinked, the broker was rebalancing, the process was killed — and the order exists with no event, so inventory never hears, and the customer's confirmation never goes out. Both are dual writes: two systems, no transaction spanning them, and the second one failing after the first committed.
Retrying the send does not fix it (the process may be gone). Putting the send inside the transaction does not fix it (Kafka is not a participant, and a commit that fails after the send still leaves the event out there). 2PC would, and the last lesson said why not.
The outbox table
Write the event into the same database, in the same transaction as the row:
CREATE TABLE outbox (
id BIGSERIAL PRIMARY KEY,
aggregate TEXT NOT NULL, -- 'order'
aggregate_id TEXT NOT NULL, -- '42', also the partition key
type TEXT NOT NULL, -- 'OrderPlaced'
payload JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
published_at TIMESTAMPTZ -- NULL until relayed
);@Transactional
public void place(Order order) {
orders.save(order);
outbox.save(new OutboxRow("order", order.id(), "OrderPlaced", json(order))); // same transaction
}Now there is exactly one commit, and it either contains both the order and the event or neither. The event has not reached Kafka yet; it is a row, durable, waiting. A separate relay reads unpublished rows and publishes them.
The relay: polling, or reading the log
Two ways to move rows from the table to the broker.
Polling. A scheduled job selects unpublished rows in id order, publishes each, and marks it. With SELECT ... FOR UPDATE SKIP LOCKED (from the SQL course's locking lesson) several relay instances can run without publishing the same row twice:
@Scheduled(fixedDelay = 200)
@Transactional
void relay() {
List<OutboxRow> batch = outbox.lockUnpublished(100); // FOR UPDATE SKIP LOCKED, ORDER BY id
for (OutboxRow row : batch) {
kafka.send(row.topic(), row.aggregateId(), row.payload()).get(); // wait for acks=all
row.markPublished();
}
}Simple, no new infrastructure, and a latency of about the polling interval. The cost is the poll itself against a busy table, and one subtlety: mark the row after the send has been acknowledged, so a crash between the two republishes rather than loses.
Change data capture. Debezium reads PostgreSQL's write-ahead log (the same log replication uses) through a logical replication slot, sees every insert into outbox the moment it commits, and publishes it to Kafka itself — the Debezium outbox event router does the table-to-topic mapping. No polling, sub-second latency, no load on the table, and the relay's state is the replication slot's position, which survives restarts. The cost is Debezium (a Kafka Connect deployment) and the operational rule that comes with logical replication: a slot that is not consumed holds WAL forever, and a forgotten slot is a disk that fills. Rows can then be deleted immediately or never, since the log already carried them.
Polling for a service with one relay and modest volume; CDC when the outbox is the backbone of many services or latency matters.
At-least-once, and therefore idempotent consumers
Both relays can publish a row twice — the send succeeded and the mark or the slot update did not — and neither can publish it zero times. That is at-least-once, and it is not a flaw to engineer away but the guarantee to design for: every consumer of an outbox event must be idempotent, which the distributed-systems course's idempotency lesson and the Kafka course's idempotent-consumer section both cover. The row's id (or a UUID in the payload) is the deduplication key; a consumer that records processed ids in its own transaction handles the duplicate by doing nothing.
Ordering comes along for free within an aggregate: rows are relayed in id order and keyed by aggregate_id, so all of order 42's events land on one partition in the order they were written. Across aggregates there is no ordering, and there should not need to be.
Keeping the table small
An outbox that is never cleaned is a table that grows by every event forever. With polling, delete rows after publication in the same batch or with a periodic job that removes rows older than a retention window (keep a day or two for debugging). With CDC, delete immediately after insert in the same transaction — Debezium sees the insert in the log regardless of the delete — so the table is always empty and the index never grows. Either way, put the relay's query on an index over (published_at, id) or the poll becomes a sequential scan of history.
Under the hood: how CDC actually reads the log, and what polling's SKIP LOCKED buys you
The relay section above already draws the top-level distinction — polling a table versus Debezium reading the write-ahead log — worth going one level deeper on both, because "reads the WAL" is doing a lot of unexplained work in that sentence, and "polling doesn't scale" is a claim usually made without saying why.
Logical decoding, concretely. PostgreSQL's WAL records physical changes to pages, not "insert this row" — that is not directly useful to a consumer that wants structured row changes. A logical replication slot pairs the WAL position with an output plugin (Postgres's built-in pgoutput, or a separately installed one like wal2json) whose job is to decode the low-level WAL records for the tables it is watching back into a stream of structured events — insert, update, delete, with column values — in the order the transactions committed. Debezium's PostgreSQL connector opens a replication connection to that slot and consumes this decoded stream directly; it never issues a SELECT against outbox at all, except once, for an initial snapshot of rows that existed before the slot was created. Because logical decoding reconstructs changes from committed transactions only — it discards the WAL from any transaction that later rolled back — a connector reading the outbox this way can never observe a row that a failed transaction almost inserted; there is no analogue of a dirty read here.
The slot's position is a log sequence number (LSN), stored server-side and advanced only when the connector confirms it has durably handled everything up to that point. A connector restart resumes from that LSN, not from a query — which is the concrete shape of "the relay's state is the replication slot's position," stated earlier in this lesson. The WAL-retention hazard follows directly from the same design: Postgres cannot retain WAL for one table only, because WAL is a single physical log for the whole instance, so an inactive or lagging slot holds back all of the instance's WAL, from every table's writes, not just the outbox's — a stalled connector on a rarely-written outbox table can still fill disk from an unrelated, high-write table elsewhere in the same database.
Polling's real cost. SELECT ... FOR UPDATE SKIP LOCKED lets several relay workers run against the same table without double-publishing, because each worker's query silently skips rows another worker already has locked rather than blocking on them — that is what makes running more than one relay instance safe, not faster. A single worker's throughput is bounded by fixedDelay plus one round trip per cycle, not by the query itself, until write volume is high enough that batch size and lock contention start to matter; CDC has no such floor, because the connector reacts to WAL activity rather than waiting out a timer.
Both mechanisms deliver at-least-once in exactly the sense the rest of this lesson already assumes: Kafka Connect (which runs Debezium) tracks its own committed offsets and re-delivers from the last uncommitted one after a restart, the same shape the polling relay has with its published_at mark. Neither relay style changes that guarantee — they only change latency and load.
Try it yourself
Decide polling or CDC, then check the tradeoff you actually traded
A payment service adds an outbox table. Volume is roughly 50 events per minute, one service publishes to it, and the team is choosing between a polling relay (fixedDelay = 200) and standing up Debezium.
Before reading on: which would you pick, and what specifically would make you switch later?
Work through what each choice actually costs at this volume, and what would change the answer
At 50 events a minute, polling every 200ms is essentially idle — most cycles find nothing to publish, the query against an indexed (published_at, id) is cheap, and end-to-end latency is bounded by the poll interval, well under a second. Standing up Debezium here trades a few lines of @Scheduled code for a Kafka Connect deployment, a slot to monitor for lag, and a new operational surface — for a latency improvement nobody asked for and a table that was never going to be the bottleneck.
The answer changes on a different axis than raw event count: many services sharing the pattern, sub-second latency actually mattering to a downstream consumer, or a table so hot that polling's per-cycle query starts competing for lock time with the application's own writes. None of those is about "50 events a minute is too slow to poll" — polling scales with instances, not row count, until contention shows up. Reach for CDC when the operational cost buys something the business needs, not by default because it is the more sophisticated-sounding option.
Misconceptions
- "CDC reads the outbox table with a faster query, just triggered by a change instead of a timer." It never queries the table at all (past an initial snapshot). Debezium reads the already-decoded stream of committed changes off the WAL through a replication slot — a fundamentally different mechanism from polling, not a faster version of the same one.
- "A replication slot only holds back WAL for the table it's decoding." WAL is one physical log for the whole Postgres instance; a slot cannot retain it per table. A slot watching a quiet outbox table can still fill disk because of a completely unrelated table's write volume, if the slot stalls.
Sources
- Chris Richardson, microservices.io — the Transactional Outbox pattern.
- Debezium documentation — "How the PostgreSQL connector works" (logical decoding, replication slots, snapshotting).
- PostgreSQL documentation — the chapter on logical decoding and replication slots.