Skip to content

Sagas: a business transaction across services

A shop is split into an order service, a stock service, a payment service and a shipping service, and each one owns its database. Placing an order means a change in three of them: reserve the stock, charge the card, create the shipment. Inside one database a transaction makes those changes all-or-nothing. Across four databases there is no such thing by default.

The classic way to get one is two-phase commit, and it is rarely the answer here for two reasons. It blocks: if the coordinator fails after the participants have voted yes, they hold their locks and cannot decide. And not every participant can take part. A payment provider’s HTTP API and a message broker do not offer a prepare step. Richardson’s saga page lists “2PC is not an option” among the forces of this problem, and the Azure Architecture Center says that, because ACID guarantees do not apply directly across independently managed data stores, the saga pattern is often the better fit.

Mental model. A travel agent books a flight, then a hotel, then a car. If the car is not available, there is no way to “un-book” the flight as if it had never been made. The agent cancels the hotel and then the flight, each cancellation being a new request to a different company, perhaps with a fee. The trip ends in a consistent state, but not by a rollback.

A saga is local transactions plus compensations

Section titled “A saga is local transactions plus compensations”

A saga is a sequence of local transactions. Each one is an ordinary ACID transaction inside one service, and when it commits it triggers the next. If a step fails, the saga runs a compensation for each step that had already committed, to undo its effect. Richardson describes it as a sequence of local transactions where a failure leads to compensating transactions that undo the changes made by the preceding ones. The idea comes from Garcia-Molina and Salem’s 1987 paper, which defined a saga as a long-lived transaction that is written as a sequence of transactions that can be interleaved with other transactions, with compensating transactions to amend a partial execution. The paper is about database transactions in a single system; microservices have borrowed the name and the idea.

For the order, the steps and their compensations are:

Step Local transaction Compensation
1 Reserve the stock Release the stock
2 Charge the payment Refund the payment
3 Create the shipment None needed: if it fails, it did not commit

A compensation is a new business action, not a rollback. The charge was committed and the customer’s statement shows it; the refund is a new payment in the other direction, and the statement shows both. A stock release is a new update that puts the units back on sale. The Azure Compensating Transaction page makes the same point: a compensation does not necessarily return the data to the state it had before, and it can apply business rules, as when cancelling a flight does not entitle the customer to a full refund. Some effects cannot be taken back at all, such as an email that was sent. The same page advises designing the workflow so that irreversible steps happen only after all the critical validations have succeeded.

The flow below shows one order in six ways. Choose a variant, press play or step through it, and read the Time until the order is confirmed or cancelled at the end.

An order saga: a step fails and the others are compensated

20 ms
30 ms
20 ms
1 s
5 s
Compare

The order service acts as the orchestrator. It sends one command at a time (reserve stock, charge payment, create shipment) and waits for each reply before it sends the next. This is the happy path, the time every other variant is compared with.

120 ms
  1. Reserve the stock10 ms
    Command ReserveStock(order 42)
    Order service to Stock service: Command ReserveStock(order 42). Arrives at 10 ms.Processing: 20 ms
  2. 40 ms
    Reply: stock reserved
    Stock service to Order service: Reply: stock reserved. Arrives at 40 ms.
  3. Charge the payment50 ms
    Command ChargePayment(order 42)
    Order service to Payment service: Command ChargePayment(order 42). Arrives at 50 ms.Processing: 20 ms
  4. 80 ms
    Reply: payment charged
    Payment service to Order service: Reply: payment charged. Arrives at 80 ms.
  5. Create the shipment90 ms
    Command CreateShipment(order 42)
    Order service to Shipping service: Command CreateShipment(order 42). Arrives at 90 ms.Processing: 20 ms
  6. 120 ms
    Reply: shipment created, order confirmed
    Shipping service to Order service: Reply: shipment created, order confirmed. Arrives at 120 ms.

Time until the order is confirmed or cancelled: 120 ms60 ms of processing

Model notes

