Sagas in Depth: Pivots, Compensations, Isolation and the Failure Modes Nobody Draws
November 7, 2025 · 36 min read
Software Architecture, Design Patterns, Distributed Systems, Messaging, Saga Pattern, C#, Python
I covered sagas in two earlier posts: Part 3, saga orchestration introduced choreography, orchestration and compensating actions, and Part 4 built an order saga on Azure Durable Functions. Both were C# and Azure.
This post is the part those skipped. It's stack-neutral, and it's about the theory and the failure modes: what a saga actually promises, the point of no return, why compensations are harder than they look, what to do when a reply comes back after you've given up, and what happens when two sagas touch the same data at once.
The running example is a trip booking: hold a flight seat, book a hotel room, charge the card, issue the ticket. It's a different domain from the order example in Part 3 on purpose, because it has a step you clearly can't undo.
Every snippet was run with .NET 10 (dotnet run file.cs) or Python 3.12, and the output shown is the real output. Crashes and timeouts are simulated at fixed points so every run is the same. Snippets that need Temporal or another engine are labelled not run.
Why two-phase commit doesn't fit
Two-phase commit (2PC) makes several databases commit as one. A coordinator asks every participant to prepare. Each one locks what it touched and votes yes. Then the coordinator tells them all to commit.
It works, and inside one data centre with databases that support it, it's sometimes the right tool. Across services it fits badly:
- Locks are held across the network. Every participant holds its locks from prepare to commit. A slow participant slows everyone, and a booking flow that waits on a payment provider for 20 seconds would hold seat and room locks for all of it.
- It blocks when the coordinator fails. A participant that voted yes can't decide on its own. If the coordinator dies at the wrong moment, the participant sits locked until it comes back.
- Availability multiplies. The transaction succeeds only if every participant is up. Five services at 99.9% each give you roughly 99.5% for the whole thing.
- Most of the stack doesn't speak it. Most cloud brokers, NoSQL stores and third-party APIs don't take part in an XA transaction. You can't make Stripe prepare.
So a saga gives up on one big atomic transaction.
What a saga actually promises
The idea comes from Hector Garcia-Molina and Kenneth Salem's 1987 paper Sagas. They were dealing with long-lived transactions that held locks for too long. Their answer: split the long transaction into a sequence of short local transactions T1, T2, ... Tn, each with a compensating transaction C1, C2, ... that semantically undoes it. The system guarantees that either all of T1..Tn run, or T1..Tj run followed by Cj..C1.
The paper also describes two ways to recover from a failure:
- Backward recovery: run the compensations, newest first. This is the "undo" everyone draws.
- Forward recovery: keep retrying the remaining steps until they succeed. No undo at all.
Real sagas use both, and where you switch from one to the other is the most important design decision. Compared with ACID, a saga keeps atomicity (eventually: all or compensated), consistency (each local transaction keeps its own invariants) and durability. It gives up isolation. Other code can see the saga's half-done work. A whole section below covers that.
Three kinds of step: compensatable, pivot, retriable
Chris Richardson's Microservices Patterns (and microservices.io) gives the step types names that make the design easy to talk about:
- Compensatable steps can be undone by a compensating transaction. Holding a seat can be undone by releasing it.
- The pivot is the go/no-go step. If it succeeds, the saga will run to completion. If it fails, the saga compensates. It's the point of no return, and it's often a step that can't be undone in any meaningful way, or one you don't want to undo.
- Retriable steps come after the pivot. They're guaranteed to succeed eventually, so they're retried rather than compensated.
For the trip:
| # | Step | Kind | Compensation |
|---|---|---|---|
| 1 | Hold seat | Compensatable | Release seat |
| 2 | Book room | Compensatable | Cancel room |
| 3 | Charge card | Pivot | (none: after this, we finish) |
| 4 | Issue ticket | Retriable | (none: retry until it works) |
Two rules fall out of this:
- Put the steps most likely to fail before the pivot. Availability checks, holds, fraud checks. If they fail, undo is cheap.
- Put only steps that can't fail for a business reason after the pivot. "Issue ticket" can time out, but it can't say no once the seat is held and paid for. If a step after the pivot can say no, the pivot is in the wrong place.
The order of steps is a business decision as much as a technical one. Charging the card before booking the room makes "refund" a compensation. Refunds are slow, cost fees and annoy customers. Holding first and charging last avoids most of them.
Orchestration, runnable
An orchestrator is the one place that knows the steps. It calls each participant, records progress after every step, and decides whether to retry, compensate or continue. The demo below has:
- Participants that are idempotent on
(saga_id, operation): a repeated call returns the first result and causes no new side effect. - Two kinds of error:
Failed(a business "no", like a declined card; retrying won't help) andTransient(a timeout; retrying might). - A
sagatable in SQLite with the status and a cursor, saved after every step.
Three trips run through it:
- trip-1: ticketing times out twice after the pivot, so it's retried.
- trip-2: the card is declined at the pivot, and the first room cancellation times out.
- trip-3: the orchestrator crashes after booking the room and before saving its progress.
Python
import sqlite3
from dataclasses import dataclass
from typing import Callable
class Failed(Exception):
"""A business 'no' (declined card, no rooms). Retrying won't help."""
class Transient(Exception):
"""A timeout or 503. Retrying might help."""
class Crash(Exception):
"""The orchestrator process dies."""
class Participant:
"""A remote service. Every operation is idempotent on (saga_id, op)."""
def __init__(self, name: str):
self.name, self.done, self.script, self.effects = name, {}, {}, []
def call(self, saga_id: str, op: str) -> str:
key = (saga_id, op)
if key in self.done: # a retry or a replay after a crash
return f"{self.done[key]} (replayed, no new side effect)"
planned = self.script.get(key)
outcome = planned.pop(0) if planned else "ok"
if outcome == "declined":
raise Failed(f"{self.name}.{op} declined")
if outcome == "timeout":
raise Transient(f"{self.name}.{op} timed out")
self.effects.append(key)
self.done[key] = f"{self.name}.{op} ok"
return self.done[key]
flights, hotels, payments, tickets = (Participant(n) for n in ("flights", "hotels", "payments", "tickets"))
@dataclass
class Step:
name: str
kind: str # "compensatable" | "pivot" | "retriable"
run: Callable[[str], str]
undo: Callable[[str], str] | None = None
STEPS = [
Step("hold seat", "compensatable", lambda s: flights.call(s, "hold"), lambda s: flights.call(s, "release")),
Step("book room", "compensatable", lambda s: hotels.call(s, "book"), lambda s: hotels.call(s, "cancel")),
Step("charge card", "pivot", lambda s: payments.call(s, "charge")), # point of no return
Step("issue ticket", "retriable", lambda s: tickets.call(s, "issue")),
]
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE saga (id TEXT PRIMARY KEY, status TEXT, cursor INTEGER)")
def save(saga_id: str, status: str, cursor: int) -> None:
with db:
db.execute("INSERT INTO saga VALUES (?, ?, ?) ON CONFLICT (id) DO UPDATE"
" SET status = excluded.status, cursor = excluded.cursor", (saga_id, status, cursor))
def run(saga_id: str, crash_after: str | None = None) -> str:
row = db.execute("SELECT status, cursor FROM saga WHERE id = ?", (saga_id,)).fetchone()
status, cursor = row if row else ("running", 0)
if row:
print(f" resume {saga_id}: status={status} cursor={cursor}")
while status == "running" and cursor < len(STEPS):
step, attempt = STEPS[cursor], 1
while True:
try:
print(f" {step.name:<12} [{step.kind}] {step.run(saga_id)}")
break
except Transient as err:
if step.kind != "retriable": # before the pivot: give up and compensate
print(f" {step.name:<12} {err}: treat as failure")
status = "compensating"
break
attempt += 1 # after the pivot there is no going back: retry
print(f" {step.name:<12} {err}, retry #{attempt - 1} (backoff)")
except Failed as err:
print(f" {step.name:<12} {err}")
status = "compensating"
break
if status == "compensating":
break
if crash_after == step.name:
raise Crash(f"orchestrator died after '{step.name}', before saving progress")
cursor += 1
save(saga_id, "running", cursor) # durable progress after every step
if status == "compensating":
save(saga_id, "compensating", cursor)
for step in reversed(STEPS[:cursor]): # newest first
while True: # a compensation may not give up: retry until it lands
try:
print(f" undo {step.name:<7} {step.undo(saga_id)}")
break
except Transient as err:
print(f" undo {step.name:<7} {err}, retry (backoff)")
cursor -= 1
save(saga_id, "compensating", cursor)
status = "compensated"
else:
status = "completed"
save(saga_id, status, cursor)
return status
tickets.script[("trip-1", "issue")] = ["timeout", "timeout", "ok"]
payments.script[("trip-2", "charge")] = ["declined"]
hotels.script[("trip-2", "cancel")] = ["timeout", "ok"]
for trip in ("trip-1", "trip-2", "trip-3"):
print(trip)
try:
print(" ->", run(trip, crash_after="book room" if trip == "trip-3" else None))
except Crash as err:
print(f" !! {err}")
print(" ->", run(trip)) # a new process picks the saga up from the saga table
print("hotel side effects:", hotels.effects)
trip-1
hold seat [compensatable] flights.hold ok
book room [compensatable] hotels.book ok
charge card [pivot] payments.charge ok
issue ticket tickets.issue timed out, retry #1 (backoff)
issue ticket tickets.issue timed out, retry #2 (backoff)
issue ticket [retriable] tickets.issue ok
-> completed
trip-2
hold seat [compensatable] flights.hold ok
book room [compensatable] hotels.book ok
charge card payments.charge declined
undo book room hotels.cancel timed out, retry (backoff)
undo book room hotels.cancel ok
undo hold seat flights.release ok
-> compensated
trip-3
hold seat [compensatable] flights.hold ok
book room [compensatable] hotels.book ok
!! orchestrator died after 'book room', before saving progress
resume trip-3: status=running cursor=1
book room [compensatable] hotels.book ok (replayed, no new side effect)
charge card [pivot] payments.charge ok
issue ticket [retriable] tickets.issue ok
-> completed
hotel side effects: [('trip-1', 'book'), ('trip-2', 'book'), ('trip-2', 'cancel'), ('trip-3', 'book')]
C#
#:package Microsoft.Data.Sqlite@10.0.13
using Microsoft.Data.Sqlite;
var flights = new Participant("flights");
var hotels = new Participant("hotels");
var payments = new Participant("payments");
var tickets = new Participant("tickets");
Step[] steps =
[
new("hold seat", StepKind.Compensatable, s => flights.Call(s, "hold"), s => flights.Call(s, "release")),
new("book room", StepKind.Compensatable, s => hotels.Call(s, "book"), s => hotels.Call(s, "cancel")),
new("charge card", StepKind.Pivot, s => payments.Call(s, "charge")), // point of no return
new("issue ticket", StepKind.Retriable, s => tickets.Call(s, "issue")),
];
using var db = new SqliteConnection("Data Source=:memory:");
db.Open();
using (var c = db.CreateCommand())
{
c.CommandText = "CREATE TABLE saga (id TEXT PRIMARY KEY, status TEXT, cursor INTEGER)";
c.ExecuteNonQuery();
}
tickets.Script[("trip-1", "issue")] = new(["timeout", "timeout", "ok"]);
payments.Script[("trip-2", "charge")] = new(["declined"]);
hotels.Script[("trip-2", "cancel")] = new(["timeout", "ok"]);
foreach (var trip in new[] { "trip-1", "trip-2", "trip-3" })
{
Console.WriteLine(trip);
try { Console.WriteLine($" -> {Run(trip, trip == "trip-3" ? "book room" : null)}"); }
catch (CrashException e)
{
Console.WriteLine($" !! {e.Message}");
Console.WriteLine($" -> {Run(trip)}"); // a new process resumes from the saga table
}
}
Console.WriteLine($"hotel side effects: [{string.Join(", ", hotels.Effects)}]");
string Run(string sagaId, string? crashAfter = null)
{
var (status, cursor) = Load(sagaId);
while (status == "running" && cursor < steps.Length)
{
var step = steps[cursor];
var retries = 0;
while (true)
{
try
{
Console.WriteLine($" {step.Name,-12} [{step.Kind}] {step.Run(sagaId)}");
break;
}
catch (TransientException e) when (step.Kind == StepKind.Retriable)
{
// After the pivot there is no going back: retry.
Console.WriteLine($" {step.Name,-12} {e.Message}, retry #{++retries} (backoff)");
}
catch (Exception e) when (e is TransientException or FailedException)
{
Console.WriteLine($" {step.Name,-12} {e.Message}");
status = "compensating";
break;
}
}
if (status == "compensating") break;
if (crashAfter == step.Name)
throw new CrashException($"orchestrator died after '{step.Name}', before saving progress");
Save(sagaId, "running", ++cursor); // durable progress after every step
}
if (status == "compensating")
{
Save(sagaId, status, cursor);
for (var i = cursor - 1; i >= 0; i--) // newest first
{
while (true) // a compensation may not give up
{
try { Console.WriteLine($" undo {steps[i].Name,-7} {steps[i].Undo!(sagaId)}"); break; }
catch (TransientException e) { Console.WriteLine($" undo {steps[i].Name,-7} {e.Message}, retry (backoff)"); }
}
Save(sagaId, status, --cursor);
}
status = "compensated";
}
else status = "completed";
Save(sagaId, status, cursor);
return status;
}
(string Status, int Cursor) Load(string sagaId)
{
using var cmd = db.CreateCommand();
cmd.CommandText = "SELECT status, cursor FROM saga WHERE id = $id";
cmd.Parameters.AddWithValue("$id", sagaId);
using var r = cmd.ExecuteReader();
if (!r.Read()) return ("running", 0);
Console.WriteLine($" resume {sagaId}: status={r.GetString(0)} cursor={r.GetInt32(1)}");
return (r.GetString(0), r.GetInt32(1));
}
void Save(string sagaId, string status, int cursor)
{
using var cmd = db.CreateCommand();
cmd.CommandText = """
INSERT INTO saga VALUES ($id, $st, $cur)
ON CONFLICT (id) DO UPDATE SET status = excluded.status, cursor = excluded.cursor
""";
cmd.Parameters.AddWithValue("$id", sagaId);
cmd.Parameters.AddWithValue("$st", status);
cmd.Parameters.AddWithValue("$cur", cursor);
cmd.ExecuteNonQuery();
}
enum StepKind { Compensatable, Pivot, Retriable }
record Step(string Name, StepKind Kind, Func<string, string> Run, Func<string, string>? Undo = null);
class FailedException(string m) : Exception(m); // a business "no": retrying won't help
class TransientException(string m) : Exception(m); // a timeout or 503: retrying might
class CrashException(string m) : Exception(m);
class Participant(string name)
{
readonly Dictionary<(string, string), string> done = new();
public Dictionary<(string, string), Queue<string>> Script { get; } = new();
public List<string> Effects { get; } = new();
// Idempotent on (sagaId, op): a replay returns the first result, no new side effect.
public string Call(string sagaId, string op)
{
if (done.TryGetValue((sagaId, op), out var prior)) return $"{prior} (replayed, no new side effect)";
var outcome = Script.TryGetValue((sagaId, op), out var q) && q.Count > 0 ? q.Dequeue() : "ok";
if (outcome == "declined") throw new FailedException($"{name}.{op} declined");
if (outcome == "timeout") throw new TransientException($"{name}.{op} timed out");
Effects.Add($"({sagaId}, {op})");
return done[(sagaId, op)] = $"{name}.{op} ok";
}
}
trip-1
hold seat [Compensatable] flights.hold ok
book room [Compensatable] hotels.book ok
charge card [Pivot] payments.charge ok
issue ticket tickets.issue timed out, retry #1 (backoff)
issue ticket tickets.issue timed out, retry #2 (backoff)
issue ticket [Retriable] tickets.issue ok
-> completed
trip-2
hold seat [Compensatable] flights.hold ok
book room [Compensatable] hotels.book ok
charge card payments.charge declined
undo book room hotels.cancel timed out, retry (backoff)
undo book room hotels.cancel ok
undo hold seat flights.release ok
-> compensated
trip-3
hold seat [Compensatable] flights.hold ok
book room [Compensatable] hotels.book ok
!! orchestrator died after 'book room', before saving progress
resume trip-3: status=running cursor=1
book room [Compensatable] hotels.book ok (replayed, no new side effect)
charge card [Pivot] payments.charge ok
issue ticket [Retriable] tickets.issue ok
-> completed
hotel side effects: [(trip-1, book), (trip-2, book), (trip-2, cancel), (trip-3, book)]
What to notice:
- trip-1 shows forward recovery. The ticket timed out twice, but the card was already charged, so compensating would mean refunding a customer whose seat and room are fine. The orchestrator retries instead. In production that's an exponential backoff and an alert after a while, but never a quiet undo.
- trip-2 shows backward recovery. The pivot failed, so the two compensatable steps are undone newest first. The room cancellation timed out once and was retried. A compensation can't give up: if it does, you have a held seat or a booked room with nobody paying for it. If it keeps failing, park the saga as "compensation failed" and page a person.
- trip-3 shows why idempotency matters. The orchestrator booked the room, then died before saving the cursor. The new process resumed at cursor 1 and called
bookagain. The hotel recognised(trip-3, book)and returned the first result. The last line confirms each trip booked one room.
That last case can't be avoided: there's always a gap between "the participant did it" and "the orchestrator recorded it". Saving before calling doesn't help either, because then a crash leaves a recorded step that never happened. So the participant has to absorb the repeat. Use the saga id and step name as the idempotency key, and have the participant store the result with the key, in the same transaction as the side effect. That's the inbox from the outbox post, on the participant side.
Choreography, runnable
In choreography there's no orchestrator. Each service reacts to events and emits its own. The flow is the sum of all the subscriptions. trip-1 succeeds, trip-2's hotel is full, and trip-3's card is declined.
Python
from collections import defaultdict, deque
class Bus:
"""In-memory pub/sub. Events are delivered in publish order, one at a time."""
def __init__(self):
self.handlers, self.queue = defaultdict(list), deque()
def subscribe(self, event: str, service: str, handler) -> None:
self.handlers[event].append((service, handler))
def publish(self, event: str, trip: str) -> None:
self.queue.append((event, trip))
def drain(self) -> None:
while self.queue:
event, trip = self.queue.popleft()
reactors = [s for s, _ in self.handlers[event]] or ["nobody"]
print(f" {trip} {event:<16} -> {', '.join(reactors)}")
for _, handler in self.handlers[event]:
handler(trip)
bus = Bus()
rooms_left = {"trip-1": 1, "trip-2": 0, "trip-3": 1} # trip-2's hotel is full
card_ok = {"trip-1": True, "trip-2": True, "trip-3": False} # trip-3's card is declined
status: dict[str, str] = {}
# Each service only knows the events it reacts to and the ones it emits.
bus.subscribe("TripRequested", "flights", lambda t: bus.publish("SeatHeld", t))
bus.subscribe("SeatHeld", "hotels",
lambda t: bus.publish("RoomBooked" if rooms_left[t] else "RoomUnavailable", t))
bus.subscribe("RoomBooked", "payments",
lambda t: bus.publish("PaymentCaptured" if card_ok[t] else "PaymentDeclined", t))
bus.subscribe("PaymentCaptured", "tickets", lambda t: bus.publish("TicketIssued", t))
# Compensation is just another subscription. Here is where choreography gets hard to read:
bus.subscribe("RoomUnavailable", "flights", lambda t: bus.publish("SeatReleased", t))
bus.subscribe("PaymentDeclined", "hotels", lambda t: bus.publish("RoomCancelled", t))
bus.subscribe("PaymentDeclined", "flights", lambda t: bus.publish("SeatReleased", t))
bus.subscribe("TicketIssued", "trips", lambda t: status.__setitem__(t, "confirmed"))
bus.subscribe("SeatReleased", "trips", lambda t: status.__setitem__(t, "rejected"))
for trip in ("trip-1", "trip-2", "trip-3"):
bus.publish("TripRequested", trip)
bus.drain()
print("status:", status)
print("who knows the whole flow? only someone who reads every subscription:")
for event, subs in bus.handlers.items():
print(f" {event:<16} handled by {[s for s, _ in subs]}")
trip-1 TripRequested -> flights
trip-1 SeatHeld -> hotels
trip-1 RoomBooked -> payments
trip-1 PaymentCaptured -> tickets
trip-1 TicketIssued -> trips
trip-2 TripRequested -> flights
trip-2 SeatHeld -> hotels
trip-2 RoomUnavailable -> flights
trip-2 SeatReleased -> trips
trip-3 TripRequested -> flights
trip-3 SeatHeld -> hotels
trip-3 RoomBooked -> payments
trip-3 PaymentDeclined -> hotels, flights
trip-3 RoomCancelled -> nobody
trip-3 SeatReleased -> trips
status: {'trip-1': 'confirmed', 'trip-2': 'rejected', 'trip-3': 'rejected'}
who knows the whole flow? only someone who reads every subscription:
TripRequested handled by ['flights']
SeatHeld handled by ['hotels']
RoomBooked handled by ['payments']
PaymentCaptured handled by ['tickets']
RoomUnavailable handled by ['flights']
PaymentDeclined handled by ['hotels', 'flights']
TicketIssued handled by ['trips']
SeatReleased handled by ['trips']
RoomCancelled handled by []
C#
var bus = new Bus();
var roomsLeft = new Dictionary<string, int> { ["trip-1"] = 1, ["trip-2"] = 0, ["trip-3"] = 1 };
var cardOk = new Dictionary<string, bool> { ["trip-1"] = true, ["trip-2"] = true, ["trip-3"] = false };
var status = new Dictionary<string, string>();
// Each service only knows the events it reacts to and the ones it emits.
bus.Subscribe("TripRequested", "flights", t => bus.Publish("SeatHeld", t));
bus.Subscribe("SeatHeld", "hotels", t => bus.Publish(roomsLeft[t] > 0 ? "RoomBooked" : "RoomUnavailable", t));
bus.Subscribe("RoomBooked", "payments", t => bus.Publish(cardOk[t] ? "PaymentCaptured" : "PaymentDeclined", t));
bus.Subscribe("PaymentCaptured", "tickets", t => bus.Publish("TicketIssued", t));
// Compensation is just more subscriptions:
bus.Subscribe("RoomUnavailable", "flights", t => bus.Publish("SeatReleased", t));
bus.Subscribe("PaymentDeclined", "hotels", t => bus.Publish("RoomCancelled", t));
bus.Subscribe("PaymentDeclined", "flights", t => bus.Publish("SeatReleased", t));
bus.Subscribe("TicketIssued", "trips", t => status[t] = "confirmed");
bus.Subscribe("SeatReleased", "trips", t => status[t] = "rejected");
foreach (var trip in new[] { "trip-1", "trip-2", "trip-3" })
{
bus.Publish("TripRequested", trip);
bus.Drain();
}
Console.WriteLine($"status: {string.Join(", ", status.Select(kv => $"{kv.Key}={kv.Value}"))}");
Console.WriteLine("who knows the whole flow? only someone who reads every subscription:");
foreach (var (evt, subs) in bus.Handlers)
Console.WriteLine($" {evt,-16} handled by [{string.Join(", ", subs.Select(s => s.Service))}]");
class Bus
{
public Dictionary<string, List<(string Service, Action<string> Handler)>> Handlers { get; } = new();
readonly Queue<(string Event, string Trip)> queue = new();
public void Subscribe(string evt, string service, Action<string> handler)
{
if (!Handlers.TryGetValue(evt, out var list)) Handlers[evt] = list = new();
list.Add((service, handler));
}
public void Publish(string evt, string trip) => queue.Enqueue((evt, trip));
public void Drain()
{
while (queue.TryDequeue(out var item))
{
var subs = Handlers.GetValueOrDefault(item.Event) ?? new();
var who = subs.Count > 0 ? string.Join(", ", subs.Select(s => s.Service)) : "nobody";
Console.WriteLine($" {item.Trip} {item.Event,-16} -> {who}");
foreach (var (_, handler) in subs) handler(item.Trip);
}
}
}
trip-1 TripRequested -> flights
trip-1 SeatHeld -> hotels
trip-1 RoomBooked -> payments
trip-1 PaymentCaptured -> tickets
trip-1 TicketIssued -> trips
trip-2 TripRequested -> flights
trip-2 SeatHeld -> hotels
trip-2 RoomUnavailable -> flights
trip-2 SeatReleased -> trips
trip-3 TripRequested -> flights
trip-3 SeatHeld -> hotels
trip-3 RoomBooked -> payments
trip-3 PaymentDeclined -> hotels, flights
trip-3 RoomCancelled -> nobody
trip-3 SeatReleased -> trips
status: trip-1=confirmed, trip-2=rejected, trip-3=rejected
who knows the whole flow? only someone who reads every subscription:
TripRequested handled by [flights]
SeatHeld handled by [hotels]
RoomBooked handled by [payments]
PaymentCaptured handled by [tickets]
RoomUnavailable handled by [flights]
PaymentDeclined handled by [hotels, flights]
TicketIssued handled by [trips]
SeatReleased handled by [trips]
(C# doesn't list RoomCancelled at the end because nothing subscribed to it; Python's defaultdict created an empty entry when the event was published. Same finding.)
Look at trip-3. PaymentDeclined fans out to two services, which is neat. But RoomCancelled goes to nobody, and the trip is marked rejected as soon as the seat is released. Nothing checks that the room was actually cancelled. If the cancellation fails, no one finds out. This is the typical choreography bug: each service is correct on its own, and the gap is between them, where nobody owns it. The only way to see the whole flow is to read every subscription, which is the last part of the output.
Choreography vs orchestration
| Choreography | Orchestration | |
|---|---|---|
| Where the flow lives | Spread across every service's subscriptions | One orchestrator definition |
| Coupling | Services know event types, not each other | The orchestrator knows every participant's commands |
| Adding a step | Change several services, and check nothing else listens | Change the orchestrator |
| Saga state | Implicit; rebuild it from events | Explicit row or workflow history |
| "Where is trip-3 stuck?" | Correlate events across services | Read one record |
| Timeouts | Every service needs its own, or nobody has one | One deadline in the orchestrator |
| Failure point | No central one | The orchestrator, so it must be durable |
| Good fit | Two or three steps, stable flow, one team | Four or more steps, branching, compensation, several teams |
I'd use choreography for short, stable flows ("invoice paid, send receipt") and orchestration for anything with a pivot and compensations. Part 3 makes the same call. The demo above shows why: the compensation path is where choreography loses track.
Designing compensations that actually work
A compensation is a new business transaction, not a rollback. The seat was held and other code may have seen it. You can't make that not have happened. You can only issue a release. That has consequences:
- A compensation must be idempotent. It will be retried, and it may run after a crash mid-compensation, as trip-2 showed.
- A compensation must not fail for a business reason. "Release seat" can time out, but it must never say no. If a compensation can be refused, design the forward step so it can't be (hold with an expiry, for example) or treat it as a pivot.
- A compensation may arrive before the action it undoes. Messages get reordered and retried. The timeout section below shows this one running.
- Some things can't be undone. You can't unsend an email or un-ship a parcel. Move those steps after the pivot, so they only happen once the saga is sure to finish. Or make them reversible in business terms: a "your booking was cancelled" email undoes a confirmation email about as well as anything can.
- Undo isn't always the exact inverse. A refund may carry a fee; a cancelled room may have a penalty. Compensation restores business consistency, not the old bytes.
Timeouts and deadlines
A participant that never answers is worse than one that says no. The saga can't move forward or back. So every step that waits on someone else needs a deadline, and the orchestrator must decide what to do when it passes. Before the pivot, the usual answer is "compensate".
The trap: a timeout doesn't mean the request failed. It means you don't know. The hotel may have the request in a queue and process it later. So when the deadline passes, the orchestrator compensates everything it asked for, including the room it never heard back about. And then the late request lands.
Below, the hotel is slow today. The deadline is t=60, the cancel arrives at t=61, and the original booking request is processed at t=90. Two versions of the hotel:
Python
import heapq
class Hotel:
def __init__(self, tombstones: bool):
self.tombstones, self.booked, self.cancelled = tombstones, set(), set()
def book(self, key: str) -> str:
if key in self.cancelled:
return "rejected: already cancelled"
self.booked.add(key)
return "booked"
def cancel(self, key: str) -> str:
if key in self.booked:
self.booked.remove(key)
return "cancelled"
if self.tombstones:
self.cancelled.add(key) # remember: a late book for this key must fail
return "nothing booked yet, tombstone written"
return "nothing to cancel"
def simulate(hotel: Hotel) -> None:
timeline: list[tuple[int, int, str]] = []
n = 0
def at(t: int, what: str) -> None:
nonlocal n
n += 1
heapq.heappush(timeline, (t, n, what))
saga = {"status": "waiting for hotel", "deadline": 60}
at(0, "send BookRoom")
at(saga["deadline"], "deadline")
while timeline:
t, _, what = heapq.heappop(timeline)
if what == "send BookRoom":
print(f" t={t:>3} orchestrator -> BookRoom(trip-4), deadline t={saga['deadline']}")
at(90, "hotel processes BookRoom") # the provider is slow today
elif what == "deadline" and saga["status"] == "waiting for hotel":
saga["status"] = "compensating"
print(f" t={t:>3} deadline passed: compensate. Send CancelRoom anyway,"
" the request may have landed")
at(61, "hotel processes CancelRoom")
elif what == "hotel processes CancelRoom":
print(f" t={t:>3} hotel CancelRoom -> {hotel.cancel('trip-4')}")
saga["status"] = "compensated"
elif what == "hotel processes BookRoom":
print(f" t={t:>3} hotel BookRoom -> {hotel.book('trip-4')}"
f" (saga is already {saga['status']})")
print(f" rooms still booked for trip-4: {len(hotel.booked)}")
print("naive hotel")
simulate(Hotel(tombstones=False))
print("hotel with tombstones")
simulate(Hotel(tombstones=True))
naive hotel
t= 0 orchestrator -> BookRoom(trip-4), deadline t=60
t= 60 deadline passed: compensate. Send CancelRoom anyway, the request may have landed
t= 61 hotel CancelRoom -> nothing to cancel
t= 90 hotel BookRoom -> booked (saga is already compensated)
rooms still booked for trip-4: 1
hotel with tombstones
t= 0 orchestrator -> BookRoom(trip-4), deadline t=60
t= 60 deadline passed: compensate. Send CancelRoom anyway, the request may have landed
t= 61 hotel CancelRoom -> nothing booked yet, tombstone written
t= 90 hotel BookRoom -> rejected: already cancelled (saga is already compensated)
rooms still booked for trip-4: 0
C#
Console.WriteLine("naive hotel");
Simulate(new Hotel(tombstones: false));
Console.WriteLine("hotel with tombstones");
Simulate(new Hotel(tombstones: true));
static void Simulate(Hotel hotel)
{
var timeline = new PriorityQueue<string, (int T, int N)>();
var n = 0;
void At(int t, string what) => timeline.Enqueue(what, (t, ++n));
var status = "waiting for hotel";
const int deadline = 60;
At(0, "send BookRoom");
At(deadline, "deadline");
while (timeline.TryDequeue(out var what, out var when))
{
var t = when.T;
switch (what)
{
case "send BookRoom":
Console.WriteLine($" t={t,3} orchestrator -> BookRoom(trip-4), deadline t={deadline}");
At(90, "hotel processes BookRoom"); // the provider is slow today
break;
case "deadline" when status == "waiting for hotel":
status = "compensating";
Console.WriteLine($" t={t,3} deadline passed: compensate. Send CancelRoom anyway, the request may have landed");
At(61, "hotel processes CancelRoom");
break;
case "hotel processes CancelRoom":
Console.WriteLine($" t={t,3} hotel CancelRoom -> {hotel.Cancel("trip-4")}");
status = "compensated";
break;
case "hotel processes BookRoom":
Console.WriteLine($" t={t,3} hotel BookRoom -> {hotel.Book("trip-4")} (saga is already {status})");
break;
}
}
Console.WriteLine($" rooms still booked for trip-4: {hotel.Booked.Count}");
}
class Hotel(bool tombstones)
{
public HashSet<string> Booked { get; } = new();
readonly HashSet<string> cancelled = new();
public string Book(string key)
{
if (cancelled.Contains(key)) return "rejected: already cancelled";
Booked.Add(key);
return "booked";
}
public string Cancel(string key)
{
if (Booked.Remove(key)) return "cancelled";
if (!tombstones) return "nothing to cancel";
cancelled.Add(key); // remember: a late book for this key must fail
return "nothing booked yet, tombstone written";
}
}
naive hotel
t= 0 orchestrator -> BookRoom(trip-4), deadline t=60
t= 60 deadline passed: compensate. Send CancelRoom anyway, the request may have landed
t= 61 hotel CancelRoom -> nothing to cancel
t= 90 hotel BookRoom -> booked (saga is already compensated)
rooms still booked for trip-4: 1
hotel with tombstones
t= 0 orchestrator -> BookRoom(trip-4), deadline t=60
t= 60 deadline passed: compensate. Send CancelRoom anyway, the request may have landed
t= 61 hotel CancelRoom -> nothing booked yet, tombstone written
t= 90 hotel BookRoom -> rejected: already cancelled (saga is already compensated)
rooms still booked for trip-4: 0
The naive hotel ends up with an orphaned room. The saga is compensated and the customer was told "sorry", but a room is booked and nobody will pay for it.
The fix is a tombstone. When a cancel arrives for a booking the hotel hasn't seen, it records "trip-4 is cancelled" anyway, and any later booking with that key is refused. Cancel-before-book becomes harmless. That only works because the request and the cancel share an idempotency key, which is one more reason every step needs one.
Two more rules for deadlines:
- Timers must be durable. An in-memory timer in the orchestrator dies with the process, and the saga waits forever. Store the deadline with the saga state and have something check it after a restart, or use an engine with durable timers: Durable Functions'
CreateTimer, a sleep in a Temporal workflow, MassTransit's scheduled messages. - Have a step timeout and a saga deadline. "The hotel has 60 seconds" is a step timeout. "This trip must be settled within 15 minutes or the seat hold expires anyway" is the saga deadline. The second protects you from a chain of retries that never quite fails.
The missing I: isolation, and the countermeasures
Each saga step commits on its own, so other transactions see the in-between states. The anomalies are the classic ones:
- Lost update: one saga overwrites another's change without reading it.
- Dirty read: a transaction reads a value a saga will later compensate away.
- Fuzzy or non-repeatable read: two steps of the same saga read the same data and get different values, because something changed it in between.
Richardson's book (chapter 4, section 4.3) lists the standard countermeasures, design techniques that put back as much isolation as you need:
| Countermeasure | Idea | In the trip example |
|---|---|---|
| Semantic lock | A compensatable step sets a *_PENDING flag; others see "in use" and decide what to do | Seat state pending instead of taken until the pivot |
| Commutative updates | Design updates so their order doesn't matter | Credit and debit loyalty points as increments, not "set balance" |
| Pessimistic view | Reorder steps to reduce the business risk of a dirty read | Don't issue the ticket, which other systems trust, until after the charge |
| Reread value | Before writing, reread the record and abort if it changed (optimistic locking) | Reread the fare before charging; restart if it changed |
| Version file | Record operations as they arrive so they can be reordered | The tombstone above is a tiny version file: it remembers the cancel came first |
| By value | Pick the mechanism per request by business risk | Use a distributed lock for a high-value group booking, a plain saga otherwise |
Here is the dirty read and the semantic lock that fixes it. Saga A holds the last seat; saga B looks at the same seat while A is still running; then A's card is declined and A releases the seat.
Python
def last_seat(semantic_lock: bool) -> None:
seat = {"state": "free", "owner": None}
# Saga A holds the last seat. That local transaction commits right away.
seat.update(state="pending" if semantic_lock else "taken", owner="trip-A")
# Saga B looks at the same seat while A is still running.
if seat["state"] == "taken":
b = "told customer B: sold out"
else: # "pending": someone's saga might still give it back
b = "customer B waitlisted, recheck when trip-A finishes"
# Saga A's card is declined. Compensation frees the seat.
seat.update(state="free", owner=None)
if b.startswith("customer B waitlisted") and seat["state"] == "free":
seat.update(state="pending", owner="trip-B")
b += " -> got the seat"
print(f" {b}; seat now {seat['state']} (owner {seat['owner']})")
print("no semantic lock (B reads A's uncommitted saga as final)")
last_seat(semantic_lock=False)
print("semantic lock (a *_PENDING state says 'a saga is using this')")
last_seat(semantic_lock=True)
no semantic lock (B reads A's uncommitted saga as final)
told customer B: sold out; seat now free (owner None)
semantic lock (a *_PENDING state says 'a saga is using this')
customer B waitlisted, recheck when trip-A finishes -> got the seat; seat now pending (owner trip-B)
C#
Console.WriteLine("no semantic lock (B reads A's uncommitted saga as final)");
LastSeat(semanticLock: false);
Console.WriteLine("semantic lock (a *_PENDING state says 'a saga is using this')");
LastSeat(semanticLock: true);
static void LastSeat(bool semanticLock)
{
var seat = new Seat("free", null);
// Saga A holds the last seat. That local transaction commits right away.
seat = new Seat(semanticLock ? "pending" : "taken", "trip-A");
// Saga B looks at the same seat while A is still running.
var b = seat.State == "taken"
? "told customer B: sold out"
: "customer B waitlisted, recheck when trip-A finishes";
// Saga A's card is declined. Compensation frees the seat.
seat = new Seat("free", null);
if (b.StartsWith("customer B waitlisted") && seat.State == "free")
{
seat = new Seat("pending", "trip-B");
b += " -> got the seat";
}
Console.WriteLine($" {b}; seat now {seat.State} (owner {seat.Owner ?? "None"})");
}
record Seat(string State, string? Owner);
no semantic lock (B reads A's uncommitted saga as final)
told customer B: sold out; seat now free (owner None)
semantic lock (a *_PENDING state says 'a saga is using this')
customer B waitlisted, recheck when trip-A finishes -> got the seat; seat now pending (owner trip-B)
Without the lock, customer B was told "sold out" for a seat that was free a moment later. With it, B could tell the seat was only maybe taken and waited. The semantic lock doesn't block anything by itself. It gives other code enough information to make a better choice: wait, retry, waitlist, or go ahead and accept the risk. The cost is that every reader now has to handle pending, and you need a way to clear locks left behind by sagas that died. The saga deadline from the last section is that way.
Persisting saga state
The orchestrator in the demo saves status and cursor after every step. A real saga record usually carries:
- Saga id, used as the correlation id on every message and as the base of every idempotency key.
- Status (running, compensating, completed, compensated, failed) and the current step.
- Data the steps produced: the seat hold id, the room confirmation number, the payment id. Compensations need them. "Cancel the room" needs to know which room.
- Deadline, so a restarted process can find sagas whose time ran out.
- A version for optimistic concurrency, so two orchestrator instances handling replies for the same saga can't both win.
- Updated-at, for finding stuck sagas.
One more trap: saving the new state and sending the next command are a dual write. If the orchestrator commits "step 2 sent" and crashes before sending, the saga waits forever; if it sends and crashes before committing, it sends again on restart. Put the command in an outbox in the same transaction as the saga state, and make the participant idempotent for the duplicates. Workflow engines do this bookkeeping for you, which is a big part of their value.
Observability
A saga that fails silently is a held seat nobody is paying for. Make them visible:
- One correlation id per saga in every message, log line and trace. Propagate the trace context through the broker so one trip is one distributed trace.
- The saga table is a dashboard. Count by status. Watch the compensation rate: a sudden rise is a failing dependency. Show time spent in
compensating. - Find stuck sagas: status
runningorcompensatingwithupdated_atolder than the deadline. That query is your most useful alert. - Alert on "compensation failed" as a page, not a log line. It means real-world inconsistency that a person must fix.
- Record every step's outcome (start, success, failure, retry count) with the saga id, so "why was trip-2 refunded?" has an answer.
Engines: when to stop hand-rolling
The demo orchestrator is fine for learning and for small sagas. For anything long-lived, a workflow engine gives you durable state, durable timers, retries and history.
- Azure Durable Functions. Orchestrators are ordinary C# (or Python, JavaScript, Java or PowerShell) functions that are replayed from history after a restart, so they must be deterministic. Part 4 builds a complete order saga with it, including retries, timeouts and human intervention.
- Temporal. Same model (workflow code replayed from an event history, activities retried by policy) with SDKs for Go, Java, TypeScript, Python, .NET and others. Compensation is ordinary code: collect undo steps as you go and run them in reverse on failure.
- MassTransit state machines (C#). A saga is a state machine with states, events and transitions, persisted through a repository (Entity Framework Core, MongoDB, Redis and others). It suits choreography-flavoured sagas that react to many events, and it has scheduled messages for timeouts and an outbox to pair state changes with sends.
In Python, the main options are the Temporal Python SDK or hand-rolled: a saga table and an outbox like the ones in this post and the last, with a worker that resumes sagas after a restart.
This is the trip as a Temporal workflow in Python. Not run (it needs a Temporal server and a worker with the activities registered):
# Not run: needs the temporalio package, a Temporal server, and a worker
# that registers the activities named below.
from datetime import timedelta
from temporalio import workflow
from temporalio.common import RetryPolicy
from temporalio.exceptions import ActivityError
STEP = timedelta(seconds=30)
PIVOT_RETRY = RetryPolicy(non_retryable_error_types=["CardDeclined"])
@workflow.defn
class TripSaga:
@workflow.run
async def run(self, trip_id: str) -> str:
undo: list[str] = []
try:
# Register the compensation BEFORE the call: if the call times out,
# it may still have happened, so the undo must run either way.
undo.append("release_seat")
await workflow.execute_activity("hold_seat", trip_id, start_to_close_timeout=STEP)
undo.append("cancel_room")
await workflow.execute_activity("book_room", trip_id, start_to_close_timeout=STEP)
await workflow.execute_activity("charge_card", trip_id, # the pivot
start_to_close_timeout=STEP, retry_policy=PIVOT_RETRY)
except ActivityError:
for name in reversed(undo): # backward recovery; activities retry by default
await workflow.execute_activity(name, trip_id, start_to_close_timeout=STEP)
return "compensated"
# Past the pivot: forward recovery. Default retry policy retries without limit.
await workflow.execute_activity("issue_ticket", trip_id, start_to_close_timeout=STEP)
return "completed"
Every lesson from the runnable demos is in there: compensations registered before the call (the timeout lesson), newest-first undo, a pivot whose business "no" isn't retried, and unlimited retries after the pivot. The engine adds the durability. The idempotency is still yours: every activity should use the workflow id and step name as its key.
When not to use a saga
Sagas are a lot of machinery. Skip them when:
- The data can live in one database. If the steps belong to one service, use one local ACID transaction. Splitting a service in a way that needs a saga for its core operation is often a sign the boundary is in the wrong place.
- You only need "do this, then tell them". One local change plus a reliable notification is an outbox, not a saga.
- There's no meaningful compensation and no safe pivot. If you can't undo a step and can't move it after a go/no-go point, a saga only hides the problem. Redesign the steps (holds with expiry, reservations) or keep that operation synchronous with a human in the loop.
- You need strict isolation. If other code must never see in-between states (moving money between two accounts in the same ledger, for example), use a single transaction or a lock. Countermeasures reduce the anomalies; they don't remove them.
- The flow is two steps. A command and a reply with a retry is enough. Add a saga when a third step and a compensation appear.
Check yourself: questions and answers
1. Why not use two-phase commit across services?
It holds locks across network calls for the whole commit, blocks participants when the coordinator fails, makes the transaction only as available as every participant at once, and most brokers, cloud stores and third-party APIs can't take part in it anyway.
2. What does a saga give up compared with an ACID transaction?
Isolation. Each step commits locally, so other transactions can see the in-between states. Atomicity becomes "all steps, or the completed ones compensated", and it's eventual.
3. What is the pivot transaction, and why does its position matter?
It's the go/no-go step: if it succeeds, the saga runs to completion; if it fails, the saga compensates. Steps before it must be compensatable, steps after it must be retriable until they succeed. Put the risky checks before it and only steps that can't say no after it.
4. A step after the pivot keeps timing out. Do you compensate?
No. Retry with backoff and alert. Compensating after the pivot means undoing the commitment the pivot made, such as refunding a customer whose trip is fine. If the step can fail for a business reason, the pivot is in the wrong place.
5. The orchestrator crashed between a participant doing the work and the orchestrator saving that fact. What happens on restart?
It calls the step again. That can't be avoided, so the participant must be idempotent on a key like the saga id plus step name, and return the first result for a repeat.
6. A step timed out and you compensated. Then the original request succeeds. How do you stop the orphan?
Send the compensation for any request whose outcome is unknown, and make the participant record a tombstone when it gets a cancel for something it hasn't seen. A later request with that key is refused.
7. What is a semantic lock?
A compensatable step marks the record as in use (PENDING) instead of final. Other transactions see that and choose to wait, retry or accept the risk, instead of treating the saga's half-done work as committed.
8. Choreography or orchestration?
Choreography for short, stable flows owned by one team. Orchestration once there are several steps, a pivot and compensations, because the flow, the timeouts and the "where is it stuck?" answer live in one place.
Further reading
- Hector Garcia-Molina and Kenneth Salem, Sagas, ACM SIGMOD 1987: the original paper
- Chris Richardson, microservices.io: Saga and Transactional outbox; his book Microservices Patterns covers step types and countermeasures in chapter 4
- Azure Architecture Center: Saga distributed transactions pattern and Compensating Transaction pattern
- Microsoft Learn: Durable Functions overview
- Temporal: documentation and the Python SDK guide
- MassTransit: saga state machines
- On this blog: The Transactional Outbox in Depth, Part 3, saga orchestration and Part 4, sagas with Durable Functions
Thoughts on this?
Tell me on X: @bobbyencoded · Share this post on X
Want more like this? Subscribe to The Decode, a weekly email on the AI and developer news worth your time.