Sobes.tech
Middle

Microservices: how to implement distributed transactions across multiple microservices with rollback capability? What are Saga and Outbox patterns?

sobes.tech AI

Answer from AI

Distributed transactions in a microservices architecture are a complex task because each service manages its own database and there is no single ACID transactional context. To ensure consistency with rollback capabilities, patterns like Saga and Outbox are used.

Saga is a sequence of local transactions across different services, each publishing an event for the next. If one transaction fails, compensating transactions are executed to rollback previous steps. There are two types of Sagas:

  • Choreography: services exchange events directly.
  • Orchestration: a centralized coordinator manages the execution of steps.

Outbox pattern solves the problem of atomicity of data recording and message sending. Instead of sending a message immediately upon data change, the service writes the event to a special "outbox" table within the same transaction as the business operation. A separate process then reads this table and sends messages to the queue, ensuring that messages are not lost and not sent twice.

An example of a simplified Saga:

  1. Service A creates an order and publishes the "OrderCreated" event.
  2. Service B reserves the product; if successful, it publishes "InventoryReserved".
  3. Service C initiates payment; if it fails, it publishes "PaymentFailed".
  4. On error, compensating operations are triggered (cancel reservation, cancel order).

This approach achieves consistency without global transactions.