Assumptions

  • Each message takes half the round-trip time of the link it crosses. Messages are never lost, never queue and never overlap, and each leaves when the one before it has arrived, once its receiver has finished any processing.
  • An order goes through three local transactions, one per service: reserve stock, charge payment, create shipment. No transaction spans two services, which is why a failure is repaired by compensation and not by a rollback.
  • Orchestration is drawn as a command and a reply between the order service and each other service; choreography is drawn as events through a broker, so each hop crosses the link to the broker. The two use different round-trip controls so that you can compare them.

Simplifications

  • The broker is assumed durable and always available, and every service is assumed to handle a message exactly once. In practice delivery is at least once, so every command, event and compensation must be idempotent.
  • Between the first step and the last, other requests can see the order half-done: reserved stock, a charge not yet refunded. A saga gives atomicity by compensation, not isolation, and this flow does not show how a real system hides or tolerates those intermediate states.
  • A compensation that keeps failing is not drawn beyond one retry; a real saga retries with a growing delay and raises an alert for a person when it cannot finish. The restart delay of a crashed orchestrator is a single number that you set.

Parameter values are illustrative. They are not benchmarks of any real product.

With the defaults, the round trip between the order service and each other service is 20 ms and a service takes 20 ms to handle a message.

  • Orchestration: every step succeeds takes 120 ms. It is six messages, a command and a reply for each of three services: three round trips of 20 ms is 60 ms of messages, plus three times 20 ms of handling.
  • Orchestration: the last step fails takes 200 ms and ten messages. The shipment is refused, so the orchestrator sends RefundPayment and then ReleaseStock. Those two compensations add two round trips and two handlings, 80 ms, to the 120 ms. A failed order costs more than a successful one.
  • Orchestration: the refund fails and is retried takes 1,220 ms. The first refund meets an unavailable payment provider, and the orchestrator waits Wait before retrying a failed compensation, 1,000 ms by default, before it sends the same command with the same key. The wait is 1,000 of the 1,220 ms. The saga cannot give up on the refund, so a slow provider makes the order take as long as the provider does.
  • Orchestration: the orchestrator crashes mid-compensation takes 5,200 ms. The orchestrator crashes after the refund and restarts after Time to restart a crashed orchestrator, 5,000 ms by default, and sends the stock release from its saga log. The next section explains why that log is the point.
  • Choreography: the payment fails takes 180 ms and eight messages. There is no orchestrator: each service publishes an event on the broker and the others react.
  • Choreography: the last step fails takes 280 ms and twelve messages. The shipping service publishes ShipmentFailed, the payment service reacts by refunding and publishes PaymentRefunded, and the stock service reacts to that by releasing the stock. The compensation runs in reverse order only because each service listens for the event of the step after its own.

The two styles are drawn with different round-trip controls, 20 ms between the order service and each service for orchestration and 30 ms between a service and the broker for choreography, so that their defaults are not a fair comparison. Set Round trip, order service to each service (orchestration) and Round trip, service to broker (choreography) both to 100 ms, and the same failing last step takes 600 ms with orchestration and 700 ms with choreography. The difference is the number of messages: ten for the orchestrator’s five commands and five replies, and twelve for the six events of the choreography, each of which crosses the broker twice, once to publish and once to deliver.

There are two ways to run a saga, and the flow draws both.

In orchestration, a central component, the orchestrator, tells each participant which local transaction to run, waits for the reply, and decides what comes next, including the compensations. In choreography, there is no coordinator: each local transaction publishes an event, and the services that care react to it. Richardson’s page gives both definitions, and the Azure page lists the trade-offs.

Orchestration Choreography
Where the flow lives In the orchestrator, in one place In the subscriptions of every service, spread out
Seeing where an order is The orchestrator holds the state of each saga Reconstructed from events across services
Adding a step Change the orchestrator Change who listens to what, in several services
Coupling The orchestrator knows every participant Services know the events, not each other, but can form cycles
If the coordinator fails The orchestrator is a point of failure that must be made durable and available No single point, but nobody sees the whole flow
Fits Many steps, branches, several teams A few steps and a few services

