outbox-demo · Main.java

Outbox Workflow

How one order becomes exactly one payment, even when the relay, Kafka or the consumer fails halfway through.

The full path of one event

The dashed boxes are database transactions. Everything inside one is saved together or not at all.

OrderService createOrder() 1 transaction orders ORD-… outbox EVT-… NEW INSERT order + event OutboxRelay publishPending…() reads pending marks status Kafka orders.events 0 1 2 3 4 send key=orderId delivers commit offset (last) PaymentConsumer handle(offset) 1 transaction processed_events UNIQUE(event_id) payments 1 per order INSERT eventId + INSERT payment if event_id exists: rollback, SKIP, commit offset
On top, the producer never talks to Kafka. It only writes to its own database, and the relay does the publishing. Below, the consumer records the eventId and creates the payment in the same transaction, and commits the offset only after the database commit. Offset 2 in amber is Bob's duplicate from scenario B.

Event states in the outbox table

The relay moves each row through these states. MAX_ATTEMPTS = 3 in OutboxRelay.

NEW PROCESSING SENT FAILED DEAD claims Kafka accepts Kafka fails attempts = 3 next run, if attempts < 3 relay crash: published again
An event left in PROCESSING (the relay published it and crashed before marking it SENT) goes out again on the next run. That is why Kafka can receive the same event twice, and why the consumer has to be idempotent. A DEAD event is never retried, even after Kafka comes back.

The five scenarios in Main

ScenarioInjected failureKafka offsetsWhat protects itResult
AliceA · normal None 0 — 1 payment
BobB · relay crash The relay publishes and crashes before marking SENT 12 Offset 2 carries the same eventId, UNIQUE rejects it, and the consumer skips it 1 payment
CarolC · consumer crash The consumer commits to the database and crashes before committing the offset 3delivered ×2 The redelivery finds the eventId in processed_events and skips it 1 payment
DaveD · Kafka blip Kafka fails twice 4 FAILED → FAILED → SENT across three relay runs 1 payment
EveE · Kafka down Kafka always fails none On the third attempt it becomes DEAD and retries stop no payment
4 payments5 orders · 5 Kafka messages · 0 duplicate payments