Tutorials Microservices Mastery
The Outbox Pattern: Ensuring 100% data consistency
On this page
The Outbox Pattern
The Outbox Pattern solves a critical bug in distributed systems: Dual-Writes. If you save an order to the DB and then send an email, what happens if the network dies *between* those two steps? You either have an order with no email, or an email for an order that failed. The Outbox ensures they happen atomically.
1. How it Works
- You create a table in your database called OutboxMessages.
- In a single SQL Transaction, you save your
Orderand you save theOrderCreatedEventinto the Outbox table. - A background process (Worker) polls the Outbox table and publishes the messages to RabbitMQ.
- Once published, the worker marks the message as 'Processed' or deletes it.
2. Why is this superior?
Because the Outbox is in the **Same Database** as your business data, the SQL transaction guarantees that you will never have an event without the corresponding data. Reliability becomes 100%.
4. Interview Mastery
Q: "What is the 'Inbox' pattern, and why is it used alongside the 'Outbox'?"
Architect Answer: "The **Inbox Pattern** is used by the *Consumer*. When a message arrives, the consumer saves it to an 'Inbox' table before processing. If the consumer crashes halfway through, it can restart and see that the message is in the Inbox but not yet processed. It also prevents processing the same message twice (Idempotency) because it can check if the MessageID already exists in the Inbox table."