Keep data consistent across services that each own their own database. Replace one distributed ACID transaction with an ordered series of local transactions. Every step before the point of no return has a compensating action, and every step after it is retried until it succeeds.
A saga splits one business transaction into a sequence of local transactions, each owned by a single service. If a later step fails, the saga runs compensating actions that semantically undo the earlier steps. It does not provide atomicity or isolation. It provides an explicit, recoverable path to a consistent end state. This guide follows one invented system the whole way through: Quayside, a berth-booking platform for marinas. You will see what broke when bookings crossed four services without coordination, how an orchestrated saga fixed it, where choreography would have been the better fit, and what an interviewer expects you to say about pivots, idempotency, isolation and recovery.
The problem
A situation where the obvious design starts to hurt.
Quayside sells berths at 140 marinas. On Friday mornings at 08:00 the next month's berths are released, and the booking endpoint takes roughly 900 bookings a minute for about ten minutes. A booking touches four services. Berths holds berth C-14 for the requested nights. Payments authorizes and then captures a 150 EUR deposit through an external payment provider. Access issues a gate PIN for the pontoon. Notifications sends the confirmation.
The first version was a single HTTP handler in the Booking API that called each service in turn. Each service has its own Postgres database, and the payment provider has no two-phase commit, so the handler had no way to wrap the four calls in one transaction. It just hoped they all succeeded.
One July release, the Access database failed over and was unavailable for about four minutes. The handler had already held the berth and captured the deposit. When the gate PIN call timed out, it returned a 500 and stopped. Nothing released the hold, and nothing refunded the money. In that window 312 boaters were charged for bookings the app reported as failed. Their berths showed as taken, so other customers could not book them either. Support spent three days refunding deposits by hand and freeing holds with SQL.
The root issue was not the outage. The system had no record of how far each booking had progressed and no defined way to undo the parts that had already happened.
The solution
What the pattern proposes.
Model the booking as a saga with an explicit, persisted state. Each step is a local transaction in one service, paired with a compensating action.
reserve_berth places a hold with a 20 minute TTL. Its compensation releases the hold. authorize_deposit puts an authorization on the card without capturing it. Its compensation voids the authorization. issue_gate_code creates a PIN in the pending state. Its compensation revokes the PIN. capture_deposit is the pivot: once money is captured, Quayside commits to the booking and never unwinds it. send_confirmation comes after the pivot. It has no compensation and is retried until it succeeds.
The ordering is deliberate. Cheap, easily reversed steps go first, and the step with the most painful undo (a refund instead of a void) becomes the pivot. Everything after the pivot must be retriable to success.
Quayside uses orchestration. A Saga Orchestrator service owns a state machine per booking. It writes each transition to a saga log table and sends commands to participants over a message bus, using the transactional outbox so the state write and the command publish cannot diverge. Participants reply with success or failure. On failure before the pivot, the orchestrator runs compensations in reverse order. Every command carries the key sagaId plus step name, so participants can deduplicate redeliveries. A recovery worker scans for sagas with no progress in 2 minutes and resumes them from the log.
The alternative is choreography. There is no coordinator: Berths publishes BerthHeld, Payments reacts and publishes DepositAuthorized, and so on, and each service listens for failure events to compensate itself. This works well for two or three steps owned by one team. With four or more steps, a pivot and timeouts, the flow becomes hard to trace and change, so Quayside centralised it.
An everyday analogy
The same idea, outside software.
Think of a stage manager running a quick costume change during a play. They have a written cue sheet: unhook the cape, swap the wig, hand over the sword, push the actor back on stage. If the wig is missing, they work the sheet backwards: re-hook the cape and send the actor back out in the old look. Once the actor has stepped into the light, there is no going back, and the only option is to finish the scene. The cue sheet is the saga log, the stage manager is the orchestrator, and stepping into the light is the pivot. Choreography is the same change with no stage manager, where each dresser watches the others and reacts.
Structure
The pieces and how they relate.
Participants
- Saga orchestrator
- Owns the booking state machine. It decides the next command, applies replies, triggers compensations in reverse order on failure before the pivot, and keeps retrying forward after it. It holds no business data beyond the saga context.
- Saga log and outbox
- Durable record of every step transition, written in the same local transaction as the outbox row that carries the next command. This is what lets a restarted orchestrator know exactly where each booking stopped.
- Participant services (Berths, Payments, Access, Notifications)
- Each runs its step as a local transaction in its own database and exposes a matching compensation. Both must be idempotent per sagaId plus step, and a compensation must succeed as a no-op if the action never happened.
- Command and reply bus
- Decouples the orchestrator from participant availability. During the Access failover, commands wait in the topic instead of failing an HTTP call in a user request.
- Recovery worker
- Finds sagas whose last transition is older than 2 minutes and re-sends the pending command or compensation. It turns orchestrator crashes and lost replies into delays rather than stuck money.
- Payment provider
- External system that cannot join a distributed transaction. Its own idempotency keys make authorize, void and capture safe to retry from Payments.
Pseudocode
The solution to the scenario, language-neutral.
steps = [
reserve_berth (compensate: release_hold),
authorize_deposit (compensate: void_authorization),
issue_gate_code (compensate: revoke_pin),
capture_deposit (pivot, no compensation),
send_confirmation (retry until success)
]
function run(sagaId, ctx):
completed = []
for i, step in steps:
log.record(sagaId, step, STARTED)
try:
if i > pivotIndex:
retry_with_backoff(step.action(ctx, key = sagaId + step))
else:
step.action(ctx, key = sagaId + step)
log.record(sagaId, step, DONE)
completed.append(step)
catch error:
log.record(sagaId, step, FAILED)
if i > pivotIndex:
return NEEDS_ATTENTION // recovery worker keeps pushing forward
completed.append(step) // a timeout may mean it half-happened
return compensate(sagaId, completed, ctx)
return COMPLETED
function compensate(sagaId, completed, ctx):
clean = true
for step in reverse(completed):
if step has no compensation: continue
try:
retry_with_backoff(step.compensate(ctx, key = sagaId + step + ":undo"))
log.record(sagaId, step, COMPENSATED)
catch:
log.record(sagaId, step, COMPENSATION_FAILED) // page on-call, manual queue
clean = false
return clean ? COMPENSATED : NEEDS_ATTENTION
recovery_worker every 30s:
for saga in log.where(state not terminal and updated_at < now - 2 min):
orchestrator.resume(saga)The code
The same solution in TypeScript, Python and PHP.
type Ctx = Record<string, string>;
type Status = "started" | "done" | "failed" | "compensated" | "compensation_failed";
type Outcome = "completed" | "compensated" | "needs_attention";
interface Step {
name: string;
action: (ctx: Ctx) => Promise<void>;
compensate?: (ctx: Ctx) => Promise<void>;
}
interface SagaLog {
record(sagaId: string, step: string, status: Status): Promise<void>;
}
class MemoryLog implements SagaLog {
readonly entries: string[] = [];
async record(sagaId: string, step: string, status: Status): Promise<void> {
this.entries.push(`${sagaId} ${step} ${status}`);
}
}
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
async function withRetry(fn: () => Promise<void>, attempts: number, baseMs: number): Promise<void> {
let lastError: unknown;
for (let i = 0; i < attempts; i++) {
try {
await fn();
return;
} catch (err) {
lastError = err;
if (i < attempts - 1) await sleep(baseMs * 2 ** i);
}
}
throw lastError;
}
class SagaOrchestrator {
constructor(
private readonly steps: Step[],
private readonly pivotIndex: number,
private readonly log: SagaLog,
private readonly attempts = 3,
private readonly baseMs = 20,
) {}
async run(sagaId: string, ctx: Ctx): Promise<Outcome> {
const completed: Step[] = [];
for (let i = 0; i < this.steps.length; i++) {
const step = this.steps[i];
await this.log.record(sagaId, step.name, "started");
try {
if (i > this.pivotIndex) {
await withRetry(() => step.action(ctx), this.attempts, this.baseMs);
} else {
await step.action(ctx);
}
await this.log.record(sagaId, step.name, "done");
completed.push(step);
} catch {
await this.log.record(sagaId, step.name, "failed");
// Past the pivot we never undo: the recovery worker keeps pushing forward.
if (i > this.pivotIndex) return "needs_attention";
// A timeout may mean the step half-happened, so compensate it too.
completed.push(step);
return this.compensate(sagaId, completed, ctx);
}
}
return "completed";
}
private async compensate(sagaId: string, steps: Step[], ctx: Ctx): Promise<Outcome> {
let clean = true;
for (const step of [...steps].reverse()) {
const undo = step.compensate;
if (!undo) continue;
try {
await withRetry(() => undo(ctx), this.attempts, this.baseMs);
await this.log.record(sagaId, step.name, "compensated");
} catch {
await this.log.record(sagaId, step.name, "compensation_failed");
clean = false;
}
}
return clean ? "compensated" : "needs_attention";
}
}
// Demo: the access service times out, so the saga voids the deposit and releases the hold.
const steps: Step[] = [
{
name: "reserve_berth",
action: async (ctx) => { ctx.holdId = `hold-${ctx.berth}`; },
compensate: async (ctx) => { if (ctx.holdId) console.log(`release ${ctx.holdId}`); },
},
{
name: "authorize_deposit",
action: async (ctx) => { ctx.authId = "auth-5521"; },
compensate: async (ctx) => { if (ctx.authId) console.log(`void ${ctx.authId}`); },
},
{
name: "issue_gate_code",
action: async () => { throw new Error("access service timeout"); },
compensate: async (ctx) => { console.log(`revoke gate code for ${ctx.bookingId} if any`); },
},
{ name: "capture_deposit", action: async (ctx) => { console.log(`capture ${ctx.authId}`); } },
{ name: "send_confirmation", action: async (ctx) => { console.log(`confirm ${ctx.bookingId}`); } },
];
async function main(): Promise<void> {
const log = new MemoryLog();
const saga = new SagaOrchestrator(steps, 3, log);
const outcome = await saga.run("saga-bk-7781", { bookingId: "bk-7781", berth: "C-14" });
console.log(outcome);
console.log(log.entries.join("\n"));
}
main();import asyncio
from dataclasses import dataclass
from functools import partial
from typing import Awaitable, Callable, Optional, Protocol
Ctx = dict[str, str]
Fn = Callable[[Ctx], Awaitable[None]]
@dataclass(frozen=True)
class Step:
name: str
action: Fn
compensate: Optional[Fn] = None
class SagaLog(Protocol):
async def record(self, saga_id: str, step: str, status: str) -> None: ...
class MemoryLog:
def __init__(self) -> None:
self.entries: list[str] = []
async def record(self, saga_id: str, step: str, status: str) -> None:
self.entries.append(f"{saga_id} {step} {status}")
async def with_retry(fn: Callable[[], Awaitable[None]], attempts: int, base_ms: int) -> None:
last_error: Optional[Exception] = None
for i in range(attempts):
try:
await fn()
return
except Exception as err:
last_error = err
if i < attempts - 1:
await asyncio.sleep(base_ms * 2**i / 1000)
assert last_error is not None
raise last_error
class SagaOrchestrator:
def __init__(self, steps: list[Step], pivot_index: int, log: SagaLog,
attempts: int = 3, base_ms: int = 20) -> None:
self.steps = steps
self.pivot_index = pivot_index
self.log = log
self.attempts = attempts
self.base_ms = base_ms
async def run(self, saga_id: str, ctx: Ctx) -> str:
completed: list[Step] = []
for i, step in enumerate(self.steps):
await self.log.record(saga_id, step.name, "started")
try:
if i > self.pivot_index:
await with_retry(partial(step.action, ctx), self.attempts, self.base_ms)
else:
await step.action(ctx)
await self.log.record(saga_id, step.name, "done")
completed.append(step)
except Exception:
await self.log.record(saga_id, step.name, "failed")
# Past the pivot we never undo: the recovery worker keeps pushing forward.
if i > self.pivot_index:
return "needs_attention"
# A timeout may mean the step half-happened, so compensate it too.
completed.append(step)
return await self._compensate(saga_id, completed, ctx)
return "completed"
async def _compensate(self, saga_id: str, steps: list[Step], ctx: Ctx) -> str:
clean = True
for step in reversed(steps):
if step.compensate is None:
continue
try:
await with_retry(partial(step.compensate, ctx), self.attempts, self.base_ms)
await self.log.record(saga_id, step.name, "compensated")
except Exception:
await self.log.record(saga_id, step.name, "compensation_failed")
clean = False
return "compensated" if clean else "needs_attention"
# Demo: the access service times out, so the saga voids the deposit and releases the hold.
async def reserve_berth(ctx: Ctx) -> None:
ctx["hold_id"] = f"hold-{ctx['berth']}"
async def release_hold(ctx: Ctx) -> None:
if "hold_id" in ctx:
print(f"release {ctx['hold_id']}")
async def authorize_deposit(ctx: Ctx) -> None:
ctx["auth_id"] = "auth-5521"
async def void_authorization(ctx: Ctx) -> None:
if "auth_id" in ctx:
print(f"void {ctx['auth_id']}")
async def issue_gate_code(ctx: Ctx) -> None:
raise TimeoutError("access service timeout")
async def revoke_gate_code(ctx: Ctx) -> None:
print(f"revoke gate code for {ctx['booking_id']} if any")
async def capture_deposit(ctx: Ctx) -> None:
print(f"capture {ctx['auth_id']}")
async def send_confirmation(ctx: Ctx) -> None:
print(f"confirm {ctx['booking_id']}")
async def main() -> None:
steps = [
Step("reserve_berth", reserve_berth, release_hold),
Step("authorize_deposit", authorize_deposit, void_authorization),
Step("issue_gate_code", issue_gate_code, revoke_gate_code),
Step("capture_deposit", capture_deposit),
Step("send_confirmation", send_confirmation),
]
log = MemoryLog()
saga = SagaOrchestrator(steps, pivot_index=3, log=log)
outcome = await saga.run("saga-bk-7781", {"booking_id": "bk-7781", "berth": "C-14"})
print(outcome)
print("\n".join(log.entries))
if __name__ == "__main__":
asyncio.run(main())<?php
declare(strict_types=1);
final class Step
{
public function __construct(
public readonly string $name,
public readonly Closure $action,
public readonly ?Closure $compensate = null,
) {
}
}
interface SagaLog
{
public function record(string $sagaId, string $step, string $status): void;
}
final class MemoryLog implements SagaLog
{
/** @var list<string> */
public array $entries = [];
public function record(string $sagaId, string $step, string $status): void
{
$this->entries[] = "{$sagaId} {$step} {$status}";
}
}
function withRetry(Closure $fn, int $attempts, int $baseMs): void
{
$lastError = new RuntimeException('no attempts made');
for ($i = 0; $i < $attempts; $i++) {
try {
$fn();
return;
} catch (Throwable $e) {
$lastError = $e;
if ($i < $attempts - 1) {
usleep($baseMs * 1000 * (2 ** $i));
}
}
}
throw $lastError;
}
final class SagaOrchestrator
{
/** @param list<Step> $steps */
public function __construct(
private readonly array $steps,
private readonly int $pivotIndex,
private readonly SagaLog $log,
private readonly int $attempts = 3,
private readonly int $baseMs = 20,
) {
}
public function run(string $sagaId, ArrayObject $ctx): string
{
$completed = [];
foreach ($this->steps as $i => $step) {
$this->log->record($sagaId, $step->name, 'started');
try {
if ($i > $this->pivotIndex) {
withRetry(fn () => ($step->action)($ctx), $this->attempts, $this->baseMs);
} else {
($step->action)($ctx);
}
$this->log->record($sagaId, $step->name, 'done');
$completed[] = $step;
} catch (Throwable) {
$this->log->record($sagaId, $step->name, 'failed');
// Past the pivot we never undo: the recovery worker keeps pushing forward.
if ($i > $this->pivotIndex) {
return 'needs_attention';
}
// A timeout may mean the step half-happened, so compensate it too.
$completed[] = $step;
return $this->compensate($sagaId, $completed, $ctx);
}
}
return 'completed';
}
/** @param list<Step> $steps */
private function compensate(string $sagaId, array $steps, ArrayObject $ctx): string
{
$clean = true;
foreach (array_reverse($steps) as $step) {
$undo = $step->compensate;
if ($undo === null) {
continue;
}
try {
withRetry(fn () => $undo($ctx), $this->attempts, $this->baseMs);
$this->log->record($sagaId, $step->name, 'compensated');
} catch (Throwable) {
$this->log->record($sagaId, $step->name, 'compensation_failed');
$clean = false;
}
}
return $clean ? 'compensated' : 'needs_attention';
}
}
// Demo: the access service times out, so the saga voids the deposit and releases the hold.
$steps = [
new Step(
'reserve_berth',
function (ArrayObject $ctx): void { $ctx['holdId'] = 'hold-' . $ctx['berth']; },
function (ArrayObject $ctx): void {
if (isset($ctx['holdId'])) {
echo "release {$ctx['holdId']}\n";
}
},
),
new Step(
'authorize_deposit',
function (ArrayObject $ctx): void { $ctx['authId'] = 'auth-5521'; },
function (ArrayObject $ctx): void {
if (isset($ctx['authId'])) {
echo "void {$ctx['authId']}\n";
}
},
),
new Step(
'issue_gate_code',
function (ArrayObject $ctx): void { throw new RuntimeException('access service timeout'); },
function (ArrayObject $ctx): void { echo "revoke gate code for {$ctx['bookingId']} if any\n"; },
),
new Step('capture_deposit', function (ArrayObject $ctx): void { echo "capture {$ctx['authId']}\n"; }),
new Step('send_confirmation', function (ArrayObject $ctx): void { echo "confirm {$ctx['bookingId']}\n"; }),
];
$log = new MemoryLog();
$saga = new SagaOrchestrator($steps, 3, $log);
$outcome = $saga->run('saga-bk-7781', new ArrayObject(['bookingId' => 'bk-7781', 'berth' => 'C-14']));
echo $outcome . "\n";
echo implode("\n", $log->entries) . "\n";When to use it
Situations where it pays off.
One business operation writes to several services that each own a database, and you cannot or will not use a distributed transaction.
Two-phase commit needs every participant to support it and holds locks across the network. External APIs like payment providers will not take part, and database-per-service rules it out anyway.
Every step before the commit point has a meaningful business undo, such as releasing a hold, voiding an authorization or revoking a PIN.
A saga is only as good as its compensations. If a step cannot be undone, it has to become the pivot or move after the pivot, where it is retried forward.
The operation can take seconds to minutes or wait on slow external systems.
Holding database locks for that long would serialize the 08:00 burst. A saga commits each local step immediately and keeps progress in a log instead of in open transactions.
The business can tolerate a short window where intermediate state is visible, for example a berth shown as held for up to 20 minutes.
Sagas give up isolation. If an inconsistent intermediate view is unacceptable even briefly, keep the data in one service and one transaction.
Choose orchestration when there are four or more steps, a pivot, timeouts or frequent changes to the flow. Choose choreography for two or three loosely related reactions.
Orchestration puts the flow in one readable state machine. Choreography avoids a central component but spreads the flow across subscriptions, which becomes hard to trace as it grows.
How to implement it
Steps to introduce it in existing code.
Write the happy path as a list of local transactions, one service each, and name the business undo for each one. If a step has no undo, mark it.
Order the steps so reversible and cheap ones come first. Pick the pivot, the first step you will not compensate, and move anything that cannot fail for business reasons after it.
Give every step and compensation an idempotency key of sagaId plus step name, and make each compensation succeed as a no-op when its action never ran.
Persist saga state in the orchestrator's database and publish commands through a transactional outbox, so a crash between saving state and sending a message cannot lose or duplicate progress silently.
Use semantic locks for isolation: create records in a pending state (held berth, pending PIN) with a TTL, and only flip them to final after the pivot.
Set a deadline per step and per saga, for example 10 seconds per command and 15 minutes per booking. Run a recovery worker that resumes or compensates sagas that pass them.
Send compensations that keep failing to a manual-resolution queue with an alert. Never drop them, because each one represents money or inventory in the wrong state.
Pros and cons
What you gain and what you pay.
Pros
- Works across services with separate databases and external APIs that cannot join a distributed transaction.
- No long-held locks: each step commits locally, so the 08:00 burst is not serialized behind slow participants.
- Failures produce a defined end state, completed or compensated, instead of the half-done bookings that cost Quayside 312 manual refunds.
- The saga log gives a per-booking audit trail that support and on-call can read directly.
- Participants can be down briefly without failing the user request, because commands wait on the bus.
Cons
- No isolation: other requests can see intermediate state, so you need pending states, TTLs and UI wording to cover it.
- Every step needs a correct, idempotent compensation, which roughly doubles the API surface you must build and test.
- Eventual consistency changes the API: POST /bookings returns 202 and the app polls or listens for the outcome.
- Compensation is semantic, not a rollback. A captured charge can only be refunded, and the customer sees both lines on their statement.
- Orchestration adds a service and a database that must be highly available. Choreography removes them but makes the flow hard to follow.
Trade-offs
Decisions you'll have to make, each with its price.
Orchestration with a central saga orchestrator instead of choreography through domain events
You gainThe five-step booking flow lives in one state machine. Adding a step is one code change, and the saga log answers 'where is booking bk-7781' in a single query.
You payOne more service and Postgres database to run at high availability, and participants are coupled to the orchestrator's command contracts rather than just publishing their own events.
Asynchronous commands over a bus instead of synchronous HTTP from the orchestrator
You gainA 4 minute Access outage queues gate-code commands instead of failing bookings, and the 900 per minute burst is smoothed by consumer concurrency.
You payThe API returns 202 and the app must poll or subscribe. End-to-end p99 latency rises from roughly a second to several seconds under load.
Semantic lock: berth held with a 20 minute TTL until the pivot
You gainTwo boaters cannot both pay for C-14, without holding database locks across services.
You payIf a saga stalls, the berth looks unavailable for up to 20 minutes. Set the TTL too short and holds expire mid-saga, forcing the capture step to re-check the hold.
Authorize first, capture as the pivot, instead of capturing up front
You gainEvery failure before the pivot is undone with a void, which the customer never sees as a charge.
You payAuthorizations expire after a provider-specific window, typically days, so the saga must capture well before that, and an extra provider call per booking.
Retry budget of 5 attempts with exponential backoff for compensations, then manual queue
You gainTransient provider errors resolve automatically, and people handle only the genuinely stuck cases.
You payA persistent failure takes a couple of minutes of retries before it reaches a person, and the manual queue needs an owner and a runbook.
How it fails
What goes wrong in production and how to prevent it.
Orchestrator crashes after a participant completes a step but before recording the reply, leaving the saga stalled.
What to doPersist state per transition and run a recovery worker every 30 seconds that resumes sagas idle for over 2 minutes by re-sending the pending command. Idempotency on sagaId plus step makes the re-send harmless.
Command is redelivered and Payments authorizes the deposit twice.
What to doParticipants store processed keys (sagaId plus step) in the same transaction as the business change and return the stored result on duplicates. Payments also passes the key to the provider as its idempotency key.
Compensation keeps failing, for example the provider rejects a void because the authorization already expired.
What to doRetry with backoff up to the budget, then mark compensation_failed, alert on-call and put the saga in a manual queue with full context. Design an alternative path, such as a refund, for known terminal errors.
State saved but command never published because the process died between the database commit and the bus send.
What to doWrite the command into an outbox table in the same transaction as the saga state and let a relay publish it. The relay may publish twice, which idempotent participants absorb.
Berth hold expires while the saga waits on a slow Access service, and another boater books C-14 before capture.
What to doMake the capture step re-validate the hold inside Berths and fail before the pivot if it was lost, triggering compensation. Size the TTL above the per-saga deadline of 15 minutes.
A saga step is added or reordered while thousands of sagas are in flight, and old sagas resume with the new definition.
What to doStore a definition version on each saga and keep old versions runnable until no in-flight saga uses them. Never reuse step names for different behaviour.
In a system design interview
When to bring it up and how to explain it.
Bring it up when a design writes to more than one service or database for a single user action, such as booking, checkout, account provisioning or money movement, and the interviewer asks what happens if a later step fails. It is also the expected answer when someone proposes two-phase commit across microservices or third-party APIs.
What you could say
Each service owns its own database and the payment provider can't join a distributed transaction, so I'd model the booking as a saga. It's a sequence of local transactions, each with a compensating action. I'd order the steps so the cheap, reversible ones come first: hold the berth with a TTL, authorize the deposit, issue a pending gate PIN. Capturing the deposit is the pivot. Before it, any failure triggers compensations in reverse: revoke the PIN, void the authorization, release the hold. After it, I only retry forward, so the confirmation is retried until it succeeds. With five steps and a pivot I'd use orchestration rather than choreography, so the flow lives in one state machine I can monitor. The orchestrator persists state and publishes commands through an outbox, every command is idempotent on saga ID plus step, and a recovery worker resumes sagas that stop making progress. The thing I'd call out is that sagas give up isolation, so I'd use pending states and TTLs as semantic locks, and the API returns 202 while the client waits for the outcome.
Likely follow-ups
Why not just use two-phase commit?
It needs every participant to support a prepare phase. The payment provider does not, and with database-per-service we would be holding locks across the network during the burst. A coordinator failure during prepare also blocks participants. A saga accepts brief inconsistency in exchange for availability and no cross-service locks.
When would you pick choreography instead?
When the flow is two or three steps, each reaction clearly belongs to one service, and nobody needs a single view of progress, such as sending a welcome email and creating a loyalty account after signup. Once there is a pivot, deadlines or frequent changes, I would move to an orchestrator before the event chain becomes impossible to trace.
How do you deal with the lack of isolation?
With countermeasures rather than locks. Records are created in a pending state, like a held berth, and only become final after the pivot. Reads that matter, such as capture, re-validate the hold. Steps are ordered so the riskiest visible effect happens last, and the UI labels pending bookings honestly.
How do you test compensations?
I'd write contract tests per participant that call each compensation without the action and after a duplicated action, and check that both are safe. In staging I'd inject failures at every step index and assert that the saga ends in completed or compensated with no leftover holds or authorizations.
Relations with other guides
Patterns it's often confused or combined with.
- Transactional Outbox: Commit State and Events Together
The orchestrator writes saga state and the next command in one local transaction through an outbox, so a crash cannot leave state saved but the command unsent, or the other way round.
- Idempotency Keys: Making Retried Writes Safe
Commands are delivered at least once and the recovery worker re-sends them, so every action and compensation is keyed by sagaId plus step and deduplicated by the participant.
- Retry with Backoff: Exponential Delays, Jitter and Retry Budgets
Steps after the pivot and all compensations are retried with exponential backoff, because giving up on them leaves money or inventory inconsistent.
- Timeouts and Deadline Propagation
Per-step and per-saga deadlines turn a silent participant into an explicit failure that triggers compensation or recovery, instead of a saga that waits forever.
- State Pattern: Explicit State Machines Without the Switch Statements
The orchestrator is a state machine per saga: each state knows which command to send next and which transitions a reply or timeout can cause.
- Command Pattern: Turn Requests into Objects You Can Queue and Undo
Each step and its compensation are command objects with an execute and an undo, stored and replayed by the orchestrator in forward or reverse order.
Common questions
Short answers to the usual doubts.
Is a saga just a distributed transaction?
No. A distributed transaction such as two-phase commit gives atomicity and isolation by holding locks until every participant votes. A saga commits each step immediately and only promises that the whole thing ends either completed or compensated. In between, other requests can see partial results.
What is the pivot transaction?
It is the step after which the saga will not compensate. Steps before it must be compensatable. Steps after it must be retriable until they succeed. At Quayside it is capturing the deposit, because voiding an authorization is free but refunding a capture is slow and visible to the customer.
How do I handle a step that timed out but may have succeeded?
Treat it as possibly done. Make the action idempotent by sagaId plus step, and either retry it to learn the real outcome or run its compensation, which must be a safe no-op if the action never happened. Payments can query the provider by idempotency key before deciding whether to void.
Orchestration or choreography: which is the default?
Neither is universally better. Use choreography for short flows where each reaction is naturally owned by one service and nobody needs to see the whole flow. Use orchestration once you have a pivot, deadlines, four or more steps or a flow that product changes often, because then a single state machine is far easier to reason about and monitor.
Does the orchestrator become a single point of failure?
Only if its state lives in memory. With state in a replicated database and commands in an outbox, any orchestrator instance can pick up any saga. An outage delays bookings but does not corrupt them, and the recovery worker resumes them afterwards.
Now, practise it
Put it to work straight away.
Tests, exercises and problems that use what you've just read.
- Split a monolith across 6 teams in a yearSolve the exercise