Dev Learning Lab

The labs on this site need JavaScript to run. The same content is written out below.

Learn › Architecture and operations › Splitting into services

Saga and outbox

When every service has its own database, how do you get "all succeed or all cancel"?

Why it exists — With one DB, one transaction can achieve "all succeed or all cancel", but if each service has a different DB, a single rollback cannot undo another service's commit. A saga gets the result consistent not by a rollback but by running, in reverse, operations that cancel the steps already finished, and an outbox stores the message to send in the same transaction as the business data, so that saving and publishing do not fall out of step.

Where it's used today — In a trip booking where separate services handle flights, hotels, and payment, or in a shopping mall where the DB is split per service, functions that undo a step, such as payment cancellation and seat return, are built in advance and used. The outbox table is read periodically by a separate job and sent to a message broker such as Kafka, or a CDC tool such as Debezium reads the DB's change log and sends it. For services that share one DB, an ordinary transaction is enough.

When ordering, payment, inventory, and shipping are split into services that each have their own database, you cannot wrap them in one database transaction. If a step fails partway through, you must run separate actions that undo the steps that already finished (the saga pattern). Also, if the server dies between saving to the database and publishing a message, the two get out of sync (the problem that the transactional outbox pattern solves).

Checked against real execution · Ran all 24 combinations (seven distinct cases) with the four services as separate Spring Boot 4.1.1 processes, a separate MySQL 8.4.11 database per service, and Kafka 4.1.1 (Spring for Apache Kafka 4.1.1), comparing the rows in each database and the order of compensations, and the orders, outbox rows, Kafka messages and receiver records after killing the server with Runtime.halt and starting it again

Concepts in this lab

Distributed transactions and the saga pattern
The problem of handling work that spans several services (or databases) as if it were a single transaction. When each service has its own database, the work cannot be wrapped in one local transaction. Two-phase commit (2PC) can tie several databases together, but its burden on availability and coupling is heavy, so it is rarely used in microservices. In the saga pattern, each service commits its own work in turn, and if a step fails partway, compensating transactions that cancel the already completed work are run to restore consistency.
Compensating transaction
Where it's used today — Even in an application that has only one service, when saving to its own database fails after it has called an external payment API, it calls the payment cancellation API to bring things back in line. Because a compensating action can also fail, it is retried or left on a list for a person to handle.
A separate operation that is run to undo the effect of work that has already been committed. Unlike a database rollback, it is a new transaction that performs the opposite action (for example, canceling a payment or restoring stock). In the saga pattern, it is used to cancel the earlier steps when a failure occurs.
Transactional outbox pattern
Where it's used today — It is used where an event must be delivered to another service after a database save, such as a shopping mall where the inventory and shipping services must be notified once an order is saved. Because the publishing side may send the same message again, the receiving side must filter out what it has already processed by message ID.
A pattern for making a database change and a message publication succeed together. Instead of publishing the message directly, the application saves the message to be sent in a separate table (the outbox) in the same transaction that changes the business data. Later, another process reads this table and publishes the messages to the message broker. This prevents the inconsistency where the change is in the database but the message was never published.
Message delivery guarantees
The level of guarantee about how many times a message is delivered. With at-most-once, a message is delivered at most one time, so there are no duplicates but messages can be lost. With at-least-once, a message is delivered at least one time, so nothing is lost but duplicates can occur. With exactly-once, a message is delivered exactly one time. In practice, systems often use at-least-once and make the consumer handle duplicates (idempotent).
Eventual consistency
The guarantee that, although some nodes may show the old value right after data changes, all nodes end up with the same value over time if no further changes are made. It gives up immediate consistency and gains availability and scalability in return. It is commonly adopted in distributed databases and for synchronizing data between microservices.

Try these

Running with the default settings

  1. The user places an order. Each of the four services commits its work to its own database, and when it finishes, it notifies the next service with an event. There is no single transaction that wraps the whole thing.
  2. Step 1 Order service: Create order completed. It commits to its own database and publishes an event for the next step.
  3. Step 2 Payment service: Approve payment completed. It commits to its own database and publishes an event for the next step.
  4. Step 3 Inventory service: Deduct inventory failed. The local transaction of this service is rolled back, so no row written by this step remains, and this service publishes a failure event. The earlier steps are already committed in their own databases, so a database rollback cannot undo them.
  5. Compensation 1: Payment service receives the Inventory service's failure event and runs the compensation: Refund payment. This undoes the work that was already committed with a new action that cancels it. After committing the compensation, it publishes a compensated event to tell the step right before it, so the compensations go in the reverse of the order in which the steps ran.
  6. Compensation 2: Order service receives the Payment service's compensated event and runs the compensation: Cancel order. This undoes the work that was already committed with a new action that cancels it. This is the first step, so the compensations end here.
  7. All the compensations are finished. The order is in the canceled state, and the data is consistent again. But until the compensations finished, an inconsistent state such as "payment went through but the order failed" existed for a short time.

Result of this run

Code

// Not Java code: a list of the steps and their compensations
// Each step is committed as a local transaction of its own service
1. Order service       Create order (PENDING)      Compensation: cancel the order
2. Payment service     Approve payment             Compensation: cancel the payment (refund)
3. Inventory service   Deduct inventory            Compensation: restore the inventory
4. Shipping service    Request shipping            (last step)

// When a step finishes, it commits and publishes an event that calls the next step
// When shipping is requested, the order service receives that event and confirms the order
// When a step fails, its service publishes a "failed" event,
// the step right before it receives that event, compensates, and publishes a "compensated" event.
// The step before that receives it and compensates in turn, so the steps are undone in reverse order

Assumptions of this model

The saga is drawn in the style where the services exchange events to move forward (choreography). There is also a style where a central orchestrator tells each step what to do (orchestration), and the principle of the compensations is the same. It is simplified so that a compensation always succeeds. The definitions of the patterns follow the explanations in the microservices pattern literature (microservices.io). The results were checked by actually running them. For the saga, the four services were separate Spring Boot 4.1.1 processes, each with its own database in MySQL 8.4.11, exchanging events through Kafka 4.1.1 and Spring for Apache Kafka 4.1.1, and all four cases were run. The failures were made with an insufficient balance, zero inventory, and a region that is not shipped to, and the rows and timestamps in each database confirmed that the row written by the failed step was rolled back and that the compensations were committed in the reverse of the order in which the steps ran. For the outbox, the code on the screen (JPA repositories, @Transactional, KafkaTemplate, a @Scheduled relay) was run as it is, the server dying was made by ending the process with Runtime.halt at a fixed point, and the service was started again to check the result. The moment when the server dies is fixed at the most problematic point. When publishing before the commit, KafkaTemplate.send is asynchronous, so the process waited with flush() until the broker received the message and was then killed. When it was killed right after send without waiting, in all 3 runs the message never reached the broker and neither the order nor the message remained. It was also confirmed by running it that if the relay dies after sending a message and before saving the mark, the same message goes out once more when it starts again, and the other service receives it twice.

Previous lab: Circuit breaker · Next lab: Gateway and gradual migration

Concepts in this lab

What this lab shows

Settings

Code


      
    

Diagram

Run comparison

Try these