Chapter 09 of 27 · Part 5: Data management

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.

The saga pattern: local transactions and compensating steps, instead of one distributed rollback.

key idea / coordinator service / good path in progress / watch out problem / failure neutral

Where we are

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.

This chapter

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

Problem

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.

One operation touches several databases createOrder() needs data consistency Consumer service reads consumer Order service writes order Kitchen service writes ticket Accounting service writes account Each service has its own database, so one ACID transaction cannot cover them all.

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.

Same change in one database and in two One database Two databases ORDERS: insert order 77 TICKETS: insert ticket for 77 one ACID transaction: both or neither Order svc: insert order Kitchen svc: insert ticket two transactions, each may fail alone

Before reaching for any new machinery, ask whether these changes really must live apart. There are four options, from simplest to most work.

Options when changes must be atomic Keep together one DB, one service Split schema app stays one Reorder steps fail early Use a saga local steps + undo Split the schema first to spot transaction and speed problems early.
The first answer is "do not split it". If two pieces of state truly must change atomically, keep them in one database owned by one service, and split something else first. Splitting the schema inside the monolith before splitting the code (chapter 8) shows these transaction problems early, while they are still cheap to fix.
Cost

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.

Problem

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.

Two-phase commit Coordinator Worker A Worker B vote: can you change? vote: can you change? yes (row locked) yes (row locked) commit, release lock commit, release lock A "yes" is a promise, so each worker must lock its record until the commit arrives.
2PC problemWhy it hurts
LocksIt is mostly distributed locking: slow, and deadlocks are hard to avoid. Long or large operations hold resources for a long time.
LatencyMore participants and slower workers or networks mean longer locks.
Lost isolationCommits land at different moments, so one worker may show the change before another.
Silent workerA worker that voted yes and then goes quiet can leave a mess an operator must fix by hand.
SupportMany NoSQL stores and brokers such as Kafka and RabbitMQ do not support it at all.
AvailabilityEvery 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.

Cost

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.

Solution · Saga

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:

Create Order saga 1. Order svc create order APPROVAL_PENDING 2. Consumer svc verify consumer 3. Kitchen svc create ticket CREATE_PENDING 4. Accounting svc authorize card 5. Kitchen svc approve ticket 6. Order svc approve order APPROVED Each step is a local ACID transaction. Finishing one triggers the next.

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.

Cost

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.

Problem

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.

Solution · Compensating transactions

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.

Saga rollback using compensating transactions Order Consumer Kitchen Accounting create order verify consumer create ticket authorize card card FAILS reject ticket (undo) reject order (undo) Committed steps cannot be rolled back. Undo them with compensating 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:

Compensating transactions for each step Step Compensating step createOrder() rejectOrder() verifyConsumerDetails() none (read-only) createTicket() rejectTicket() authorizeCreditCard() none (pivot) approveTicket(), approveOrder() none (always succeed)

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.

Structure of a saga Compensatable createOrder verifyConsumer createTicket Pivot authorize card go / no-go point Retriable approveTicket approveOrder After the pivot commits the saga always runs to the end.

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.

Two recovery styles Backward recovery Undo committed steps Needs compensating actions Forward recovery Retry from the failure Needs saved progress Mixed Each failure picks a style Late steps go forward Sagas handle business failures, not technical ones such as a 500 error.

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.

A fail-forward step No courier all are busy Retry again in 2 minutes Still failing retries used up Human steps in not a full rollback The card is charged and the food is cooked, so rolling everything back would be odd.

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.

Reorder steps to reduce undo work Points awarded early: a Pack failure needs two undos Take payment Award points Pack fails Dispatch Points awarded late: only the payment is left to refund Take payment Pack fails Dispatch Award points Move steps that are likely to fail earlier, and steps hard to undo later.
Cost

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.

Problem

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.

Choreography versus orchestration In choreography services exchange events. In orchestration a central orchestrator sends commands. Choreography: services react to events Order svc Kitchen svc Accounting svc events Orchestration: a boss sends commands Saga orchestrator owns the sequence Consumer svc Kitchen svc Accounting svc
Dashed arrows are events. Solid arrows are commands. Replies go back to the orchestrator.
Solution · Saga orchestrator

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.

Saga orchestrator as a state machine Verifying consumer start Creating ticket Authorizing card pivot Approving ticket Approving order Order approved final state Any failure moves the saga to Rejecting, then Order rejected.

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:

OrchestrationChoreography
Process visibleIn one placeSpread across services
CouplingThe orchestrator knows every serviceServices only know events
Usual styleCommands and replies (request-response)Events on a broker
Main riskLogic drains out of services, leaving them anemicHard to see where a saga is, or to trigger compensation
Fits whenOne team owns the whole sagaSeveral 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.

A choreographed saga with a tracker Order Kitchen Accounting Delivery Event topic on the broker Saga tracker groups events by correlation id shows the state of each order

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.

