What you'll learn: By the end of this lesson you will be able to explain the dual-write problem and its two failure orders, design an outbox table and a relay, say why the relay delivers at least once and what the consumer must do about it, state what ordering the pattern keeps, and read a lab that runs both failure orders and the outbox against H2 and an in-process Kafka broker.
A shop assistant sells a cake and must also tell the delivery depot. Phoning the depot first is risky: if the till then jams, the depot sends a van for a sale that never happened. Ringing the sale up first is risky too: if the assistant is called away before phoning, the cake is sold and nobody delivers it. There is no way to do two separate things, on a till and on a telephone, as one act.
The fix is to write the delivery slip on the same ledger page as the sale, so the two are one entry, and have a runner collect slips and phone the depot. If the runner phones twice about one slip, the depot must cope. That is the transactional outbox. Distributed Transactions: 2PC and Sagas gives it a section; this lesson is the dedicated treatment, and the partner of Saga: Orchestration vs Choreography, where every service needs it to publish events.
Verified with Spring Boot 4.1.2, Kafka clients and the in-process broker from spring-boot-starter-kafka-test, and Java 25 as the compile target, on 2026-12-01.
The core idea
A service that must change its database and publish a message cannot do both atomically, because they are two systems. The outbox makes the message a row: the service inserts it into an outbox table in the same local database transaction as the business change, and a separate relay reads committed rows and publishes them. The message is sent if and only if the transaction commits, and the relay's delivery is at least once.
Three illustrations run through the lesson, each labelled:
- Minimal example: an order placed in H2 and an event sent to Kafka, with each failure injected, in the lab.
- Realistic example: ShopStream's order service publishing
OrderPlaced, in "In practice". - Failure example: a relay that dies after publishing and before marking the row sent, which duplicates the event.
The dual-write problem
The microservices.io description of the pattern states the requirement plainly: a service must "atomically update its database and publish a message/event", and it cannot use "the traditional mechanism of a distributed transaction that spans the database and the message broker". The AWS guidance gives the two failures. If the database update succeeds and the notification fails, downstream services never learn of the change; if the update fails but the notification goes out, downstream services act on something that did not happen.
Figure 1. Two orders of a dual write, two failures. How to read this: commit-first can lose the event; publish-first can announce something that never happened, a ghost event. Retrying does not help, because the process that must retry is the one that died.
No order of the two writes is safe. What is missing is atomicity across two systems, and the outbox gets it by reducing the problem to one system.
The outbox: the message becomes a row
Figure 2. The outbox. How to read this: the service talks only to its own database. The relay is a separate loop that moves committed outbox rows to the broker. The two failure orders of Figure 1 cannot occur, because the event and the change commit or roll back together.
The outbox table needs few columns. The one in the lab has an increasing id (it doubles as the event id and the order of publication), an aggregate_id (the order id, used as the Kafka record key), a type and a sent flag. The Debezium outbox event router expects a similar shape by default: an event id, an aggregate type, an aggregate id ("important for maintaining correct order in Kafka partitions") and a payload. Its page also expects the outbox table to be insert-only: "an outbox table functions as a queue; updates to records in an outbox table are not allowed". That suits a log-tailing relay; the lab's polling relay marks rows sent, which is an update.
Here is the service side, from the lab. Inserting the order, inserting the outbox row and taking stock are three statements in one TransactionTemplate callback:
public void placeWithOutbox(String orderId, String sku) {
tx.executeWithoutResult(status -> {
insertOrder(orderId, sku);
insertOutbox(orderId, "OrderPlaced");
takeStock(sku);
});
}
The Spring reference recommends TransactionTemplate for programmatic transaction management in imperative code, with a callback that rolls back when it calls setRollbackOnly(), and by default Spring rolls a transaction back on a RuntimeException or Error. In the lab the third statement violates a CHECK (quantity >= 0) constraint for an out-of-stock item, the exception escapes the callback, and the order row and the outbox row both roll back.
The relay and what it guarantees
The relay is a loop. The lab's is a polling relay, which microservices.io lists next to a transaction-log tailing relay; the later lesson on change data capture covers the second kind.
public int runOnce(Crash crash) {
List<Row> rows = jdbc.sql("select id, aggregate_id, type from outbox where sent = false order by id")
.query((rs, n) -> new Row(rs.getLong(1), rs.getString(2), rs.getString(3))).list();
for (Row row : rows) {
publisher.send(row.aggregateId(), row.type(), Long.toString(row.id()));
crash.check(Crash.Point.BETWEEN_PUBLISH_AND_MARK_SENT);
jdbc.sql("update outbox set sent = true where id = ?").param(row.id()).update();
}
return rows.size();
}
Three properties follow from this order of steps.
It reads only committed rows. A row inside an uncommitted transaction is invisible to the relay, so rolled-back events never appear. The AWS page makes the same point: the event processing service "recognizes only those rows that are part of a committed (successful) transaction".
It publishes in outbox order. Rows are read order by id, so two events for one order reach the topic in commit order, provided one relay publishes them and the topic key is the order id (the same key lands in the same partition, and the Kafka documentation describes a topic as a set of totally ordered partitions). The AWS guidance lists order of notification as an issue to preserve, with sequence numbers or timestamps.
It delivers at least once, never less. The relay publishes and then marks the row sent. A death between the two leaves the row unsent, and the restart publishes it again. Marking first would invert that: a death after the mark and before the publish would lose the event, which is at-most-once. The microservices.io page names this duplicate and says consumers must be idempotent.
The Kafka producer's idempotence does not help here. Its Javadoc limits the guarantee to "messages sent within a single session" and warns that application-level re-sends "cannot be de-duplicated". A restarted relay is a new session, so the consumer must recognise the duplicate by the event id in the header.
Figure 3. The duplicate. How to read this: both publishes are legitimate from the relay's point of view, because the row was never marked. Only the event id, the outbox row id, tells the second from a new event.
Build it: three ways to tell Kafka about an order
This is the minimal example, a lab you can run. The database is H2 in memory, and the broker is a real Kafka broker started in the test JVM by @EmbeddedKafka, which the Spring Kafka reference describes as using KRaft in combined controller and broker mode. There is no Docker. The producer uses acks=all and enable.idempotence=true, and the consumer's seen-set is in memory; a real consumer stores the id in the same transaction as its effect, as in Delivery Guarantees.
Goal. See the lost and ghost events of a dual write, then the outbox remove both and show its one remaining cost.
Setup. From the repository's examples/spring-labs folder:
cd examples/spring-labs && ./gradlew :labs:transactional-outbox:test
The command runs 6 tests: five behaviour tests plus a golden test that compares the report with examples/spring-labs/golden/transactional-outbox.txt. The code is under examples/spring-labs/labs/transactional-outbox/src/main/java/buildingai/labs/outbox/.
Runs 1 and 2: the dual write fails both ways
Run 1 commits and then dies before publishing; run 2 publishes inside the transaction and then fails on a later statement (saffron has no stock):
Expected output, captured from a real run (runs 1 and 2):
Run 1. Dual write, publish after commit. The process dies between the commit and the publish (order o-1, milk).
crash : process died BETWEEN_COMMIT_AND_PUBLISH
database : orders=[o-1:PLACED]
topic : []
verdict : the order exists and no event was ever published (LOST EVENT)
Run 2. Dual write, publish inside the transaction. The stock update after it fails (order o-2, saffron).
failure : DataIntegrityViolationException, the transaction rolled back
database : orders=[]
topic : [o-2 OrderPlaced]
verdict : an OrderPlaced event for an order that does not exist (GHOST EVENT)
Runs 3 and 4: the same failure through the outbox, and the normal path
Run 3 repeats the failing saffron order, this time through the outbox. Run 4 places an order, pays it and places a second, then runs one relay pass:
Expected output, captured from a real run (runs 3 and 4):
Run 3. Outbox, the same failing saffron order (o-3).
failure : DataIntegrityViolationException, the transaction rolled back
database : orders=[] outbox=[]
relay : published 0 row(s)
topic : []
verdict : the order and its event both rolled back; nothing to publish
Run 4. Outbox, the normal path: place o-4, pay o-4, place o-5 (all milk), then one relay pass.
before : orders=[o-4:PAID, o-5:PLACED]
outbox=[1:o-4:OrderPlaced:unsent, 2:o-4:OrderPaid:unsent, 3:o-5:OrderPlaced:unsent]
relay : published 3 row(s)
after : outbox=[1:o-4:OrderPlaced:sent, 2:o-4:OrderPaid:sent, 3:o-5:OrderPlaced:sent]
topic : [o-4 OrderPlaced (event-id 1), o-4 OrderPaid (event-id 2), o-5 OrderPlaced (event-id 3)]
verdict : events appear in outbox id order, so o-4 OrderPlaced precedes o-4 OrderPaid
After the failure, both tables are empty and the relay has nothing to publish. In the normal path the three events reach the topic in outbox id order, so OrderPlaced for o-4 precedes OrderPaid.
Runs 5 and 6: the relay dies after publishing
Expected output, captured from a real run (runs 5 and 6):
Run 5. Outbox, the relay dies after publishing row 1 and before marking it sent (order o-6, milk).
crash : process died BETWEEN_PUBLISH_AND_MARK_SENT
outbox : [1:o-6:OrderPlaced:unsent]
restart : the relay published 1 row(s) again
outbox : [1:o-6:OrderPlaced:sent]
topic : [o-6 OrderPlaced (event-id 1), o-6 OrderPlaced (event-id 1)]
verdict : the event is on the topic twice (at-least-once), with the same event id
Run 6. The consumer of the topic from run 5.
applies every message : [o-6 OrderPlaced (event-id 1), o-6 OrderPlaced (event-id 1)]
applies each event id once: [o-6 OrderPlaced (event-id 1)]
The restarted relay published row 1 again, so the topic holds the event twice with event id 1. A consumer that applies every message applies it twice; one that remembers event ids applies it once. The outbox moved the problem from "lost or ghost" to "duplicate", which a consumer can absorb.
Stretch. Move the update outbox set sent = true above publisher.send, predict run 5, then restore the code. Run two relays against one outbox and describe what goes wrong.
What the lab leaves out. A log-tailing relay, several relay instances, cleanup of sent rows, several partitions, a durable consumer-side dedupe table, and a broker that is down (the lab's relay would throw and stop at that row).
Trade-offs
| Option | Gain | Cost | Wrong when |
|---|---|---|---|
| Dual write | Simplest code | Lost and ghost events | Anyone depends on the event |
| Outbox with a polling relay | Atomic with the change, plain SQL, no extra infrastructure | At-least-once, polling delay and load, table growth, ordering needs a single relay | You need very low publish latency at high volume |
| Outbox with log tailing (CDC) | No polling, rows read from the database's log | A connector to run, database configuration | The database or the team cannot run one |
| Kafka transactions alone | Atomic inside Kafka | The database write is outside the transaction | The change is in a relational database |
In practice: ShopStream's OrderPlaced event
This is the realistic example, an educational scenario on the course's running example, ShopStream; nothing in it describes a real company. Numbers other than the shared ShopStream figures are illustrative.
This is a realistic scenario, not a case history.
The situation
ShopStream's order service inserts an order and publishes OrderPlaced for the payment and delivery services; the peak target is about 58 checkouts per second, a shared illustrative number. Support has found orders that were charged but never delivered, and one delivered though checkout had failed. The code publishes to Kafka, then updates stock in the same method.
Starting architecture
Figure 4. Today's order service. How to read this: the service writes to two systems with no shared transaction. A failure between or after the two writes leaves them disagreeing, which support sees as charged-but-undelivered and delivered-but-failed orders.
Options considered
| Option | What it gives | Problem |
|---|---|---|
| A. Commit first, then publish, with retries | Removes ghost events, handles broker outages | A crash after the commit still loses the event |
| B. Outbox with a polling relay | Both failures gone, no new infrastructure | Polling latency, a relay to run, duplicates |
| C. Outbox read by log tailing | No polling | A connector and database settings to operate |
The decision
Option B. The order service writes OrderPlaced to an outbox table in the same transaction as the order and the stock change, keyed by order id, with an increasing id as the event id. One relay instance polls every 200 ms (illustrative), publishes in id order with acks=all and idempotence on, and marks rows sent. The payment worker records the event id in the same transaction as its ledger row, so a duplicate is skipped, as in the payments and ledger stage. Sent rows are archived after a retention period so the table stays small. Revisit option C if polling load or latency shows up in the metrics.
Rollout and verification
Ship the outbox write first and keep the old direct publish, with consumers deduplicating on order id, so a comparison job can count orders with no event and events with no order. When both counts are zero for a week, remove the direct publish. Verify with the lab's crash points in staging: a kill between commit and relay, a kill between publish and mark, and a rollback on a failed stock update. In production watch the age of the oldest unsent row, the count of unsent rows, publish failures per minute and duplicates skipped per hour.
The 2 a.m. failure
The page reads: oldest unsent outbox row 14 minutes old, rows growing. The relay is up. The log shows it failing on one row, a payload larger than the broker's message size limit, and because it publishes in id order and stops at a failure, every row behind it waits. The checks: the relay's error for the first unsent row, the size of its payload, and whether it is the only bad row. The mitigation is to move it to a quarantine table by hand so the relay can continue, then replay it after a fix; customers see delayed notifications, not wrong ones. The lasting fix is a bounded retry per row followed by quarantine, an alert on the age of the oldest row rather than the count, and a size check at insert time. This is the head-of-line problem of any ordered queue; Dead-Letter Queues and Retries covers messages that keep failing.
Architect's notes
- Insert the event in the same transaction, always. A row written in a second transaction recreates the dual write.
- The event id is the dedupe key. Assign it once, when the row is written, never in the relay.
- Decide the cleanup. Sent rows grow without bound; delete or archive them.
- Monitor age, not just count. One stuck row blocks an ordered relay.
Common mistakes
- Publishing from inside the transaction. That is the ghost event of run 2.
- Marking the row sent before publishing. A crash then loses the event.
- Assuming the relay is exactly-once. It is at-least-once; the consumer must be idempotent.
- Letting the outbox grow forever. Polls slow down and the table bloats.
Key takeaways
- A database write and a broker publish cannot be atomic; both orders of a dual write fail, one by losing the event and one by announcing a change that never committed.
- The outbox turns the event into a row in the same local transaction, so the event and the change commit or roll back together.
- The relay publishes committed rows in id order and marks them sent afterwards, which makes delivery at-least-once.
- The duplicate is real (run 5): consumers must recognise the event id and apply it once.
- The outbox keeps commit order for events read by one relay and keyed by aggregate; it does not make the consumer's work exactly-once.
Practice exercises
Exercise 1 (30 min). Run the lab and, for each of runs 1 to 5, say what an observer of the topic sees and what an observer of the database sees.
Exercise 2 (45 min). Add an OrderCancelled event with its own outbox row and test that two events for one order keep their order through the relay.
Exercise 3 (1 hour). Add a retention rule that deletes sent rows older than a threshold. Decide what the relay does about a sent row it has not yet seen.
Related reading
- Saga: Orchestration vs Choreography: the paired lesson, where each service publishes events through an outbox.
- Distributed Transactions: 2PC and Sagas: why a transaction cannot span a database and a broker.
- Delivery Guarantees: at-least-once delivery and the idempotent consumer.
- Dead-Letter Queues and Retries: what to do with a message that keeps failing.
- Spring @Transactional: the local transaction behind the outbox write.
- ShopStream Stage 5: The Order Pipeline: the running example.
The other side of this topic
On the client, an at-least-once event is a message that may arrive twice after a reconnect, and a UI that applies it twice shows the wrong count. The front-end treatment is in the lesson on heartbeats, backpressure and delivery guarantees: the same event id, used to drop a repeat.
Official documentation
- microservices.io, Pattern: Transactional outbox: the problem, the solution, duplicates and the two relay kinds.
- AWS Prescriptive Guidance, Transactional outbox pattern: dual-write failures, ordering, duplicates and rollback.
- Debezium, Outbox Event Router: the expected table shape and the insert-only rule for log tailing.
- Apache Kafka 4.2 Javadoc, KafkaProducer: idempotence and its single-session scope.
- Spring Framework reference, Programmatic transaction management and Rolling back a declarative transaction:
TransactionTemplateand the default rollback rule.