How it works
A service that saves an order and publishes an OrderPlaced event is making a dual write: two writes with no transaction across them. Commit first, then crash before publishing, and the order exists but billing never hears about it. Publish first, then have the commit fail, and billing charges for an order that does not exist. A try/catch does not help, because a crash skips the catch and a publish timeout does not say whether the broker got the message.
The transactional outbox takes the second write out of the request path. In one transaction, the service inserts the order and a row in an outbox table holding an event ID, order ID, and payload. Either both commit or neither does. A separate relay then reads unsent rows, publishes each one, and marks it sent.
Order 812 commits with its outbox row. The relay publishes the event, the broker acknowledges, and the relay dies before marking the row. On restart it publishes again. So the outbox gives at-least-once delivery, and consumers must deduplicate by event ID. In exchange, nothing committed is lost.
The costs are a relay to run, polling load on the database, delay up to the polling interval, and a table to prune. Publishing with the order ID as key keeps each order’s events in sequence. IDs are assigned before commit, so a poller that tracks only the highest ID seen can skip a row that commits late; select by unsent status instead. Notification System uses this handoff for receipts and News Feed for fanout.
A teammate proposes keeping the direct Kafka publish but deleting the order row whenever the publish throws an error. They say this keeps the code simple and avoids running a relay. How do you respond?
A crash skips the error handler and leaves an order with no event. A timeout throws even when the broker received the message, so the handler deletes a valid order whose event is already on its way. Choose the outbox: it adds a relay to operate, but the order and its event then commit together.
Use this as a guide for self review; written answers are not graded.Keep in mind
- A dual write has no atomic boundary, so a crash between the writes leaves the systems disagreeing.
- An outbox row commits with the business change, so its event is neither lost nor invented.
- The relay can publish twice, so consumers deduplicate by event ID.