Transactional outbox
Close the gap between a database commit and a message publish.
The problem and the pattern
Saving a booking and then publishing to a broker can lose the event if the process crashes between the two operations. Write the booking and an outbox row in one database transaction. A separate dispatcher publishes the row and records delivery. A crash after publish can still cause duplicate delivery.
Follow the flow
Make it concrete
This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.
BEGIN;
INSERT INTO bookings(id, tenant_id) VALUES ($1, $2);
INSERT INTO outbox(id, kind, payload)
VALUES ($3, 'BookingReserved', $4);
COMMIT;
-- A dispatcher later claims and publishes pending rows.Trade-offs
- No distributed transaction is required between DB and broker.
- The dispatcher needs locking, retry limits, and lag monitoring.
- Retention and deduplication windows must support the replay policy.
When to avoid it
Avoid an outbox when no external effect must be coupled to a local commit.
Your turn
The dispatcher crashes after broker acknowledgement but before marking the row sent. What must the consumer support?
Reveal a worked answer
The row can be published again. Make the consumer idempotent using event IDs and a durable deduplication record committed with its effect. The outbox prevents lost publish intent, not all duplicate deliveries.