What you'll learn: By the end of this lesson you will be able to explain who owns the flow in an orchestrated saga and in a choreographed one, write the steps and compensations of the same order flow both ways, say what each style stores and what it cannot see, predict what happens when a process dies mid-saga or an event is lost or delivered twice, and choose a style for a flow using a lab that runs the same ShopStream order seven ways against H2.
A restaurant kitchen can run an order two ways. In one, a head chef calls the dish: "grill, go; sauce, go; plate, go", and if the plate is dropped the head chef calls "bin the sauce". In the other there is no caller. The grill cook rings a bell when the steak is done, the sauce cook starts when the bell rings, and the plating cook watches for the sauce. Both kitchens turn out the same dinner on a good night. The difference shows when the plate is dropped, when a bell is not heard, or when a new cook joins: in the first kitchen you ask the head chef where the order is; in the second you walk the line.
Those are orchestration and choreography. The lesson Distributed Transactions: 2PC and Sagas introduces sagas and gives this choice a section. This lesson is the dedicated treatment of that one choice: what each style looks like in code, what each records, and how each behaves when things fail.
Verified with Spring Boot 4.1.2 and Java 25 as the compile target, on 2026-12-01.
The core idea
A saga is a sequence of local transactions, each with a compensating transaction that undoes it, and the only real question in running one is who knows what comes next. In orchestration one component holds the flow and tells each participant what to do. In choreography nobody holds it: each participant reacts to events and publishes new ones, and the flow exists only as the sum of the subscriptions.
Three illustrations run through the lesson, each labelled:
- Minimal example: one ShopStream order with three steps, run both ways in the lab (runs 1 to 4).
- Realistic example: ShopStream's checkout when a fourth step and a support team arrive, in "In practice".
- Failure example: a compensation that never finishes, because a process died or an event was lost (run 7).
What both styles share
Strip away the coordination and the two styles carry the same business logic. The microservices.io pattern description defines a saga as "a reliably coordinated sequence of local transactions", and the two styles as choreography, where "each local transaction publishes domain events that trigger local transactions in other services", and orchestration, where "an orchestrator (object) tells the participants what local transactions to execute".
ShopStream's checkout has three steps, each a local transaction in a service that owns its data:
| Step | Local transaction | Compensation | Can fail because |
|---|---|---|---|
| 1. Reserve stock | Decrement stock, write a reservation | Release the reservation, add the units back | Not enough stock |
| 2. Charge the card | Write a captured payment | Mark the payment refunded | Card declined |
| 3. Assign a courier | Mark a free courier as taken | None needed: if this is the last step and it succeeded, the saga is over | No courier free |
Three rules hold in both styles. The first is that compensation runs in reverse and only for steps that completed: a failure at step 3 undoes 2 and then 1. The second is that every step and every compensation must be safe to repeat, because a restarted orchestrator and a redelivered event both repeat work; the Azure Architecture Center page on the saga pattern lists idempotence among its considerations, and the AWS guidance for both styles lists idempotency as a consideration for participants. The third is that the saga gives up isolation: between step 1 and the end, other requests can see stock that is reserved for an order that may still be cancelled. The Azure page names countermeasures, one of which is a semantic lock, an application-level flag that says an update is in progress. In the lab the order's PENDING status is that flag.
The Azure page also separates compensable steps, a pivot step that is the point of no return, and retryable steps after it. In the lab every step can be undone, so there is no pivot; in a booking flow the pivot is often the moment a ticket is issued. Decide where your pivot is before you write the compensations, because everything after it must be retried to completion, never undone.
Orchestration: one owner of the flow
Figure 1. An orchestrated saga. How to read this: the orchestrator is the only component that knows the order of the three steps. The services expose a transaction and its compensation and know nothing about each other. The orchestrator writes down how far the saga got after every step.
The Azure page describes the orchestrator as the component that "stores and interprets the states of each task" and "handles failure recovery by using compensating transactions". In the lab it is one class, and its whole flow is a list of steps:
this.steps = List.of(
new Step("reserve-stock", inventory::reserve, o -> inventory.release(o.id())),
new Step("charge-card", payment::charge, o -> payment.refund(o.id())),
new Step("assign-courier", delivery::assign, o -> { }));
A step is a name, a local transaction and its compensation. Because the flow is data, adding a step is adding a line. The orchestrator also owns a saga row per order, with a state (RUNNING, COMPENSATING, COMPLETED or CANCELLED) and a count of completed steps, updated after each step. That row is what makes the orchestrator restartable:
Figure 2. The saga row as a state machine. How to read this: the loops on RUNNING and COMPENSATING are the steps and the compensations, each recorded as it finishes. A process that dies leaves the row in one of these states, and a restart reads it and continues.
The compensation half of the loop, from the lab's OrderSagaOrchestrator:
for (int i = done - 1; i >= 0; i--) {
steps.get(i).compensation().accept(order);
trail.add("compensate " + steps.get(i).name());
jdbc.sql("update saga set completed_steps = ? where order_id = ?").params(i, order.id()).update();
crash.check(Where.AFTER_COMPENSATION, i + 1);
}
There is one catch the lab makes visible. The action of a step and the update of the saga row are two separate commits: the orchestrator writes to the participant's database and then to its own. A process that dies between them restarts with a row that says the step has not happened, and repeats it. That is the reason the steps must be idempotent, and run 5 below shows it.
Choreography: no owner, only subscriptions
Figure 3. A choreographed saga. How to read this: there is no coordinator. Every service, including the order service, publishes to the bus and subscribes to the events it cares about. The sub-labels are the subscriptions: inventory reserves, payment charges and delivery assigns when its event arrives. The flow is what they add up to.
In the lab the choreography is nine subscriptions. Two of them show the whole idea. The delivery service's only knowledge is that when a payment is captured it assigns a courier and says how that went:
// Delivery service: assigns a courier once the money is captured.
bus.on("PaymentCaptured", e -> {
try {
delivery.assign(e.order());
bus.publish("CourierAssigned", e.order());
} catch (Rejected r) {
bus.publish("NoCourierAvailable", e.order());
}
});
And compensation is also an event. The payment service refunds when delivery reports that no courier is free, and announces the refund so that inventory can release the stock:
bus.on("NoCourierAvailable", e -> {
payment.refund(e.order().id());
bus.publish("PaymentRefunded", e.order());
});
Compare with Figure 1. Nothing here says "after the charge comes the courier"; that fact lives in the delivery service's subscription to PaymentCaptured. The AWS guidance for choreography describes the same shape, and warns that as participants are added "it becomes harder to track the dependencies between the participants", and that "cyclic dependencies" can appear because participants consume each other's messages.
One more property is easy to miss. In choreography each service must update its database and publish its event, and the two cannot be done atomically by a plain publish call. The AWS choreography page lists this as the dual-write issue and points at the transactional outbox, which the paired lesson, The Transactional Outbox, treats on its own. The lab's bus sidesteps it by being in memory.
Build it: the same order, seven ways
This is the minimal example, a lab you can run. The services are Spring @Transactional beans over H2 in memory (one instance standing in for three databases); the bus is an in-memory FIFO queue, not Kafka, so it never loses anything unless a test tells it to. There is no Docker.
Goal. See the same business outcome from both styles, then see how each behaves when a process dies, an event is redelivered, and an event is lost.
Setup. From the repository's examples/spring-labs folder:
cd examples/spring-labs && ./gradlew :labs:saga-orchestration-choreography:test
The command runs 11 tests: ten behaviour tests, which also assert that both styles end in the same state for runs 1 to 4, plus a golden test that compares the report with examples/spring-labs/golden/saga-orchestration-choreography.txt. The code is under examples/spring-labs/labs/saga-orchestration-choreography/src/main/java/buildingai/labs/saga/.
Runs 1 to 4: four orders, two styles
Run 3 is the card-declined order, and run 4 the order where the card is charged and then no courier is free, so two steps must be undone:
Expected output, captured from a real run (runs 3 and 4):
Run 3. Card declined (shopper s-2).
orchestrated : reserve-stock ok -> charge-card REJECTED (card declined) -> compensate reserve-stock
order=CANCELLED stock(milk)=5 payment=none couriers-assigned=0 saga=CANCELLED
choreographed: OrderPlaced(o-3) StockReserved(o-3) PaymentDeclined(o-3) StockReleased(o-3)
order=CANCELLED stock(milk)=5 payment=none couriers-assigned=0
Run 4. No courier free after the card was charged (zero couriers).
orchestrated : reserve-stock ok -> charge-card ok -> assign-courier REJECTED (no courier available) -> compensate charge-card -> compensate reserve-stock
order=CANCELLED stock(milk)=5 payment=REFUNDED couriers-assigned=0 saga=CANCELLED
choreographed: OrderPlaced(o-4) StockReserved(o-4) PaymentCaptured(o-4) NoCourierAvailable(o-4) PaymentRefunded(o-4) StockReleased(o-4)
order=CANCELLED stock(milk)=5 payment=REFUNDED couriers-assigned=0
Read run 4 twice. The orchestrator's trail ends in two compensations in reverse order. In the choreography the same order appears as a chain of events: the refund is triggered by NoCourierAvailable, and the stock release by the refund. Both end with order=CANCELLED, stock back at 5 and payment REFUNDED. A test asserts the two final states are equal for runs 1 to 4.
Run 5: the orchestrator dies after a step, before recording it
The orchestrator charges the card, and the process dies before it updates the saga row. The restart reads the row, sees one completed step, and repeats the charge:
Expected output, captured from a real run (run 5):
Run 5. Orchestrator process dies after the card was charged but before the saga row was updated (courier free).
crash : process died AFTER_ACTION of step 2
trail 1 : reserve-stock ok -> charge-card ok
unfinished: [o-5 RUNNING with 1 step(s) still done]
trail 2 : charge-card ok -> assign-courier ok (restart reads the saga row and repeats charge-card)
result : order=CONFIRMED stock(milk)=4 payment=CAPTURED couriers-assigned=1 payment rows=1 saga=COMPLETED
The second trail starts with charge-card ok: the step ran again. The payment table still has one row, because charge returns early when the order already has a payment. Without that early return the restart would have charged twice. This is the saga-level version of the problem in Delivery Guarantees, and the fix is the same: an operation that is safe to repeat.
Run 6: a redelivered event
In the choreography the bus delivers PaymentCaptured twice, as a broker does after a consumer restarts before acknowledging:
Expected output, captured from a real run (run 6):
Run 6. Choreography: the bus delivers PaymentCaptured twice (a redelivery; two free couriers).
events : OrderPlaced(o-6) StockReserved(o-6) PaymentCaptured(o-6) [delivered twice] CourierAssigned(o-6) CourierAssigned(o-6)
result : order=CONFIRMED stock(milk)=4 payment=CAPTURED couriers-assigned=1
CourierAssigned appears twice, one per delivery, and one courier is assigned, because assign checks first. The duplicate still costs a repeated downstream event, so consumers of CourierAssigned must be idempotent too; Idempotency keys and safe retries covers the patterns.
Run 7: compensation that does not finish
The no-courier order again, but this time the compensation is interrupted. In the orchestrated half the process dies after the refund and before the stock is released. In the choreographed half the NoCourierAvailable event is lost:
Expected output, captured from a real run (run 7):
Run 7. Compensation is interrupted (zero couriers, so the saga must undo the reservation and the charge).
orchestrated: the process dies after the refund, before the stock is released
crash : process died AFTER_COMPENSATION of step 2
world : order=PENDING stock(milk)=4 payment=REFUNDED couriers-assigned=0
unfinished : [o-7 COMPENSATING with 1 step(s) still done]
after resume: order=CANCELLED stock(milk)=5 payment=REFUNDED couriers-assigned=0 saga=CANCELLED
choreographed: the NoCourierAvailable event is lost
events : OrderPlaced(o-7) StockReserved(o-7) PaymentCaptured(o-7) NoCourierAvailable(o-7) [lost]
world : order=PENDING stock(milk)=4 payment=CAPTURED couriers-assigned=0
what the tables can tell you: orders still PENDING = [o-7] (no row says which step is missing)
after replay of the lost event: order=CANCELLED stock(milk)=5 payment=REFUNDED couriers-assigned=0
Both halves leave the order PENDING with money refunded (or still captured) and stock held. What differs is what you can do next. The orchestrated half has a saga row: the query unfinished() returns o-7 COMPENSATING with 1 step(s) still done, and a restart finishes the job from that row. The choreographed half has an order stuck in PENDING and nothing that says which step is missing; the operator can see the order, read the event log (if the broker kept it), and replay the lost event, which finished the cancellation. The two failures are not identical (a crash versus a lost message), and a durable broker would typically redeliver an event that was never acknowledged. The point is narrower: orchestration gives the unfinished saga a name and an address.
Stretch. Add a fourth step, a fraud check between the stock reservation and the charge, in both styles, and count the files you touch. Then make PaymentService.charge non-idempotent and watch run 5 fail.
What the lab leaves out. Timeouts, a sweeper that resumes unfinished sagas, concurrent sagas on the same stock, a workflow engine, a real broker (the outbox lab has one) and three separate databases. A business rejection is modelled; a step that times out and may or may not have happened is not.
What each style stores and what it cannot see
| Question | Orchestration | Choreography |
|---|---|---|
| Where is the flow written? | One class or workflow definition | Spread over the subscriptions of every participant |
| Where is the saga's state? | A saga row (or a workflow engine's history) | In the participants' own tables and the event log |
| "Where is order 4821 stuck?" | Read its saga row | Join the order's status, the services' tables and the events |
| Who knows about step 3? | The orchestrator and the delivery service | Only the services that subscribe to its events |
| What does adding a step touch? | The orchestrator's list and the new service | The new service and whichever service's events it must follow or precede |
| What does it risk? | The orchestrator becomes a single point of failure and a place where logic piles up | Cyclic dependencies, a flow nobody can read in one place |
| Coupling | Services depend on the orchestrator's commands | Services depend on each other's event names |
The Azure page's lists agree with the table: for choreography it names simple workflows with few services and no single point of failure as benefits, and a confusing workflow when steps are added and cyclic dependencies as drawbacks; for orchestration it names suitability for complex workflows and no cyclic dependencies as benefits, and extra coordination logic and a point of failure as drawbacks. The AWS orchestration page notes that using AWS Step Functions mitigates the single point of failure, because the workflow service carries its own fault tolerance. A durable workflow engine is the usual answer to "the orchestrator must not die": it stores the saga row for you.
Choosing a style
Figure 4. A decision path. How to read this: size and branching come first, team boundaries second, operability third. The last box is a hybrid: even an orchestrated saga announces its result as an event, and downstream consumers that do not affect the outcome stay choreographed.
| Option | Gain | Cost | Wrong when |
|---|---|---|---|
| Choreography | No coordinator to run, loose coupling, each team owns its reaction | Flow is implicit, debugging needs the event log, cycles creep in | The flow has more than a few steps, or support must answer "where is it" |
| Orchestration in application code | One readable flow, one saga row, one place for timeouts | You own the state machine, and the orchestrator is a component to keep alive | You build and maintain what an engine already gives you |
| Orchestration on a workflow engine | Durable state, retries and history provided | A new system to operate and learn | The flow is two steps and rarely fails |
| A distributed transaction (2PC) | Atomic commit across participants that support it | Blocking, availability coupling, participants must support it | Participants include external APIs or brokers that cannot take part |
In practice: ShopStream's checkout grows a fourth step
This is the realistic example, an educational scenario on the course's running example, ShopStream; nothing in it describes a real company. Every number other than the shared ShopStream figures is illustrative.
This is a realistic scenario, not a case history.
The situation
ShopStream's checkout is a choreography of three services (inventory, payment, delivery) over the event stream from the order pipeline stage; the peak target is about 58 checkouts per second, a shared illustrative number. Two things have changed. Product wants a fraud check before the charge and a loyalty-points step after it, and support keeps receiving "my order has been pending for ten minutes" tickets that nobody can diagnose without three engineers and the event log.
Starting architecture
Figure 5. The checkout today. How to read this: all steps react to events on one topic. The orders service shows PENDING until a final event arrives, and nothing records which step an order reached.
Options considered
| Option | What it gives | Problem |
|---|---|---|
| A. Add two more subscriptions | No new component | Two more services follow event names owned by others; the compensation chain gets longer and still cannot be read in one place |
| B. Orchestrate checkout in the orders service, with a saga row | One flow, one state per order, support can read it | The orders team owns the flow and the orchestrator must be kept alive |
| C. Adopt a durable workflow engine | State, retries and history provided | A new system to run for a flow of five steps |
| D. Keep it as it is and add a dashboard | Cheapest | The dashboard cannot show state the system does not record |
The decision
Option B, with a hybrid edge. The orders service owns an orchestrator with a saga row per order, in its own database, with steps reserve stock, fraud check, charge, assign courier and award points. The first four can be undone (the fraud check by doing nothing, the courier assignment by freeing the courier); awarding points comes after the pivot, so it is retried until it succeeds and is never undone. After the saga ends, the orders service announces OrderConfirmed as an ordinary event, and notifications and analytics stay choreographed because they cannot change the outcome. A workflow engine (option C) is the planned revisit if the number of steps passes about ten or if the team spends more time keeping the orchestrator alive than the flow; both numbers are illustrative.
Every step and every compensation is idempotent, keyed by the order id, and each service publishes through an outbox (see The Transactional Outbox). Each saga has a deadline.
Rollout and verification
Run the new orchestrator in shadow first: it records the saga row while the old choreography still decides, and a comparison job checks that the row's final state agrees with the order's real status. Then switch a small share of traffic, with the choreography as the fallback. Verify with the lab's crash points against a staging copy: a kill after a step and before the row update, a kill in the middle of compensation, and a duplicate command. The dashboards are the number of unfinished sagas by state, the age of the oldest one, compensations per hour by step, and duplicate-step hits (proof that idempotence is working).
The 2 a.m. failure
The page reads: unfinished sagas above threshold, oldest 25 minutes. The orders service had been restarted during a deploy, and 40 sagas were left COMPENSATING after a payment-provider outage made refunds fail. The saga rows show every one of them waiting on the same compensation, charge-card. The checks: the provider's status, the retry count on the refund, and whether the refund call reuses the same idempotency key each time. The mitigation is to let retries continue with backoff and pause new checkouts that would be charged, because customers are safe: stock is held and no new money moves. The lasting fix is a scheduled sweeper that resumes unfinished sagas older than a deadline, an alert on age rather than on count, and a manual-repair queue for compensations that exceed their retry budget. Choreography would have left the same 40 orders PENDING with no indication of which step each needed.
Architect's notes
- Draw the pivot first. List which steps can be undone and which cannot, then order the saga so the risky, compensable steps come before the point of no return.
- Make compensations boring. A compensation is a business operation (refund, release), not a rollback; it can fail, and it must be retryable until it succeeds.
- Give every saga a deadline and an owner. A saga stuck forever in
PENDINGholds stock and money. Alert on the age of the oldest unfinished saga. - Use both styles on purpose. Orchestrate the part that decides the outcome; choreograph the reactions that do not.
- Never publish with a bare call after a commit. A service that updates its database and then publishes can lose the event; use an outbox.
Common mistakes
- Choreography for a long flow with compensations. The flow becomes a graph nobody can draw from the code.
- An orchestrator that contains business rules. It should sequence, not decide; the rules belong to the services.
- Non-idempotent steps. A restart or a redelivery then charges twice.
- Compensating steps that did not run. Undoing step 2 when step 2 was rejected refunds money that was never taken.
- No answer to "where is it". If no record names the step an order reached, support is blind.
- Believing a saga rolls back. It compensates, and a compensation can fail or be late.
Key takeaways
- A saga is local transactions plus compensations; orchestration and choreography differ only in who holds the flow.
- An orchestrator keeps a saga row, so an unfinished saga has a state, a step and an address; a choreography has an event log and the participants' tables.
- Steps and compensations must be idempotent in both styles, because restarts repeat work and brokers redeliver.
- Compensation runs in reverse over completed steps only, and steps after the pivot are retried, never undone.
- Choreography suits short flows with few independent participants; orchestration suits longer flows, and the sweet spot is often orchestrating the outcome and choreographing the reactions.
- Whichever style you choose, each service needs an atomic way to update its database and publish its event: the outbox.
Practice exercises
Exercise 1 (30 min). Run the lab and, for run 4, write the three states of the world (orders, stock, payment) after each event of the choreography, and after each step of the orchestrator.
Exercise 2 (45 min). Add a fraud-check step to the orchestrator with an empty compensation. Then do the same in the choreography. List every class or subscription you changed in each style.
Exercise 3 (1 hour). Write a scheduled sweeper that calls resume for every saga that has been RUNNING or COMPENSATING for more than a deadline. Decide what it does when resume fails twice.
Exercise 4 (2 hours). Design the saga row for ShopStream's checkout: columns, the states, the deadline, and the index the sweeper needs. State what you would do with a saga that reaches CANCELLED but whose refund shows FAILED.
Related reading
- Distributed Transactions: 2PC and Sagas: why a transaction cannot span services, and the first treatment of sagas.
- The Transactional Outbox: the paired lesson, publishing an event atomically with the change that caused it.
- Delivery Guarantees: why an event can arrive twice and what an idempotent consumer is.
- Idempotency Keys and Safe Retries: the keys that make a repeated step harmless.
- Dead-Letter Queues and Retries: where an event goes when a step keeps failing.
- Spring @Transactional: the local transaction each saga step is.
- ShopStream Stage 5: The Order Pipeline: the running example.
The other side of this topic
The front-end view of a saga is the order page that must be honest while the saga runs: a PENDING status that later becomes CONFIRMED or CANCELLED, an optimistic screen that may have to retract, and a client that polls or listens for the outcome. Eventual consistency in user interfaces is treated in the lesson on eventual consistency UX.
Official documentation
- microservices.io, Pattern: Saga: the definition, the two coordination styles and the lack of isolation.
- Microsoft Azure Architecture Center, Saga design pattern: benefits and drawbacks of each style, pivot and retryable transactions, countermeasures for data anomalies.
- AWS Prescriptive Guidance, Saga choreography pattern: issues and considerations, including the dual-write problem.
- AWS Prescriptive Guidance, Saga orchestration pattern: issues and considerations, and the Step Functions implementation.
- Spring Framework reference, Rolling back a declarative transaction: the default rollback rule behind each local step.