The Azure page puts it this way: choreography is good for simple workflows with few services and no need for coordination logic, while its drawbacks are that the workflow gets confusing as steps are added, that cyclic dependencies between participants are a risk, and that integration testing is hard because every service must run. Orchestration suits complex workflows and avoids cycles, at the price of a coordination component that becomes a point of failure.

Compensations are retried, so they are idempotent

Section titled “Compensations are retried, so they are idempotent”

A compensation cannot be abandoned: if the refund fails, the order stays half-undone with the customer’s money taken. So it is retried, with a wait that grows, until it works. That has a consequence. When the first RefundPayment gets a 503, the orchestrator cannot tell whether the provider applied the refund before it failed. The retry in the flow carries the same key, refund-42, so that the payment service can recognise a repeat. This is the idempotency key of the idempotency module, and the Azure page says the same: a step may run more than once, so design each step as an idempotent command.

The C# example runs a small orchestrator with the same shape. A permanent failure sends it into compensation, and a transient failure inside a compensation makes it wait and try again, with the growing wait that you know from retries.

C# exampleA saga orchestrator with compensations, a retried refund and an idempotency key
saga-orchestrator.cs
// A saga orchestrator: run the steps in order; when one fails for good, undo the steps that completed,
// newest first. An undo is a new action (a refund, not an un-charge), it is retried until it works,
// and it must be safe to run twice, because a crash can make the orchestrator replay it.
using ShardCraft.Playground;
var clock = new FakeClock();
Scenario("all steps succeed", shippingScript: "", refundScript: "");
Scenario("shipment refused", shippingScript: "p", refundScript: "");
Scenario("shipment refused, refund unavailable twice", shippingScript: "p", refundScript: "tt", replayRefund: true);
void Scenario(string title, string shippingScript, string refundScript, bool replayRefund = false)
{
Console.WriteLine($"== {title}");
var stock = new StockService();
var payments = new PaymentService();
var shipping = new FlakyService(clock, shippingScript); // "p": the first call is refused for good
var refundGateway = new FlakyService(clock, refundScript); // "t": a call fails with a 503, then works
var shipments = 0;
SagaStep[] steps =
[
new("reserve stock", () => stock.Reserve(2), () => stock.Release(2)),
new("charge payment", () => payments.Charge("order-42", 25), () =>
{
refundGateway.Call();
payments.Refund("refund-order-42", 25);
}),
new("create shipment", () => { shipping.Call(); shipments++; }, () => shipments--),
];
new Orchestrator(clock, line => Console.WriteLine(" " + line)).Run(steps);
Console.WriteLine($" state stock={stock.Reserved} balance={payments.Balance} refunds={payments.Refunds} shipments={shipments}");
if (replayRefund)
{
// The orchestrator crashed after the refund and replays it from its log: the same key changes nothing.
payments.Refund("refund-order-42", 25);
Console.WriteLine($" replay refund-order-42 again -> balance={payments.Balance} refunds={payments.Refunds}");
}
}
record SagaStep(string Name, Action Do, Action Compensate);
class Orchestrator(FakeClock clock, Action<string> log)
{
public void Run(IReadOnlyList<SagaStep> steps)
{
var done = new Stack<SagaStep>();
foreach (var step in steps)
{
log($"do {step.Name}");
try
{
step.Do();
done.Push(step);
}
catch (PermanentFailureException e)
{
log($"failed {step.Name}: {e.Message}");
while (done.Count > 0) Undo(done.Pop());
log("saga compensated");
return;
}
}
log("saga completed");
}
// A transient failure is retried with a growing wait. A real saga also alerts a person when an undo can never finish.
private void Undo(SagaStep step)
{
for (var attempt = 1; ; attempt++)
{
try
{
step.Compensate();
log(attempt == 1 ? $"undo {step.Name}" : $"undo {step.Name} (attempt {attempt})");
return;
}
catch (TransientFailureException e)
{
var wait = TimeSpan.FromSeconds(attempt);
log($"undo {step.Name} failed ({e.Message}), retry in {wait.TotalSeconds:0}s");
clock.Advance(wait);
}
}
}
}
class StockService
{
public int Reserved { get; private set; }
public void Reserve(int units) => Reserved += units;
public void Release(int units) => Reserved -= units;
}
class PaymentService
{
private readonly HashSet<string> _refundKeys = [];
public int Balance { get; private set; }
public int Refunds => _refundKeys.Count;
public void Charge(string key, int amount) => Balance += amount;
// Idempotent: the key says which refund this is, so a second call with it does nothing.
public void Refund(string key, int amount)
{
if (_refundKeys.Add(key)) Balance -= amount;
}
}
Output
== all steps succeed
do reserve stock
do charge payment
do create shipment
saga completed
state stock=2 balance=25 refunds=0 shipments=1
== shipment refused
do reserve stock
do charge payment
do create shipment
failed create shipment: 400 bad request
undo charge payment
undo reserve stock
saga compensated
state stock=0 balance=0 refunds=1 shipments=0
== shipment refused, refund unavailable twice
do reserve stock
do charge payment
do create shipment
failed create shipment: 400 bad request
undo charge payment failed (503 service unavailable), retry in 1s
undo charge payment failed (503 service unavailable), retry in 2s
undo charge payment (attempt 3)
undo reserve stock
saga compensated
state stock=0 balance=0 refunds=1 shipments=0
replay refund-order-42 again -> balance=0 refunds=1

