Every event-driven system eventually meets the same bug. An order is saved, but the OrderCreated event never reaches Kafka. Or the event reaches Kafka twice, and the customer is charged twice.

Neither bug shows up in a happy-path test. They appear when a process crashes at the wrong millisecond, or when the broker is unavailable for a few seconds. To see them, you have to cause those failures on purpose.

That is what outbox-demo does. It is a small Java project with no dependencies. Kafka and the database are simulated with plain classes, so you can run it with javac and watch every step in the log. It runs five scenarios: a normal flow, a relay crash, a consumer crash, a temporary broker failure, and a permanent one. Five orders go in, four payments come out, and no payment is ever created twice.

This article walks through the two patterns that make that true: the transactional outbox on the producer side and the idempotent consumer on the receiving side.

👉 Diagrams of the whole flow: https://josesaid.github.io/outbox-demo/diagrams/workflow-english.html

The problem: two systems, one decision

Here is the code most of us write first:

// ❌ The dual write @Transactional public void createOrder(Order order) { orderRepository.save(order); // 1. database kafkaTemplate.send("orders.events", order.getId(), // 2. broker new OrderCreated(order)); } 

It looks atomic because it sits inside @Transactional, but it is not. The annotation covers the database only. Kafka is a separate system with its own failure modes:

  • The send fails after the save. The order exists, but no service ever hears about it. No payment, no shipment, no email.
  • The send succeeds and the database commit fails. Downstream services process an order that does not exist.
  • The send times out but actually succeeded. Your retry publishes the event a second time.

Moving the send after the commit only changes which of these bugs you get. You cannot make a database and a broker agree with a single local transaction. That is the dual-write problem.

The fix is to stop writing to two systems at once. Write to one system, the database, and let a separate process move the data to the other system.

The solution: outbox on one side, idempotency on the other

The full flow has three parts:

  1. OrderService writes the order and an event row into an outbox table, in one database transaction. It never talks to Kafka.
  2. OutboxRelay runs on its own schedule. It reads pending rows from the outbox, publishes them to Kafka, and marks them as sent.
  3. PaymentConsumer reads from Kafka. It records each eventId in a processed_events table in the same transaction as the payment, and commits the Kafka offset only after that transaction commits.

The relay gives you at-least-once delivery. An event is never lost, because it stays in the outbox until Kafka confirms it. But an event can be published more than once, because the relay can crash after Kafka accepts the message and before it marks the row as sent.

The consumer is what turns at-least-once delivery into exactly-once effect. A duplicate arrives, the consumer recognizes its eventId, and it does nothing.

Every event moves through these states in the outbox table:

NEW ──► PROCESSING ──► SENT │ └──► FAILED ──► PROCESSING ──► ... (retried on the next run) │ └──► DEAD (attempts = MAX_ATTEMPTS = 3) 

Step 1: save the order and the event together

This is the whole producer. Note what is missing: there is no Kafka client here.

