Senior
Tell about the Outbox pattern for guaranteed message delivery.
sobes.tech AI
Answer from AI
The Outbox pattern is used to guarantee message delivery between microservices or components, especially when ensuring atomicity of data recording and message sending.
Idea:
- Instead of immediately sending a message to the broker, the service records the event (message) in a special "outbox" table within the same transaction where business data is changed.
- A separate process or thread periodically reads new messages from the outbox table and sends them to the messaging system.
- After successful sending, the message is marked as sent or removed from the table.
This ensures that the message is not lost and will not be sent twice, as the record in the outbox and the data change occur in a single database transaction.
Example:
// In a transaction
updateOrderStatus(orderId, "PAID");
insertOutboxMessage(orderId, "OrderPaidEvent");
// Separate process
List<Message> messages = fetchUnsentOutboxMessages();
for (Message msg : messages) {
sendToMessageBroker(msg);
markMessageAsSent(msg);
}
This is a reliable way to integrate with asynchronous systems, minimizing data loss and desynchronization.