This is the exact code that produced this output, run with the .NET SDK when the site was built. Nothing runs in your browser.

In the first scenario all steps succeed and the state is stock=2 balance=25 refunds=0 shipments=1. In the second the shipment is refused for good, the orchestrator undoes the payment and then the stock, and the state is back to stock=0 balance=0 with refunds=1: the refund is recorded as an action, it did not erase the charge. In the third the refund gateway answers 503 twice, so the orchestrator waits 1 s and then 2 s and succeeds on the third attempt. The last line replays the refund, as an orchestrator that crashed and replayed its log would, and refund-order-42 again leaves refunds=1. The code in the page is never run in the browser: the output was produced by a CI run of the same file.

A failing payment provider is also a case for the circuit breaker of the reliability module, which stops an orchestrator from hammering a provider that is down. The saga decides what to do when a step fails; the breaker decides whether to try the call at all.

A saga gives atomicity by compensation, and no isolation. Each local transaction commits as soon as it is done, so every other request can read what it wrote, including state that a compensation will undo. The Azure page names the anomalies: lost updates, dirty reads, and fuzzy (non-repeatable) reads. In the anomalies lesson you saw them inside one database, where isolation levels prevent them; between the steps of a saga nothing does.

The flow shows the window. In the failing order, the stock service reserves the units at 30 ms and releases them at 190 ms, so for 160 ms the units are held for an order that will not happen. If the refund is retried, the same window lasts 1,180 ms. A second customer who asks for the last units in that time is told they are out of stock, and the order is lost although the stock is back. That is a dirty read between the steps.

The countermeasures come from Richardson’s book and are listed on the Azure page. These are the ones to know:

  • Semantic lock. The saga’s first step marks the record as being in progress, such as an order in the PENDING state, and the other requests see the flag and wait, refuse, or show “pending” to the customer.
  • Commutative updates. Design updates so that they give the same result in any order, such as adding and subtracting amounts instead of overwriting a balance, so that a compensation does not conflict with other sagas.
  • Pessimistic view. Reorder the steps so that the updates other sagas could read happen in steps that are retried and never compensated, after the point where the saga can no longer be undone, which removes the dirty reads.
  • Reread values. Check that a record has not changed before updating it, and restart the saga if it has.

