Kafka in practice (2): dual writes, exactly-once and message ordering
The dual write between a database and Kafka (why emitting first or wrapping in a DB transaction both fail, the transactional outbox with Debezium), exactly-once for Kafka-to-Kafka flows and for flows that write to a database, and keeping message order from producer to consumer.
On this page
1. The problem
A payment service debits the balance in the DB, then sends BillPaid to Kafka. The pod is killed between the two steps: the money is gone, the bill isn't marked paid. The team swaps the order "to be safe", and the next week hits the opposite: the bill is marked paid but the money was never taken.
2. Key idea
A dual write is one process writing to two places that must succeed or fail together. If both are Kafka, there's a Kafka transaction; DB + Kafka share no transaction.
| Approach | Breaks when |
|---|---|
| Save to DB, then send | it dies in between: state changed, event lost |
| Send, then save | it dies in between: event out, state unchanged |
send() inside @Transactional |
send succeeds, COMMIT fails: DB rolls back, event already out |
@TransactionalEventListener(AFTER_COMMIT) |
it dies after commit, before sending: event lost |
| Transactional outbox | no divergence; the cost is tens to hundreds of ms of delay and at-least-once delivery |
Outbox: write the state and an outbox row in the same DB transaction; Debezium reads the WAL and publishes the event. The event is a business contract you name, without exposing table structure like direct CDC does.
2.1 How far does exactly-once reach?
| Flow | Example | How to get it |
|---|---|---|
| Kafka → Kafka | topic A → stage → topic B | a Kafka transaction: write output and commit input offsets together; read with read_committed |
| Kafka → DB, email, API | topic B → stage → DB | at-least-once + an idempotent consumer |
enable.idempotence stops duplicates in the Kafka log; Kafka transactions stop them across topics. A consumer that dies after writing the DB but before committing its offset will get that record again.
Order exists only within a partition. To keep one account's events in order: same key (account_id), an idempotent producer (retries don't reorder), and a consumer processing each partition sequentially.
3. In SQL and Java
The outbox table stores pre-encoded bytes; the consumer blocks duplicates with a unique constraint.
CREATE TABLE outbox (
id uuid PRIMARY KEY,
topic varchar(255) NOT NULL,
key bytea, -- account_id: decides partition and order
value bytea NOT NULL, -- serialised event
created_at timestamptz NOT NULL DEFAULT now()
);
BEGIN;
UPDATE balance SET amount = amount - 500000 WHERE account_id = 'A' AND amount >= 500000;
INSERT INTO outbox (id, topic, key, value) VALUES (gen_random_uuid(), 'bill-events', 'A', :payload);
COMMIT; -- both, or neither// Idempotent consumer: same transaction as the side effect
int fresh = jdbc.update("INSERT INTO processed_event (event_id) VALUES (?) ON CONFLICT DO NOTHING", e.id());
if (fresh == 1) bills.markPaid(e.billId()); // retries or connector replays: skippedProducer: acks=all, min.insync.replicas=2 with RF 3, idempotence (default since 3.0). Consumer: disable auto-commit if processing isn't synchronous within the poll loop.
Running an outbox and Kafka transactions
- Ordering: Debezium reads the WAL in commit order and uses the
keycolumn as the Kafka key. Two concurrent transactions for one account are ordered by commit; lock the account row if business order matters. - Cleanup: Debezium reads the WAL, not the table, so you can
INSERTthenDELETEin the same transaction: the WAL still has the insert, and the table stays nearly empty. Or delete rows older than N hours in batches. - Polling relay (no CDC):
SELECT ... WHERE published_at IS NULL ORDER BY id LIMIT 500 FOR UPDATE SKIP LOCKED, send to Kafka, markpublished_at. Easier to set up; more DB load, and parallel relays can reorder events. - Kafka transactions: a fixed
transactional.idper instance,initTransactions(), thenbeginTransaction(),send(),sendOffsetsToTransaction(),commitTransaction(). An older instance with the sametransactional.idis fenced. - When several services change data together you need a saga, not just an outbox.
4. Working with AI
Hand to AI: the outbox migration, the Debezium Outbox Event Router config, tests that kill the service between the two writes.
Check in AI-written code:
- No
kafkaTemplate.send()inside@Transactionalas the consistency mechanism. - State and the outbox row are written in the same transaction.
- Consumers with side effects block duplicates with a unique constraint, in the same transaction.
- The Kafka key is the business id that needs ordering (
account_id). - The producer uses
acks=allwith idempotence; the consumer commits after processing.
5. Exercises
Exercise 1: Review "consistency via @Transactional"
The AI wrote this, saying "it's transactional, so the DB and Kafka always match". Find the bug, name a test that proves it, fix it.
@Transactional
public void pay(Bill bill) {
balances.debit(bill.accountId(), bill.amount());
kafkaTemplate.send("bill-events", bill.accountId(), new BillPaid(bill.id()));
bills.markPaid(bill.id());
}Solution to Exercise 1
send() publishes while the transaction is still open. If markPaid throws (or the commit fails), the DB rolls back but BillPaid is already in Kafka: another service marks an unpaid bill as paid. Conversely, a Kafka failure after the DB commit loses the event.
Test: Testcontainers PostgreSQL + Kafka, make markPaid throw, assert the topic has no BillPaid: it fails.
Fix: a transactional outbox. INSERT INTO outbox in the same transaction as debit and markPaid, Debezium publishes; the bill-events consumer is idempotent on bill.id().
Exercise 2: Read an out-of-order incident
A consumer shows account A as ACTIVE although the last event was FROZEN. The producer log shows two events sent 3 ms apart with key null. The topic has 12 partitions. Diagnose and fix.
Solution to Exercise 2
Diagnosis: a null key put the two events in different partitions (the sticky partitioner picks per batch). Kafka only orders within a partition; the consumer of the partition holding ACTIVE ran slower and overwrote later.
Fix: key by account_id so every event of A lands in one partition; an idempotent producer so retries don't reorder; sequential processing per partition. Add a safety net: store the event's version and only update when newer (UPDATE ... WHERE version < :v).
Summary
- DB + Kafka share no transaction; use a transactional outbox.
send()inside@Transactionaldoesn't make two writes atomic.- Kafka's exactly-once covers only Kafka → Kafka; sinks need idempotent consumers.
- No loss:
acks=all, retries, idempotence; commit after processing. - Order exists only within a partition: same key, sequential processing.
Read more: Part 1: Partition count, large messages, lag and long-running tasks.
Practice interview questions on this topic
- What ordering does Kafka guarantee, and how do you make an order's events get processed in order end to end?
- What is the dual write problem, and how do you publish an event after a DB write without divergence (transactional outbox, CDC)?
- acks=0/1/all, retries and the idempotent producer: how do you configure Kafka to neither lose nor duplicate messages?
- How do Kafka transactions and exactly-once work under the hood, and why must a consumer writing to a DB still be idempotent?
Comments
Community rules