Managing transactions with sagas
Placing one FTGO order now changes four databases, and no single transaction can cover them. This chapter shows how to keep that data consistent with sagas instead of distributed transactions, and how to live with the gaps they leave.
key idea / coordinator service / good path in progress / watch out problem / failure neutral
In chapter 8 each FTGO service took ownership of its own data, and other services lost direct access to its tables. That left one problem open: an operation that changes data in several services can no longer be one ACID transaction.
How does FTGO keep an order, its kitchen ticket and its card payment consistent when they live in different databases? By the end you can design a saga with compensating steps, choose between choreography and orchestration, guard against the anomalies sagas allow, and handle the stale reads of an eventually consistent system.
One order, four databases
A customer places an order. createOrder() must check the consumer in Consumer Service, write the order in Order Service, create a ticket in Kitchen Service and authorize the card in Accounting. In the monolith this was one database transaction. Now the ticket can be saved while the card authorization fails, and the restaurant starts cooking a meal nobody paid for.
ACID means atomicity (all or nothing), consistency, isolation (no one sees half-done work) and durability. Each service can still use ACID transactions on its own database. What the split takes away is atomicity, and isolation, across services.
Before reaching for any new machinery, ask whether these changes really must live apart. There are four options, from simplest to most work.
Order, Kitchen and Accounting are separate services for good reasons, so FTGO cannot keep their data together. The team needs atomicity across databases, and the classic tool for that is a distributed transaction.
Why not a distributed transaction?
The obvious fix for "four databases, one change" is to make the databases agree before anyone commits.
An FTGO architect proposes two-phase commit across Order, Kitchen and Accounting. Then the team finds out that the message broker does not support it, and that every order would hold row locks in three databases until the slowest one answered. At Friday-evening peak, a slow Accounting database would freeze order and ticket rows across the system.
Two-phase commit (2PC) has a vote phase and a commit phase. A coordinator asks every worker whether it can make its change; if all say yes, it tells them all to commit.
| 2PC problem | Why it hurts |
|---|---|
| Locks | It is mostly distributed locking: slow, and deadlocks are hard to avoid. Long or large operations hold resources for a long time. |
| Latency | More participants and slower workers or networks mean longer locks. |
| Lost isolation | Commits land at different moments, so one worker may show the change before another. |
| Silent worker | A worker that voted yes and then goes quiet can leave a mess an operator must fix by hand. |
| Support | Many NoSQL stores and brokers such as Kafka and RabbitMQ do not support it at all. |
| Availability | Every participant must be up at once, so availabilities multiply. Say each of three services is up 99.5% of the time: together they are up only about 98.5%. |
Pat Helland's comparison: when every node must work, adding a node lowers availability, like adding an engine to a plane that needs all of its engines to fly. Systems such as Google Spanner do make distributed transactions work, but behind one logical database and on very costly infrastructure. Use 2PC, if ever, only for very short operations. A saga, next, is built for the opposite: it works with any modern stack and stays available.
Saying no to 2PC means giving up the one tool that makes several databases commit as one. FTGO needs another way to finish, or cleanly abandon, a change that spans services.
A saga: a chain of local transactions
If one big transaction is off the table, split the work into small ones that each commit on their own.
A saga is a sequence of local transactions, one per service. Each step updates its own database in an ordinary ACID transaction and then sends a message that triggers the next step. No locks are held across services.
FTGO's Create Order saga has six steps:
Each step must update its database and send its message together, or the saga stalls with the step done and nobody told. That is exactly the transactional outbox from chapter 6. Messages can also arrive twice, so every step must be idempotent. Because messages are buffered by the broker, a saga keeps going when a service is briefly down; it just waits.
A saga does not give atomicity for the whole operation. It gives you enough recorded state to know where you are, and it makes the business process explicit: the order of steps above is now something the team designs on purpose.
Each step commits as soon as it runs. If step 4 fails, steps 1 to 3 are already permanent in three databases. There is no ROLLBACK to call.
When a step fails: compensate or push forward
Committed steps cannot be rolled back, so the saga must undo them, or finish, in business terms.
The customer's card is declined at step 4. Order 77 already exists as APPROVAL_PENDING, and Kitchen Service has a ticket for it. Unless something cleans up, the restaurant tablet shows a ticket for an order that will never be paid.
For each step that changes data, write a compensating transaction that undoes its effect. When a step fails, the saga runs the compensations for the committed steps in reverse order.
Not every step needs a compensation. Read-only steps have nothing to undo, and steps after the point of no return never need undoing:
That gives every saga the same shape. Compensatable steps come first and can be undone. The pivot is the go/no-go step: once card authorization succeeds, the saga will run to the end. Retriable steps after the pivot cannot fail for business reasons, so if they hit an error they are simply retried.
A compensation is a semantic rollback, not a database one. You cannot unsend an email, so the compensation sends a second email saying the order was cancelled. The rejected order also stays in the database as REJECTED, because that history is useful.
Undoing is called backward recovery. Sometimes it is wrong to go backward at all, and the saga should push forward instead, retrying from the failed step. That needs the saga's progress to be saved. One saga can mix both: early failures roll back, late failures go forward.
Take delivery. The card is charged and the food is cooked when Delivery Service finds no free courier. Rolling everything back would throw away a hot meal. Instead the saga retries, and only when the retries run out does a person step in.
The order of steps decides how much undoing a failure costs. A side example from an online shop shows it clearly. If loyalty points are awarded before packing, a packing failure needs two undos; awarded at the end, there is nothing to take back. The rule: move steps that are likely to fail earlier, and steps that are hard to undo later. FTGO's saga follows it: the cheap, read-only consumer check comes first, and the card is authorized just before the steps that cannot fail.
Every data-changing step now needs a compensation that is designed and tested, and someone must decide, after every reply, which step or compensation runs next. Where does that decision live?
Who runs the saga: choreography or orchestration
A saga needs coordination: something must start each step and, on failure, each compensation.
FTGO first wires the Create Order saga as a chain of events: Order Service publishes OrderCreated, Kitchen reacts and publishes TicketCreated, Accounting reacts to that, and so on. A month later support asks, "Where is order 77 stuck?" Nobody can answer without reading the code of four services, and Order Service now listens to events from services that listen to it.
There are two styles. In choreography, each service reacts to the others' events and decides what to do next. In orchestration, one orchestrator sends commands to each service and reacts to the replies.
Give the saga one owner: a Create Order orchestrator that sends a command to each service, waits for the reply, and decides the next step or compensation. Model it as a state machine and keep it small.
Choreography is simple for small sagas and has no central point of failure, but the flow is hard to see and cyclic dependencies creep in. Orchestration keeps the flow readable in one place, keeps dependencies one-way and keeps domain objects simple, as long as the business logic stays in the services. Prefer orchestration for all but the simplest sagas, and pick by who owns the flow:
| Orchestration | Choreography | |
|---|---|---|
| Process visible | In one place | Spread across services |
| Coupling | The orchestrator knows every service | Services only know events |
| Usual style | Commands and replies (request-response) | Events on a broker |
| Main risk | Logic drains out of services, leaving them anemic | Hard to see where a saga is, or to trigger compensation |
| Fits when | One team owns the whole saga | Several teams are involved |
If you do choreograph, get the central view back with a saga tracker. Every event in a saga carries the same correlation id, a unique id created when the saga starts. The tracker listens to all the events and groups them by that id, so support can see the state of order 77 in one place.
You can also mix styles. Across teams, a saga can be choreographed with events; inside one service whose team owns a whole sub-flow, that part can be orchestrated. Say Kitchen Service orchestrates accepting, cooking and handing over a ticket, while it talks to Order and Delivery only through events.
An orchestrator is one more component that knows every participant, and it tempts teams to move business rules into it. And whichever style runs the saga, its steps commit one by one, so other requests can see the half-finished work in between.
No isolation: anomalies and countermeasures
A saga is ACD, not ACID: atomic (in the business sense, through compensation), consistent and durable, but not isolated.
A customer places order 77 and, a second later, taps "Cancel". The Cancel Order saga sets the order to CANCELLED. Meanwhile the Create Order saga, still running, reaches its last step and sets the order to APPROVED, overwriting the cancellation. The restaurant cooks a meal the customer cancelled.
Because each step commits at once, other sagas see, and can change, half-finished data. That causes the same anomalies that isolation levels prevent inside one database:
- Lost update: one saga overwrites a change made by another, as with the cancelled order above.
- Dirty read: a saga reads data another saga has changed but may still compensate. Say a saga checks a consumer's credit limit while another saga has raised it and is about to roll back.
- Fuzzy (nonrepeatable) read: two steps of one saga read the same data and get different answers, because another saga changed it in between.
While a saga is working on a record, mark it with a pending state such as APPROVAL_PENDING. Other sagas that see the flag know the record is in flux: they fail, wait or retry. The saga clears the flag when it finishes or compensates.
With the lock, the Cancel Order saga sees APPROVAL_PENDING on order 77 and waits until the Create Order saga finishes, then cancels the approved order with its own compensations. The semantic lock is the most common countermeasure, but there are others:
| Countermeasure | FTGO example |
|---|---|
| Commutative updates | "Debit 20" and "credit 20" give the same balance in either order, so a compensation can never land on the wrong value. |
| Pessimistic view | Reorder steps so a dirty read does less harm, for example update a consumer's available credit only in a retriable step after the pivot. |
| Reread value | Before approving, reread the order and check it has not changed since the saga started; if it has, abort and restart. This is optimistic locking at the business level. |
| Version file | Accounting records the operations it receives, so an authorization reversal that arrives before the authorization can be matched up correctly. |
| By value | Pick the mechanism by business risk: small orders run as sagas, very large catering orders use a stronger, slower process. |
Each countermeasure is design work and extra states to handle; a pending flag also means some requests must wait or fail. And the gaps do not end when the saga does. Every service that learns about order 77 from events learns it a little later than the others, so for a moment different parts of FTGO disagree.
Stale reads: what eventual consistency costs
Sagas and events make FTGO eventually consistent: every service reaches the same state, but not at the same moment.
A restaurant has a limited daily stock of its special. When an order is placed, Restaurant Service updates the stock, and Notification Service tells followers "Last portion left!" when one remains. Both react to the same OrderCreated event. Notification is faster: it asks Restaurant's stock read model before that model has applied the event, gets the old count, and skips the alert, or sends it twice.
The time during which a reader can see old data is the inconsistency window. In a monolith a change is visible everywhere at once; with events, every consumer catches up at its own speed. Two properties help you reason about it. Safety means nothing invalid ever happens; liveness means something good eventually happens, here mainly higher availability. Eventual consistency promises liveness. It gives no safety guarantee by itself, so where safety matters you must add it.
Be careful with the usual justification. The CAP theorem (see chapter 18) says that during a network partition you must choose consistency or availability, and event-driven design chooses availability. But CAP's availability is about partitions, not overall uptime, and partitions are a small share of real outages: Google reported that only 7.6 percent of Spanner incidents were network-related. Meanwhile eventual consistency pushes the work of handling stale data onto every consumer. Confirm the business can live with it. One team lost the users' trust in a product-visibility feature after repeated delays, and the users went back to doing the work by hand.
Agree with the business where staleness is acceptable and for how long. Then measure consumer lag and keep the window small enough that users rarely notice, mainly by scaling consumers horizontally when lag grows.
For services, a small window means enough consumer instances to keep up with bursts. One setup scales on lag: an exporter reads Kafka consumer lag, Prometheus stores it as a custom metric, and the Kubernetes horizontal pod autoscaler (HPA) adds instances when lag passes a limit.
A small window is still a window. Scaling makes stale reads rarer, but the "last portion" alert can still go wrong at the busiest moment. Consumers need designs that stay correct when they do see old data.
Five ways to handle stale data
Back to the special of the day. Notification Service needs the remaining stock, but OrderCreated only says that one portion was sold. There are five ways to stop it from acting on an old number.
| Strategy | How it works for FTGO | Gain | Cost |
|---|---|---|---|
| 1 Richer event | Restaurant publishes StockChanged with the remaining count, so Notification never has to ask (the "event size" choice from chapter 7). | Simple, no extra request, scales linearly | Bigger events tied to consumer needs; the data must exist upstream; meaning can blur |
| 2 Domain boundary | Restaurant tells outside services only after its own read model is updated. | Little code; outsiders see only settled data | Slower end to end; a read model that publishes events is debatable; use sparingly |
| 3 Version and retry | The event carries a version; if the API answers with an older one, Notification retries later. | Quick fix | Does not remove the problem; retries cause load peaks, so use backoff and a circuit breaker |
| 4 Keep local state | Notification keeps its own stock count, built from events. | No runtime dependency; fast and resilient | Storage and upkeep; copies of the data spread across services |
| 5 End-to-end check | The menu may show stale stock, but Order Service checks stock with Restaurant when the order is placed. | The parts stay fast and loosely coupled | Needs a final check in the flow; an order can still fail late |
Local state does not have to live in a database. A service can keep a time window of recent events in memory, which suits bulk jobs, or load the whole stream at startup, which works only for small, stable data sets such as a few hundred cuisine categories.
The end-to-end check is the strongest idea of the five. Small parts of the system can stay eventually consistent because the one place where the business rule matters, placing the order, checks it against the authoritative source.
Every one of these strategies relies on events being published reliably whenever state changes, which is still two writes per step: the database row and the outbox message. And the services keep only their latest state, so when the stock count looks wrong, nobody can see the history of how it got there.
Patterns in this chapter
| Pattern | Problem it solves | What it costs |
|---|---|---|
| Keep data together | State that must change atomically | That data cannot be split into separate services |
| Two-phase commit | Atomic commit across several databases | Distributed locks, lower availability, little tool support; avoid it |
| Saga | An operation spans several services' databases | No automatic rollback and no isolation; needs the outbox and idempotent steps |
| Compensating transaction | A later step fails after earlier steps committed | A designed, tested undo for every data-changing step; semantic, not exact |
| Forward recovery | Undoing late steps would waste work already done | Saved progress, retries, and a person when retries run out |
| Orchestration | Nobody can see or change the whole saga | A central component that knows all participants; risk of anemic services |
| Choreography with a saga tracker | Teams want loose coupling but still need to see a saga's state | Flow spread across services; every event must carry a correlation id |
| Semantic lock and other countermeasures | Lost updates, dirty reads and fuzzy reads between sagas | Extra states and design work; some requests wait or fail |
| Small inconsistency window | Consumers read stale data after an event | Lag metrics and autoscaling; the window never reaches zero |
| Stale-data strategies (richer event, boundary, version and retry, local state, end-to-end check) | A consumer must act correctly on possibly old data | Bigger events, slower flows, retries, copied data or a late final check |
Recap
- With a database per service, an operation like creating an order loses cross-service atomicity and isolation; first ask whether the data can stay together.
- Two-phase commit is mostly distributed locking, needs every participant up at once, and is missing from many modern tools, so FTGO uses sagas instead.
- A saga is a chain of local transactions linked by reliable messages; failures are handled by compensating transactions in reverse order, or by retrying forward after the pivot, and step order decides how much undoing a failure costs.
- Orchestration keeps a saga's flow in one small state machine and suits most sagas; choreography suits flows across teams and needs a correlation id and a tracker.
- Sagas have no isolation, so guard against lost updates, dirty reads and fuzzy reads with semantic locks, commutative updates, rereads and the other countermeasures.
- Event-driven systems are eventually consistent: keep the inconsistency window small, and design consumers with richer events, boundaries, version checks, local state or an end-to-end check.
Quick check
Show answer
Each earlier step already committed in its own service's database, and no transaction spans them. The saga must run compensating transactions instead, in reverse order: rejectTicket() in Kitchen Service, then rejectOrder() in Order Service. The consumer check was read-only, so it needs nothing.
CANCELLED, then the still-running Create Order saga marks it APPROVED, and the restaurant cooks the meal. What went wrong, and which pattern fixes it?
Show answer
A lost update: sagas have no isolation, so one overwrote the other's change. Use a semantic lock. While the Create Order saga runs, the order is APPROVAL_PENDING; the Cancel Order saga sees that flag and waits or retries until the first saga finishes, then cancels with its own compensations.
Show answer
Usually not. The menu can stay eventually consistent as long as the window is small and the order path performs an end-to-end check: Order Service validates stock with Restaurant Service when the order is placed, and rejects it if the dish is gone.
Every saga step still writes its state and then publishes an event, two writes that the outbox has to keep in step. And each service stores only its latest state, so nobody can see how an order got to where it is.
Next: 10 Event sourcing: store what happened, not just where you ended up →
The saga pattern: common questions
What is the saga pattern?
A business transaction split into local transactions, one per service. If a step fails, earlier steps are undone by compensating transactions.
Choreography or orchestration?
Choreography lets services react to each other's events; simple, but the flow is hard to see. An orchestrator tells each service what to do; easier to follow and change for longer flows.