Saga Pattern (Distributed Transactions)
Keep data consistent across several services without a distributed transaction: a chain of local transactions, each with a compensating step that undoes it if a later step fails.
Overview
A saga is a business operation that spans several databases, written as a sequence of ordinary local transactions. Each step commits on its own. If a later step fails, the saga runs a compensating transaction for every step that already committed, newest first, so the system ends in a state the business accepts.
The idea comes from Hector Garcia-Molina and Kenneth Salem, in the paper *Sagas* (ACM SIGMOD, 1987). They were solving a problem inside a database system: a long-lived transaction that holds locks for hours blocks everyone else and is more likely to deadlock or hit a crash. Their answer was to split it into steps that release their locks as they go, and to pair each step with code that can undo it. About thirty years later the same idea became a common way to run one business operation across microservices that each own a database.
Interviewers ask about sagas because the pattern forces you to say what you give up. A saga is not a transaction. It has no isolation, its rollback is code you write, and the coordinator can crash halfway. A strong answer names those costs and shows the design that pays for each one.
The problem: one operation, three databases
Placing an order touches three services. Each has its own database, so no single database transaction can cover the whole operation.
There are three ways to get all-or-nothing behavior across those writes.
- One database: one ACID transaction covers every table. The cost is that every service shares a schema, so the split into services is gone.
- Two-phase commit (2PC): a coordinator asks every participant to prepare, then tells all of them to commit. The cost is that participants hold locks from prepare until the decision arrives; if the coordinator crashes in between, they wait, blocked.
- Saga: each service commits its own step, and failures are undone by compensating steps. The cost is no isolation, eventual consistency, and rollback code you must write and test.
The rest of this chapter is about the third option and how to pay its costs.
Interview questions
- Walk through an order saga and what happens when the payment is declined.
- Choreography or orchestration: which would you pick, and why?
- What must a compensating transaction satisfy? Show a bad one and a good one.
- How is a saga different from two-phase commit?
- Sagas have no isolation. What goes wrong, and how do you defend against it?
- The orchestrator crashes after step 2 of 4. How does the saga finish?
Sign up free to read the full topic
More Low-Level Design topics
Start free on Cariara · Coding problems · System design studio