Sobes.tech
Senior

What are Saga and Outbox patterns?

sobes.tech AI

Answer from AI

The Saga and Outbox patterns are used for managing distributed transactions and ensuring data consistency in microservices.

Saga is a pattern that breaks down a long distributed transaction into a series of local transactions, each executed in a separate service. If one of the transactions fails, compensating transactions are executed to rollback changes. There are two types of Sagas:

  • Choreography — services exchange events and decide what to do next.
  • Orchestration — a central orchestrator manages the sequence of steps.

Outbox is a pattern that addresses the problem of atomic data and message recording for integration. Within a single transaction, business data and messages to be sent (e.g., to Kafka) are stored in a special outbox table in the database. A separate process then reads these messages and sends them to the messaging system. This guarantees that the message is not lost and will only be sent after the data has been successfully saved.

Example of using Outbox:

// In a transaction
saveOrder(order);
saveOutboxMessage(orderId, "OrderCreated");

// Separate process
List<Message> messages = readUnsentOutboxMessages();
for (Message msg : messages) {
    kafkaProducer.send(msg);
    markMessageAsSent(msg);
}

Together, these patterns help build reliable distributed systems with guarantees of consistency and message delivery.