public String createOrder(String customer) { String orderId = "ORD-" + UUID.randomUUID().toString().substring(0, 8); // A unique ID for THIS event. The consumer uses it to detect duplicates. String eventId = "EVT-" + UUID.randomUUID(); db.beginTransaction(); try { // 1) The business change. db.insertOrder(orderId, customer); // 2) The event, in the SAME transaction. Nothing goes to Kafka yet. OutboxEvent event = new OutboxEvent(eventId, orderId, "OrderCreated", "{orderId=" + orderId + ", customer=" + customer + "}"); db.insertOutboxEvent(event); db.commit(); } catch (RuntimeException ex) { // The order AND the event are rolled back together. db.rollback(); throw ex; } return orderId; } 

Because both inserts share one transaction, there is no state where the order exists without its event, or the event exists without its order. The dual write is gone, and both writes now depend on one database commit.

The eventId is generated here, once, and travels with the event all the way to the consumer. That ID is what makes deduplication possible later.

Step 2: the relay publishes at least once

public void publishPendingEvents() { List<OutboxEvent> pending = db.findPendingOutboxEvents(); for (OutboxEvent event : pending) { // 1) Claim the row so another relay instance does not publish it too. db.markOutboxEventAsProcessing(event.eventId); // 2) Send. The aggregateId is the key, so one order's events stay in order. try { kafka.send(event.aggregateId, event.eventId, event.payload); } catch (RuntimeException ex) { int attempts = db.markOutboxEventAsFailed(event.eventId, ex.getMessage()); if (attempts >= MAX_ATTEMPTS) { db.markOutboxEventAsDead(event.eventId); // stop retrying } continue; // retry on the next run } // 3) Kafka accepted it. Mark it so it is not published again. db.markOutboxEventAsSent(event.eventId); } } 

Three details matter here.

The gap between step 2 and step 3. If the process dies after kafka.send and before markOutboxEventAsSent, the row stays in PROCESSING. The next run picks it up and publishes it again. You cannot close this gap, because Kafka and your database still do not share a transaction. The outbox doesn't prevent duplicates. It guarantees that nothing is lost, and it leaves deduplication to the consumer.

The message key. Using the orderId (the aggregate ID) as the Kafka key sends every event for one order to the same partition, so consumers see them in the order they were written.

The retry limit. Without MAX_ATTEMPTS, an event that can never be published is retried forever. After three failures the demo marks it DEAD and moves on. In production, a DEAD row should trigger an alert, and someone should look at it.

Step 3: the consumer skips what it has already done

public void handle(int offset) { FakeKafka.Record record = kafka.read(offset); db.beginTransaction(); try { // Idempotency check, done as an INSERT. processed_events.event_id is UNIQUE. boolean isNew = db.insertProcessedEvent(record.eventId); if (!isNew) { // Already processed. Do nothing, but move past the message. db.rollback(); kafka.commitOffset(offset); return; } // The business work, in the SAME transaction as the insert above. db.insertPayment(record.key); db.commit(); } catch (RuntimeException ex) { db.rollback(); // undoes the processed_events row AND the payment throw ex; } // Only now tell Kafka this message is done. kafka.commitOffset(offset); } 

The SQL behind it is short:

CREATE TABLE processed_events ( event_id VARCHAR(64) PRIMARY KEY, -- the UNIQUE constraint does the work processed_at TIMESTAMP NOT NULL DEFAULT now() ); -- inside the consumer transaction INSERT INTO processed_events (event_id) VALUES (:eventId) ON CONFLICT (event_id) DO NOTHING; -- 0 rows affected = duplicate 

Two decisions make this correct.

The check is an insert, not a select. A SELECT followed by an INSERT has a race: two consumers can both see "not processed" and both charge the customer. The database's unique constraint gives you an atomic check. Only one transaction can insert a given event_id.

The offset is committed last. If the consumer crashes after the database commit and before the offset commit, Kafka redelivers the message. That is fine, because the event_id is already in processed_events and the redelivery is skipped. If you commit the offset first and then crash, the message is gone and the payment never happens.

The five scenarios

Main runs all five scenarios in one process, so you can read the log from top to bottom:

Scenario Injected failure What protects it Result
A · Alice None — 1 payment
B · Bob The relay publishes, then crashes before marking SENT The duplicate on offset 2 has the same eventId and is skipped 1 payment
C · Carol The consumer commits to the database, then crashes before the offset commit The redelivery finds the eventId in processed_events 1 payment
D · Dave Kafka fails twice FAILED → FAILED → SENT across three relay runs 1 payment
E · Eve Kafka always fails DEAD after three attempts, no more retries No payment

The final line of the log:

Payments created: 4 (expected 4: Alice, Bob, Carol, Dave; Eve never reached Kafka) 

Kafka received five messages for four orders, plus one redelivery. The database holds exactly four payments.

Common mistakes

  • Treating @Transactional as covering Kafka. It covers the database only. A KafkaTemplate.send inside it is still a dual write.
  • Deduplicating by business key alone. "Has this order been paid?" breaks as soon as one order legitimately produces two events. Deduplicate by a unique event ID created once by the producer.
  • Checking with SELECT, then inserting. Under concurrency, two consumers can pass the check. Let a unique constraint decide.
  • Committing the offset before the database. One crash in between loses the message for good.
  • Retrying forever. A poison event blocks nothing in this demo, but in a real relay it consumes every run. Cap attempts and alert on DEAD.
  • Letting the tables grow without limit. Delete or archive SENT outbox rows, and expire processed_events rows once Kafka can no longer redeliver them (longer than your topic's retention).

Taking it to production

Each simulated class maps to a real component:

  • FakeDatabase → PostgreSQL or MySQL with real transactions.
  • OutboxRelay → a @Scheduled job that selects with FOR UPDATE SKIP LOCKED, so several instances can share the work. Alternatively, use Debezium to stream the outbox table through change data capture, so you don't need a polling job.
  • FakeKafka.send → KafkaTemplate.send(topic, key, payload), with the eventId in a header.
  • PaymentConsumer.handle → a @KafkaListener with manual acknowledgment (ack.acknowledge() after the commit).

Two performance notes. Polling adds latency equal to the polling interval, so tune it, or switch to CDC if you need near real-time delivery. And the processed_events insert adds one indexed write per message, which is a small price compared with a double charge.

Conclusion

You cannot make a database and a broker commit together, so don't try. Split the guarantee in two:

  • The outbox makes sure every committed change produces an event that is eventually published. Nothing is lost.
  • The idempotent consumer makes sure every event takes effect once. Duplicates are harmless.

Together they give you at-least-once delivery with an exactly-once effect, using only the database transactions you already have.

The code is about 600 lines of plain, heavily commented Java. Clone it, run it, and break it in new ways:

git clone https://github.com/josesaid/outbox-demo.git cd outbox-demo javac -d out $(find src -name "*.java") java -cp out com.mx.development.jose.said.Main