Junior — Middle
What is the main purpose of the Outbox pattern in system architecture?
sobes.tech AI
Answer from AI
The Outbox pattern is used to ensure reliable delivery of messages or events in distributed systems, especially when integrating with external services or microservices.
Main idea:
- All state changes (e.g., database writes) and related events are recorded in a single transaction.
- Instead of immediately sending messages at the moment of data change, events are stored in a special table — the "outbox".
- A separate process or service periodically reads this table and sends events to a message queue or other consumers.
This helps avoid issues with data consistency and message loss during failures, as the database write and event saving occur atomically.
Example of usage in C# (simplified):
using (var transaction = dbContext.Database.BeginTransaction())
{
// Change data
dbContext.Orders.Add(newOrder);
// Add event to outbox
dbContext.OutboxEvents.Add(new OutboxEvent {
EventType = "OrderCreated",
Payload = JsonConvert.SerializeObject(newOrder),
CreatedAt = DateTime.UtcNow
});
dbContext.SaveChanges();
transaction.Commit();
}
// A separate service reads OutboxEvents and sends them to the queue