A service must save an order in its database and publish an order-placed event. How do you make sure neither happens without the other?
Sketch your own answer first, then compare it with the one below.
A strong answer
Writing to the database and then to the broker is two writes with no shared transaction, so a crash between them leaves one without the other. Retrying does not close the gap, because the crash can come before the retry.
Use a transactional outbox. In the same database transaction that inserts the order, insert a row describing the event into an outbox table. Both commit or neither does. A separate relay then reads unsent rows, publishes them and marks them sent. Change-data-capture tools can do the same job by reading the database log.
If the relay crashes after publishing and before marking, it publishes the event again. So the pattern gives at-least-once publishing, not exactly once. Give every outbox row a stable id, put it in the event, and let consumers use it as an idempotency key.
Operationally, delete or archive sent rows so the polling query stays fast, and publish in write order with the order id as the key if events for one order must stay ordered.
Sources
- Chris Richardson (2018). Transactional outbox.
- Martin Kleppmann (2017). Designing Data-Intensive Applications.