Seats A-12 and A-13 are held, Budi's card has been charged $150, and then the ticket service refuses to issue the e-tickets. There's no single transaction to roll back, because every step lives in a different service and database. So how do you back out?
It's like planning a holiday: book a hotel, then a flight, then a rental car. Three companies, three systems, no single "cancel everything" button. If the car rental is refused, you cancel the flight yourself, then the hotel. Every booking has its own way to cancel, and the cancellation is itself a new transaction (a refund), not erasing history.
This approach is called a saga: running one business process that touches several services without one big transaction. The process is split into a sequence of local transactions, one per service, and every step has a compensating action (a compensation) that cancels it. If one step fails, the steps that already succeeded are cancelled one by one, in reverse order.
TicketTune checkout: three services, three databases
In the Distributed Transactions lesson we saw why two-phase commit doesn't suit TicketTune: every participant stays locked waiting for one coordinator. So checkout runs as a saga. Every service has its own database, and every step commits to it right away:
| Step | Service | Action (local transaction) | Compensation |
|---|---|---|---|
| 1 | concert |
HoldSeats: A-12, A-13 become HELD |
ReleaseSeats |
| 2 | payment |
ChargeCard: $150 |
Refund $150 |
| 3 | ticket |
IssueTickets: 2 e-tickets, holders' national ID numbers checked |
CancelTickets |
A compensation is not a magic "undo". A charged card can't be made as if it was never charged; what you can do is a new transaction that gives the money back. That's why it's called a compensating transaction.
Fails at step 3: compensate in reverse order
In this example model, one trip across the network takes 10 ms, concert works for 20 ms, payment for 120 ms (charging the card) and 100 ms (a refund), ticket for 60 ms. The order service coordinates, and the second ticket holder's national ID number turns out to be invalid:
| ms | Message | What it causes |
|---|---|---|
| 0 | order -> concert: HoldSeats |
|
| 40 | concert -> order: SeatsHeld |
free seats go from 10,000 to 9,998 |
| 180 | payment -> order: CardCharged |
Budi's card -$150 |
| 260 | ticket -> order: rejected, 422 invalid national ID |
no e-tickets issued |
| 380 | payment -> order: RefundDone |
Budi's card back to $0 |
| 420 | concert -> order: SeatsReleased |
seats back to 10,000 |
So the first thing cancelled is the payment, then the seats. The last step that succeeded is undone first. Why? Because every state along the way is then one the saga really passed through going forward: "seats held, card charged", then "seats held, card untouched", then "nothing". If the seats were released first, there would be a moment when Budi's card is charged while his seats can already be bought by someone else.
The rule holds for any order: if a saga runs charge, then reserve stock, then shipping, and shipping fails, the stock is released first, then the payment is refunded. The step that failed needs no compensation itself: its local transaction never committed.
The orchestrator's code
// Checkout saga #1001 (orchestration): ticket rejects at step 3
const db = { seats: 10000, budiCard: 0, eTickets: 0 };
const steps = [
{ svc: "concert", action: "HoldSeats", undo: "ReleaseSeats",
run: () => (db.seats -= 2), compensate: () => (db.seats += 2) },
{ svc: "payment", action: "ChargeCard", undo: "Refund",
run: () => (db.budiCard -= 150), compensate: () => (db.budiCard += 150) },
{ svc: "ticket", action: "IssueTickets", undo: "CancelTickets",
run: () => { throw new Error("422 invalid ticket holder national ID"); }, compensate: () => (db.eTickets -= 2) },
];
function sagaCheckout() {
const done = []; // steps that committed, in order
for (const l of steps) {
try {
l.run();
console.log(l.svc + ": " + l.action + " succeeded");
done.push(l);
} catch (err) {
console.log(l.svc + ": " + l.action + " rejected, " + err.message);
for (const s of done.reverse()) {
s.compensate(); // compensate, in reverse order
console.log(s.svc + ": " + s.undo);
}
return "CANCELLED";
}
}
return "PAID";
}
console.log("order #1001:", sagaCheckout());
console.log(db); // { seats: 10000, budiCard: 0, eTickets: 0 }
Its output: concert: HoldSeats succeeded, payment: ChargeCard succeeded, ticket: IssueTickets rejected, 422 invalid ticket holder national ID, payment: Refund, concert: ReleaseSeats, order #1001: CANCELLED.
- Every item in
stepspairs an action with its compensation. A saga step with no compensation is a step that can't be cancelled. donerecords the steps that committed. Only those are compensated.done.reverse()flips their order: Refund first, ReleaseSeats after.- In a real system,
ordersaves the saga's position to the database every time a reply comes in (a state machine). If the process crashes after CardCharged, it knows on restart to go on with step 3, not start over.
Orchestration vs choreography
There are two ways to arrange who calls whom:
- Orchestration: one central coordinator, here
OrderSagain theorderservice, sends a command to each service, waits for its reply, and decides on compensations. The flow is explicit in one file, and every saga's state can be read from one table. - Choreography: no coordinator. Every service listens for events and reacts on its own, as in the Event-Driven Architecture lesson:
concerthears OrderCreated and publishes SeatsHeld,paymenthears SeatsHeld, and so on. On failure,ticketpublishes TicketsRejected,paymenthears it and refunds,concerthears PaymentRefunded and releases the seats.
For the same failure, orchestration needs 10 messages (5 commands, 5 replies) and finishes at ms 420. Choreography needs only 6 events and finishes at ms 380. The price: the rule "on TicketsRejected, refund" lives in payment, the rule "on PaymentRefunded, release the seats" lives in concert. To know where order #1001 is right now, you have to piece together events from four services.
The practical rule of thumb: choreography for short chains (2 to 3 steps) whose services should not know each other; orchestration for sagas of more than 3 steps, or when the team often struggles to find at which step an order failed. An explicit flow is easier to debug.
Compensations must be idempotent
Remember the Why Distributed Systems Are Hard lesson: a response can get lost on the way. Say payment has refunded $150 at ms 370, but its reply is lost. order waits 2,000 ms, times out, and sends Refund again. With no safeguard, payment refunds again: Budi receives $300 for a $150 payment. Choreography is worse: the broker redelivers TicketsRejected, payment publishes PaymentRefunded twice, and concert releases the seats twice. Free seats become 10,002, two phantom seats that can be sold.
The fix is the same as in the Idempotency & Retry Safety lesson: every compensation carries an Idempotency-Key, for example refund-1001. payment stores the result per key; a second delivery with the same key only gets the stored result, and no money goes out again. An idempotent compensation can be called many times with the same result, and that's mandatory, because retries will happen.
If a compensation keeps failing (say the bank is down), don't give up silently: retry with a pause, then move it to a dead letter queue for a human to check (Message Queue lesson).
📌 A saga has no isolation
An ordinary database transaction hides half-done changes from everyone else. A saga can't: as soon as step 1 commits, other buyers already see A-12 as HELD. So the in-between states are made explicit: the seat's status is HELD (not SOLD) and the order's is WAITING_FOR_PAYMENT until the saga finishes. Other pages read that status and don't treat it as final. Put the step most likely to be rejected first, and a step that can't be undone (sending an email) last.
🎯 Saga checklist
- Save the saga state to the database at every step, so a crash can be resumed.
- A correlation ID (here the saga number #1001) on every command and event, so one saga can be traced across services (Observability in Distributed Systems lesson).
- Idempotent compensations, tested: the part with the most bugs.
- A timeout on every step: never wait forever.
- A dead letter queue for compensations that still fail.
⚠️ Double refunds and ghost seats
- Compensations that aren't idempotent. A retry after a timeout means a double refund or phantom seats.
- Compensating in the same order, not the reverse. Releasing the seats before the refund leaves a moment when Budi has paid with no seats.
- Saga state only in memory. The orchestrator crashes, the saga is gone: seats held and money taken with nobody to finish.
- Treating a compensation as deleting a row. A refund is a new transaction with its own record; the trace of the first payment stays.
TL;DR: A saga runs a cross-service process as a sequence of local transactions, each with a compensation. Checkout #1001: HoldSeats (concert), ChargeCard (payment), IssueTickets (ticket). If ticket rejects, the steps that succeeded are undone in reverse order: Refund first, ReleaseSeats after; the failed step needs no compensation. Orchestration: one coordinator sends commands, the flow is explicit and easy to debug, a fit for sagas of more than 3 steps. Choreography: services react to events, fewer messages and looser coupling, but the flow is spread out, a fit for short chains. Compensations must be idempotent (an Idempotency-Key like refund-1001), because a retry after a timeout can refund twice. Save the saga state to the database, add a correlation ID and timeouts, and send compensations that still fail to a dead letter queue.
⚡ Local transactions, each with a compensation
Meaning: A saga splits a cross-service process into a sequence of local transactions that commit right away: HoldSeats in concert, ChargeCard in payment, IssueTickets in ticket. Every step has a compensation. A compensation isn't a magic undo: Refund is a new transaction that gives the money back.
⚡ Compensate in reverse order
Write:
for (const s of done.reverse()) {
s.compensate(); // compensate, in reverse order
console.log(s.svc + ": " + s.undo);
}
Guess first: the saga runs charge, then reserve stock, then shipping, and shipping fails. What gets undone first?
The stock is released first, then the payment is refunded. The last step that succeeded is undone first, and the step that failed needs no compensation.
Meaning: In reverse order, every state along the way is one the saga really passed through going forward.
⚡ Orchestration or choreography
Meaning: Orchestration: one coordinator sends commands to each service, the flow is explicit and easy to debug, a fit for sagas of more than 3 steps. Choreography: services react to events, fewer messages but the flow is spread out, a fit for short chains.
⚡ Compensations must be idempotent
Meaning: The Refund reply can get lost, and order sends Refund again after a timeout. With no safeguard, Budi receives $300. Every compensation carries an Idempotency-Key, such as refund-1001.