Distributed transactions: two-phase commit, sagas and the outbox
A distributed transaction is a change that must take effect in several databases or services together, or not at all. There are two broad ways to get it: an atomic commit protocol such as two-phase commit, which locks every participant until all agree, or a saga, which runs a chain of local transactions and undoes finished steps with compensating actions when a later one fails. In most interviews the strongest answer starts by asking whether the data can live together so no distributed transaction is needed.
By Evin JohnPublished 10 min read
1. What a distributed transaction is
Inside one relational database, a transaction is easy to ask for: begin, make several changes, commit, and the database promises all or none of them stick. The trouble starts when the changes live in places that do not share a transaction log. Moving money between accounts on two different shards, or placing an order that touches an order service, a payment service and an inventory service, each with its own database, are the textbook cases. No single engine can roll the whole thing back, so the system needs a protocol or a pattern that does the job across the boundary.
2. Why interviewers raise it
Splitting a design into services or shards is easy to draw, and this is the bill that arrives later. An interviewer who hears "order service, payment service, inventory service" will usually ask what happens when the payment succeeds and the stock reservation fails. The question tests whether you know the cost of two-phase commit, whether you can design compensations that make business sense, and whether you notice the gap between a database write and a message publish. Candidates who answer "we use a distributed transaction" without naming a mechanism tend to get pushed until they do.
3. The cheapest option: do not need one
- Co-locate what changes together. If two tables are always updated in the same operation, keep them in one database. Service boundaries drawn along transaction boundaries save a lot of machinery.
- Choose the partition key with transactions in mind. If most transfers happen inside one customer's accounts, partition by customer so the common case is a single-shard transaction. More on this in sharding.
- Accept a short delay. Many workflows do not need both sides to change at the same instant. Write one side now and let an event update the other, with the user seeing a "processing" state in between.
- Use one owner per invariant. A rule such as "stock never goes below zero" should be enforced by the one service that owns stock, with a conditional write, not by coordinating several services.
4. Two-phase commit
Two-phase commit (2PC) adds a coordinator that drives every participant through two rounds. In the prepare round, each participant does the work, writes it durably, keeps its locks and votes yes or no. If every vote is yes, the coordinator records a commit decision in its own log and tells everyone to commit; if any vote is no or missing, it tells everyone to abort. The XA standard is a common interface for this between a transaction manager and databases or message brokers.
- Coordinator
- Send prepare
- Log the decision
- Send commit or abort
- Participant A
- Write changes, hold locks, vote yes
- Commit and release locks
- Participant B
- Write changes, hold locks, vote yes
- Commit and release locks
The weak spot is the gap after a participant votes yes. It has promised to commit if told to, so it cannot decide on its own; if the coordinator crashes at that moment, the participant sits "in doubt" holding its locks until the coordinator comes back. Every other transaction that needs those rows waits too. That is why 2PC is called a blocking protocol. Three-phase commit was proposed to remove the blocking, but it depends on timing assumptions real networks do not keep, so it is rarely what production systems use. The practical fix is to make the coordinator itself fault-tolerant: databases in the style of Google's Spanner, as described in its published paper, run two-phase commit between groups that are each replicated with a consensus protocol, so losing one machine does not lose the coordinator.
2PC fits inside one database product that spans shards (many distributed SQL databases do this for you) or between systems that support a prepare step. It fits poorly across independent services owned by different teams, across third-party APIs (a card network will not hold a lock for you) and anywhere a slow participant should not stall everyone else.
5. Sagas
A saga, a term from a 1987 database paper by Garcia-Molina and Salem, splits the work into a sequence of local transactions. Each step commits on its own. For each step you also write a compensating action that semantically undoes it: void an authorization, release a reservation, cancel an order. If step four fails, the saga runs the compensations for steps three, two and one in reverse. Nothing is ever locked across services, so a slow inventory service cannot freeze the payment database.
| Step | Local transaction | Compensation if a later step fails |
|---|---|---|
| 1 | Order service creates the order in state PENDING | Mark the order CANCELLED and tell the customer |
| 2 | Payment service authorizes the card | Void the authorization |
| 3 | Inventory service reserves the items | Release the reservation |
| 4 | Order service marks the order CONFIRMED | None: this is the pivot, so from here the saga only moves forward |
| 5 | Shipping service books a courier (after confirmation) | Retried until it succeeds; it is past the point of no return |
Step 4 is what saga literature calls the pivot: once it commits, the saga is going forward, and later steps must be retried rather than undone. Placing the steps most likely to fail before the pivot, and steps that cannot be undone (sending a parcel, an email) after it, is a design choice worth saying out loud.
class StepFailed(Exception):
pass
def run_saga(steps, log):
"""steps: list of (name, action, compensation). Runs actions in order;
on a failure, runs the compensations of completed steps in reverse."""
done = []
for name, action, compensate in steps:
try:
action()
log.append(f"did {name}")
done.append((name, compensate))
except StepFailed as e:
log.append(f"failed {name}: {e}")
for prev, comp in reversed(done):
comp() # must be idempotent and retried until it succeeds
log.append(f"undid {prev}")
return "compensated"
return "completed"
def ok(): pass
def out_of_stock(): raise StepFailed("no stock")
steps = [("create order (PENDING)", ok, ok), ("authorize payment", ok, ok),
("reserve stock", out_of_stock, ok), ("confirm order", ok, ok)]
log = []
print(run_saga(steps, log)) # compensated
print(log)
# ['did create order (PENDING)', 'did authorize payment', 'failed reserve stock: no stock',
# 'undid authorize payment', 'undid create order (PENDING)']A real orchestrator also persists the saga's state after every step, so a crash in the middle resumes where it stopped instead of forgetting that a card was authorized.
Orchestration or choreography
| Style | How it works | Strength | Weakness |
|---|---|---|---|
| Orchestration | A saga coordinator (often a workflow engine) tells each service what to do next and records progress | The whole flow is in one place; easy to see where a saga is stuck | The orchestrator is one more service to run and scale |
| Choreography | Each service reacts to events from the previous one and emits its own | No central component; services stay loosely coupled | The flow is spread across services and hard to follow once it passes four or five steps |
The isolation you give up
Because each step commits immediately, other requests can see a saga half done: an order that is PENDING, stock that is reserved but not yet sold. Sagas handle this with visible intermediate states rather than locks. Showing "payment processing", refusing to ship anything not CONFIRMED, and re-reading a value before acting on it (so a compensation does not overwrite a newer change) are the usual countermeasures. Compensations must also be idempotent and retried until they succeed, because a compensation that fails leaves the system inconsistent for real.
6. The outbox: the step everyone forgets
Each saga step usually ends with "update my database, then publish an event so the next service acts". Those are two writes to two systems, a tiny distributed transaction of their own. If the service crashes between them, the database changed but nobody hears about it. The transactional outbox removes the gap: the service writes the event into an outbox table inside the same local transaction as the business change, and a separate relay (polling, or reading the database's change log) publishes it afterwards. The relay may publish twice, so every consumer must treat messages as possibly repeated; see idempotency for the consumer side.
7. Reservations: try, confirm, cancel
A variant that suits bookings is to make the first phase a business-level reservation with an expiry. Try holds a seat or a room for a few minutes; confirm turns the hold into a sale; cancel, or the expiry itself, releases it. It looks like 2PC, but no database lock is held: the hold is ordinary data with a timeout, so an abandoned checkout cleans itself up. The ticket booking walk-through holds seats with a short expiring reservation in the same spirit.
8. Choosing between them
| Two-phase commit | Saga | Try/confirm/cancel | |
|---|---|---|---|
| Atomicity | All or nothing | Eventually all or nothing, through compensations | Holds become sales or expire |
| Isolation | Full, through locks | None between steps; intermediate states are visible | Holds are visible as reserved |
| Behavior under failure | Participants can block while in doubt | Keeps running; compensations clean up | Expiry releases abandoned holds |
| Needs from participants | A prepare step (XA or built-in) | A compensating action per step | An API to hold, confirm and release |
| Typical home | Inside one distributed database | Across microservices and third parties | Seats, rooms, stock at checkout |
9. How it shows up in common prompts
| Prompt | The multi-party change | Common answer |
|---|---|---|
| Payment system | Charge with a provider, record in a ledger, update the order | Saga with the provider's idempotency key; ledger and outbox in one local transaction |
| Ticket booking | Hold a seat, take payment, issue the ticket | Reservation with expiry, then a saga for payment and issuing |
| Sharding | A transfer between accounts on two shards | Pick a key that keeps most transfers on one shard; otherwise 2PC inside the database or a saga |
| Job scheduler | A job that writes to several systems | Idempotent steps with a recorded checkpoint after each |
10. Interview questions on distributed transactions
| Question | What a strong answer includes |
|---|---|
| Why not just use two-phase commit everywhere? | Blocking when the coordinator fails, locks held across a network round trip, and participants that cannot prepare |
| What happens if the 2PC coordinator crashes after prepare? | Participants stay in doubt, holding locks, until it recovers from its log; replicating the coordinator is the fix |
| Walk me through a saga for placing an order. | Ordered steps, a compensation for each, the pivot, and the states the user sees |
| Orchestration or choreography? | Orchestration for long or branching flows; choreography for two or three simple steps |
| What if a compensation fails? | Retry it with backoff because it is idempotent; alert and park it for manual handling if it keeps failing |
| How do you publish an event and update the database atomically? | Transactional outbox plus a relay, with consumers deduplicating |
| What isolation problems do sagas have? | Other requests see intermediate states; handle them with pending states and re-checks |
| Can you avoid the distributed transaction altogether? | Often, by co-locating data, choosing the partition key, or accepting a short delay |
11. Mistakes to avoid
- Saying "distributed transaction" with no mechanism. Name 2PC, a saga or a reservation and say why.
- Compensations that are not real undos. Refunding a captured payment is not the same as voiding an authorization; a sent email cannot be unsent. Order steps so the irreversible ones come last.
- Dual writes. Writing the database and then the queue, with no outbox, loses events on a crash.
- Forgetting the user's view. Say what the screen shows while the saga is in flight and after it compensates.
- No saga state. An orchestrator that keeps progress only in memory forgets half-finished sagas when it restarts.
12. How to talk about it in the interview
- Start by asking whether the data can share one database. If yes, use a local transaction and move on.
- If not, pick the mechanism and give the reason in one sentence: who supports prepare, who cannot be locked.
- Walk the failure path, not only the happy path: which step fails, what gets compensated, what the user sees.
- Mention the outbox and idempotent consumers before the interviewer asks how events are delivered.
Fictional example
- Interviewer
- Booking a room touches the room inventory, payments and the loyalty points service. How do you keep them consistent?
- Candidate
- Payments goes through an external provider, so two-phase commit is off the table. I would run an orchestrated saga. First, inventory places a hold on the room with a fifteen-minute expiry. Then payment authorizes the card with an idempotency key. Then the booking is confirmed, which is the pivot.
- Candidate
- If the authorization is declined, the saga releases the hold. Loyalty points are awarded after confirmation and simply retried until they succeed, since a late point credit harms nobody.
- Interviewer
- And if the orchestrator crashes halfway?
- Candidate
- It records the saga's state after each step, so on restart it picks up the open sagas and either continues or compensates. Every step accepts the same request twice without doing the work twice.
Drilling failure paths with Natively
This topic is mostly failure paths, so practice by having someone interrupt you with "and if that step fails?" until you run out of answers. Natively can sit in on that mock call on your Mac or Windows PC, transcribing the exchange live; one shortcut asks it for a suggested reply to the latest question, and the Recap action summarizes what you have covered so far. It can also draw a saga or a two-phase commit flow as a diagram inside its answer, which helps when you want to compare your sketch against a clean one. The saved transcript shows afterwards which failure you skipped.
Questions people ask
What is the difference between two-phase commit and a saga?
Two-phase commit makes every participant prepare and hold locks until a coordinator tells all of them to commit or abort, so the change is atomic and isolated but can block. A saga commits each step locally and undoes earlier steps with compensating actions if a later one fails, so it never blocks across services but other requests can see intermediate states.
Why is two-phase commit called blocking?
After a participant votes yes it must wait for the coordinator's decision and keep its locks. If the coordinator crashes at that point, the participant cannot safely commit or abort on its own, so it stays in doubt until the coordinator recovers. Replicating the coordinator with a consensus protocol is the usual remedy.
What is a compensating transaction?
It is a local transaction that semantically undoes an earlier saga step, such as voiding a card authorization or releasing a stock reservation. It is not a database rollback: the original step already committed. Compensations must be idempotent and retried until they succeed.
What is the transactional outbox pattern?
A service writes the event it needs to publish into an outbox table in the same local transaction as its business change. A relay then reads the outbox and publishes the events. This removes the gap where a crash between a database write and a queue publish would lose the event, at the cost of possible duplicate publishes.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