Mixing styles in one saga Choreographed across teams Order svc Kitchen svc Delivery svc event event Orchestrated inside Kitchen Accept Cook Hand over one team owns this flow, so central control is easy
Keep orchestrators small. Use a separate orchestrator per flow (placing orders, cancelling orders, refunds) so no single service collects all the logic; if logic can be centralized, it will be. Prefer plain code over drag-and-drop BPM tools, which are hard to version and test and which developers end up maintaining anyway. If you do want a workflow engine, Camunda and Zeebe are examples. Whatever you mix, keep one clear way to see a saga's state.
Cost

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.

Problem

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:

Anomalies caused by lack of isolation Sagas are ACD: no isolation Lost update overwrites another saga Dirty read reads half-done data Fuzzy read same data, different result
Solution · Semantic lock

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.

Semantic lock with Order state APPROVAL_PENDING semantic lock set APPROVED saga finished REJECTED compensated Other sagas see the *_PENDING state and know a saga is still working on the order.

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:

Countermeasures for lack of isolation Countermeasure Idea Semantic lock flag the record (e.g. *_PENDING) Commutative updates make steps runnable in any order Pessimistic view reorder steps to cut business risk Reread value check data is unchanged before write Version file record operations, then reorder them By value risky requests use stronger control
CountermeasureFTGO 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 viewReorder 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 valueBefore 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 fileAccounting records the operations it receives, so an authorization reversal that arrives before the authorization can be matched up correctly.
By valuePick the mechanism by business risk: small orders run as sagas, very large catering orders use a stronger, slower process.
Cost

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.

Problem

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.

A stale read between two consumers of one event Notification asks the stock read model before it has been updated by the same event. Order svc Stock write Stock read Notification OrderCreated OrderCreated GET stock still old value update read model Result: a missed or duplicate "last portion left" alert, even with a small delay.

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.

Solution · Keep the inconsistency window small

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.

It is not eventual if nobody notices. Studies of real databases found about 98 percent of Cassandra reads consistent within 1 ms or less, and 96 percent of MongoDB reads within 5 ms or less. Keep the window that small and most users never see it.

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.

Autoscaling on consumer lag Kafka exporter feeds lag to Prometheus; the Kubernetes horizontal pod autoscaler adds consumer instances above a threshold. Kafka consumer lag Exporter reads lag Prometheus custom metric HPA lag > limit Instances scale out and in A lunch-time burst raises lag; extra instances drain it; resources shrink after the peak.
Cost

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.

Strategies for eventual consistency Richer events, publish after the read model updates, version and retry, keep local state, or validate end to end. 1 Richer event carry total stock 2 Domain boundary publish after read model 3 Version and retry detect a stale answer 4 Keep local state persist or buffer in memory 5 End-to-end check validate at purchase time
StrategyHow it works for FTGOGainCost
1 Richer eventRestaurant publishes StockChanged with the remaining count, so Notification never has to ask (the "event size" choice from chapter 7).Simple, no extra request, scales linearlyBigger events tied to consumer needs; the data must exist upstream; meaning can blur
2 Domain boundaryRestaurant tells outside services only after its own read model is updated.Little code; outsiders see only settled dataSlower end to end; a read model that publishes events is debatable; use sparingly
3 Version and retryThe event carries a version; if the API answers with an older one, Notification retries later.Quick fixDoes not remove the problem; retries cause load peaks, so use backoff and a circuit breaker
4 Keep local stateNotification keeps its own stock count, built from events.No runtime dependency; fast and resilientStorage and upkeep; copies of the data spread across services
5 End-to-end checkThe menu may show stale stock, but Order Service checks stock with Restaurant when the order is placed.The parts stay fast and loosely coupledNeeds 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.

End-to-end argument Browsing may show stale stock, but Order Service validates stock with Restaurant Service when the order is placed. Browse path (eventual) Customer sees stock on menu Menu read model may lag Order path (checked) Customer places order Order Service validates the rule Restaurant authoritative The smaller parts can stay eventually consistent because the end-to-end flow guarantees the business rule.
Cost

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

PatternProblem it solvesWhat it costs
Keep data togetherState that must change atomicallyThat data cannot be split into separate services
Two-phase commitAtomic commit across several databasesDistributed locks, lower availability, little tool support; avoid it
SagaAn operation spans several services' databasesNo automatic rollback and no isolation; needs the outbox and idempotent steps
Compensating transactionA later step fails after earlier steps committedA designed, tested undo for every data-changing step; semantic, not exact
Forward recoveryUndoing late steps would waste work already doneSaved progress, retries, and a person when retries run out
OrchestrationNobody can see or change the whole sagaA central component that knows all participants; risk of anemic services
Choreography with a saga trackerTeams want loose coupling but still need to see a saga's stateFlow spread across services; every event must carry a correlation id
Semantic lock and other countermeasuresLost updates, dirty reads and fuzzy reads between sagasExtra states and design work; some requests wait or fail
Small inconsistency windowConsumers read stale data after an eventLag 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 dataBigger events, slower flows, retries, copied data or a late final check

Recap

Quick check

Why can the Create Order saga not just call ROLLBACK when card authorization fails?
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.

A customer cancels order 77 one second after placing it. The Cancel Order saga marks it 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.

FTGO's menu sometimes shows a dish as available a few seconds after it sold out. Must this be fixed with strong consistency?
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.

Still open

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.