Ordering is the cheapest. A step that cannot be compensated, such as an email, goes after every step that can still fail, and the steps that are most likely to fail go early. Choosing the order is part of designing the saga.

What happens if the orchestrator crashes in the middle?

Section titled “What happens if the orchestrator crashes in the middle?”

In the flow, the orchestrator crashes after the refund and before releasing the stock, and the order finishes at 5,200 ms. That only works because the orchestrator saved the saga’s state before each command. When the restarted instance reads that log it sees that the reserve and the charge are done, that the shipment failed, and that the refund is done, so it sends the stock release.

An orchestrator that kept its progress only in memory would restart knowing nothing. The refund is done and the stock is still reserved, and no one will ever release it. The units would be lost to sale until someone found them. A saga needs a durable log of where each order is, written before the command it describes is sent, which also means the commands and the compensations must be idempotent, because a crash after a command was sent and before its reply was recorded makes the restarted orchestrator send it again. The Azure Compensating Transaction page says the same of the infrastructure: it must not lose the information needed to compensate, and must record progress so that it can resume from the point of failure.

And if a compensation can never finish, because the card account was closed, for example, the saga cannot decide by itself. The Azure page notes that sometimes manual intervention is the only way to recover, and that the system should then raise an alert with the details. A stuck saga is something to monitor, not a rare case to ignore.

Step of the framework For a saga
Decision Run a business transaction that spans services as a saga, with compensations.
Why No transaction spans the databases, and two-phase commit blocks and is not available to every participant.
Benefits Each service keeps its own database and commits locally. No locks are held across services, and a slow service delays the saga without blocking the others’ data.
Costs A compensation to design, write and test for every step; no isolation; a durable saga log; more states than a single transaction has.
Failure modes A compensation that fails; an orchestrator that crashes without a log; duplicate commands; dirty reads of half-finished work.
Scaling limits Every in-flight saga holds a row of state. When a downstream service fails, many sagas compensate and retry together, which is the retry amplification you saw in the reliability module.
Alternative Keep the data that must change together in one service with one database, or use two-phase commit where every participant supports it and the coordinator is replicated.

The cheapest saga is the one you avoid by drawing the service boundaries so that the data which must be consistent lives together.

Check your understanding: sagas

This quiz needs JavaScript to check your answers.

Question 1 of 3

An order saga has reserved the stock and charged the payment. The shipping service then refuses the order because the address cannot be served.

What does the saga do next?

Choose one answer.

Question 2 of 3

The saga sends RefundPayment and gets a 503 from the payment provider. It cannot tell whether the provider applied the refund before it failed.

How should it retry so that the customer is refunded exactly once?

Choose one answer.

Question 3 of 3

An order saga has reserved the last 2 units of an item and is waiting for the payment. A second customer asks for the item and is told that it is out of stock. The payment then fails and the units are released.

What happened to the second customer?

Choose one answer.

  • No transaction spans services that own their databases, and two-phase commit blocks and is not available to every participant. A saga uses only local transactions.
  • A saga is a sequence of local transactions with a compensation for each step. A compensation is a new business action, such as a refund, and not a rollback.
  • In the flow an order takes 120 ms when every step succeeds and 200 ms when the last step fails, because the refund and the stock release add two round trips and two handlings.
  • Orchestration keeps the flow in one place at the price of a component that must be durable and available. Choreography has no coordinator and an implicit flow. With the same 100 ms round trips a failing last step takes 600 ms with ten messages against 700 ms with twelve.
  • Compensations are retried and must be idempotent, and the orchestrator keeps a durable log: with a 5,000 ms restart the order is cancelled at 5,200 ms instead of never.
  • A saga has no isolation: the units stayed reserved for 160 ms in a failing order, 1,180 ms with a retried refund. Semantic locks and ordering the steps are the usual countermeasures.

Next: the transactional outbox, which makes a database write and a message one step.

Your progress

Built by GhaziAlibi.

© ShardCraft. All rights reserved.