System Design

Core Concepts

Distributed Transactions and Sagas

A write that spans services always has a moment when it is half done. Two-phase commit hides that moment in locks nobody can see or expire. A saga writes it into your data, and most of the design is giving it a name, an owner and a deadline.

Why you are doing this at all

A booking that touches three services is never all or nothing. The seat service marks a seat as taken. A card processor such as Stripe charges the card. The order service writes the order. Each of those commits on its own, in its own system.

Now say the process dies after the charge and before the order is written. The customer has paid and has no ticket. No row anywhere says the booking is unfinished, so nothing will come back to finish it or to undo it.

A booking that stops half done
The seat service takes the seat (1) and the card processor charges the card (2), each in its own commit. The process dies before the order service writes the order (3), in red. The customer has paid and has no ticket, and no row anywhere says the booking is unfinished.The seat service takes the seat (1) and the card processor charges the card (2), each in its own commit. The process dies before the order service writes the order (3), in red. The customer has paid and has no ticket, and no row anywhere says the booking is unfinished.
Each step commits, so a crash between steps leaves no record of the gap. The seat service takes the seat (1) and the card processor charges the card (2), each in its own commit. The process dies before the order service writes the order (3), in red. The customer has paid and has no ticket, and no row anywhere says the booking is unfinished.

Inside one database this can't happen. All three writes go into one transaction, and the database writes one commit record to one log. Before that record is on disk, none of the writes count. After it, all of them do.

Other transactions can't see the writes in between, either. In Postgres and MySQL's InnoDB, each reader works from a snapshot that leaves out uncommitted writes, and row locks stop a second writer from changing the same rows.

Across services you have none of that. There's no shared log to hold one commit record, and no shared lock manager. And the network can't tell you whether a request was lost or its reply was, as Idempotency and Exactly-Once Delivery explains. So a call that times out leaves you not knowing which side of a commit you're on.

A transaction across services always has a half-finished state. The design question is where it lives: in locks a database holds, or in rows you own, with a name, an owner and a deadline.

There are three ways to handle it.

Two-phase commit (2PC). Every database keeps its part locked until a coordinator tells all of them to commit or to abort, so the half-finished state lives in locks.

A saga. Each step commits on its own, and a later failure runs steps that undo the earlier ones, so the half-finished state lives in your rows.

A different boundary. You move the data so that one database commits all of it, and the half-finished state never leaves one commit.

Try the third first, because it removes the problem instead of handling it. It often isn't available, though. The card processor is another company, and its data will never move into your database. So you'll usually need one of the first two.

When you need none of this

Not every write that follows another one needs a saga. The test is whether a later step can say no.

Sending the confirmation email, updating the Elasticsearch index and counting the sale can all be slow. They can fail and be retried. None of them can refuse for a business reason. A step like that needs at-least-once delivery and a receiver that ignores duplicates. That's the outbox pattern: you write the event in the same transaction as the order, and a relay delivers it.

Holding a seat, authorising a card, which reserves the money without taking it, and taking money from a wallet can each refuse. The seat is gone, the card is declined, the balance is short. When a step like that comes after other steps, those earlier steps may need undoing, and now you need a saga or a transaction.

A step that can only be slow needs a retry. A step that can say no needs an undo for every step before it.

And if the writes already share a partition key, one local transaction covers them. Choosing a Database makes that the first question to ask about transactions.

The toolkit

Two-phase commit, step by step

2PC has one coordinator and several participants. The coordinator is the process that decides the outcome. A participant is a database, or anything else that can hold changes and later commit or discard them. In the X/Open XA standard, they're called the transaction manager and the resource managers.

The first phase is the prepare. The coordinator asks each participant to prepare. A participant that agrees writes its changes and a prepare record to disk, keeps every lock it took, and votes yes. A yes vote is a promise: the participant can still commit after a crash, and it won't abort on its own. A participant that can't make that promise votes no.

The second phase is the decision. If every vote is yes, the coordinator writes "commit" to its own log and tells every participant. If any vote is no, or a participant doesn't answer in time, it writes "abort" instead. The participants apply the decision and release their locks.

Jim Gray and Leslie Lamport counted the cost of the normal case in 2004. It takes four message delays and three writes to stable storage.

Two-phase commit, one booking
The coordinator asks both databases to prepare (1). Each writes a prepare record, keeps its locks and votes yes (2). The coordinator writes commit to its own log (3) and sends it (4). The bar beside each database is its in-doubt window, when it holds its locks and can neither commit nor abort on its own.The coordinator asks both databases to prepare (1). Each writes a prepare record, keeps its locks and votes yes (2). The coordinator writes commit to its own log (3) and sends it (4). The bar beside each database is its in-doubt window, when it holds its locks and can neither commit nor abort on its own.
After its yes vote, a participant can't release its locks until the decision arrives. The coordinator asks both databases to prepare (1). Each writes a prepare record, keeps its locks and votes yes (2). The coordinator writes commit to its own log (3) and sends it (4). The bar beside each database is its in-doubt window, when it holds its locks and can neither commit nor abort on its own.

Between voting yes and hearing the decision, a participant is in doubt. It can't commit, because the coordinator may have decided to abort. It can't abort, because it promised not to. So it waits with its locks held. You pay for that wait on every transaction, not only when something fails.

Back of envelopeWhat two-phase commit adds to a lock
Only one transaction at a time can hold the lock on a row,
so the time each one holds it sets how many commits a
second that row can take. Take a row that every booking
for one event updates, such as the remaining count for a
general admission event. Compare a local commit with 2PC,
using the course's figures: 0.3 ms per fsync (forcing a
write onto disk), 1.5 ms round trip across zones, 25 ms to
the nearest other region.

Local commit, one database
  lock held through the commit     one fsync      0.3 ms
  commits/s on the row             1 / 0.3 ms  ≈ 3,300

2PC, from the prepare request until the decision reaches
the participant: three one-way messages and two fsyncs,
the participant's prepare record and the coordinator's
decision
  across zones     1.5 × 1.5 ms + 2 × 0.3 ms   ≈ 2.9 ms
                   1 / 2.9 ms                  ≈ 350/s
  across regions   1.5 × 25 ms + 2 × 0.3 ms    ≈ 38 ms
                   1 / 38 ms                   ≈ 26/s
  ─────────────────────────────────────────────────────
These are floors, because the work before the prepare
holds the lock too. Across zones, 2PC cuts the row from
about 3,300 commits a second to about 350. Across regions
it cuts it to 26, which is a booking system that sells
26 tickets a second for its most popular event.

A row like that is a hot key, and taking load off it comes before putting it inside a distributed commit.

The blocking failure

Now say the coordinator crashes after every participant has voted yes.

Each participant is in doubt, and nothing it can do alone is safe. If it commits, it may disagree with a coordinator that decided to abort. If it aborts, it breaks its promise. Asking the other participants doesn't help, because they voted yes too and know no more.

Gray and Lamport call this the problem with 2PC: no participant can learn the outcome, so the protocol blocks until the coordinator is repaired.

Here the half-finished state has an owner, the coordinator, and no deadline. Nothing expires, so the locks stay.

A coordinator that dies after the votes
Both databases vote yes (1). The coordinator writes commit to its log, then crashes before sending the decision (2). Each database holds its locks, in red, and can't tell whether to commit. Requests for the event's count row queue behind it (3) until the coordinator restarts, reads commit from its log and sends it (4).Both databases vote yes (1). The coordinator writes commit to its log, then crashes before sending the decision (2). Each database holds its locks, in red, and can't tell whether to commit. Requests for the event's count row queue behind it (3) until the coordinator restarts, reads commit from its log and sends it (4).
Prepared participants keep their locks until the coordinator comes back. Both databases vote yes (1). The coordinator writes commit to its log, then crashes before sending the decision (2). Each database holds its locks, in red, and can't tell whether to commit. Requests for the event's count row queue behind it (3) until the coordinator restarts, reads commit from its log and sends it (4).

Little's law, from Latency Numbers That Matter, says how far that spreads: requests in flight equal the arrival rate times how long each one waits.

Back of envelopeWhat one coordinator crash costs
The question is how far the damage spreads beyond the
locked rows. Assumptions to replace with your own: the
coordinator takes 5 minutes to restart and read its log,
the locked row is the event's count row, and the event
sells 200 tickets a second, each of which updates it.
Each request waits up to 2 s for a lock, and the booking
service has a pool of 100 database connections.

Requests that need the event's count row
  during the outage    200/s × 300 s            =  60,000
  every one of them waits 2 s and then fails

Connections held by waiting requests, by Little's law
  in flight            200/s × 2 s              =     400
  connection pool                                     100
  ─────────────────────────────────────────────────────
400 waiting requests need 4 times the pool, so requests
for every other event queue behind them too. One crashed
coordinator stops all bookings for 5 minutes, not just
the bookings for one event.

Where two-phase commit still runs

2PC didn't go away. It runs between databases that one team owns, inside distributed databases across their own shards, and in Spanner.

XA is the X/Open standard for 2PC across data stores, and MySQL supports it for InnoDB. XA works when every participant is a database you run, in one region, and you accept the blocking failure. It doesn't work with a card processor, because there's no XA prepare to call. A charge over HTTP either happens or it doesn't.

Inside one database, 2PC is how a write across shards stays atomic, and you never see the coordinator. DynamoDB's TransactWriteItems writes several items atomically, and AWS documents the price: two underlying writes per item, one to prepare and one to commit.

CockroachDB keeps a transaction record next to the transaction's first write. Raft, the consensus protocol covered in Quorums, Raft and Paxos, replicates the record like any other data. If the coordinator stops sending heartbeats, the record is marked aborted. Any later transaction that finds a leftover write checks the record and cleans the write up.

Kafka's own transactions run the same kind of 2PC, with the coordinator's state in a replicated internal topic.

Spanner splits its data into Paxos groups. A Paxos group is a consensus group, the same idea as a Raft group. A transaction inside one group needs no 2PC, and the 2012 Spanner paper says that covers most transactions. A transaction across groups runs 2PC between the groups' leaders, and each leader stores its 2PC state in its own Paxos group.

The paper claims that running 2PC over Paxos "mitigates the availability problems". It also argues that programmers are better off fixing transactions that turn out slow than coding around having no transactions at all.

Gray and Lamport reached the same design from the protocol side. Their Paxos Commit records each participant's vote in a Paxos group instead of in one coordinator's log. Plain 2PC is the case where that group is a single machine.

The coordinator's decision, replicated
Each participant is a consensus group of three replicas, not one machine. The coordinator group's leader writes the commit decision through its group (1) before it tells the participant groups. When that leader dies (2), another replica in the same group becomes leader, reads the decision from the log and sends it (3).Each participant is a consensus group of three replicas, not one machine. The coordinator group's leader writes the commit decision through its group (1) before it tells the participant groups. When that leader dies (2), another replica in the same group becomes leader, reads the decision from the log and sends it (3).
When the decision is in a replicated log, a replica can finish the commit. Each participant is a consensus group of three replicas, not one machine. The coordinator group's leader writes the commit decision through its group (1) before it tells the participant groups. When that leader dies (2), another replica in the same group becomes leader, reads the decision from the log and sends it (3).

Spanner, CockroachDB and Kafka all write the coordinator's decision to a replicated log before anyone acts on it. When the coordinator dies, a replica carries on with the decision, so the half-finished state's owner is a group of machines instead of one process. That makes blocking rare, not impossible: a group that loses its majority still stalls, with its locks held.

It does nothing for the cost. Spanner's paper measured 2PC latency against the number of participants, across 3 zones. The mean was 17.0 ms with one participant, 42.7 ms with 50 and 150.5 ms with 200. At 200, the 99th percentile (p99) was 320.3 ms.

Two-phase commit latency in Spanner
Spanner's own measurements, across 3 zones. The solid purple line is the mean commit latency and the dashed line is the p99, against the number of participants.Spanner's own measurements, across 3 zones. The solid purple line is the mean commit latency and the dashed line is the p99, against the number of participants.
A replicated coordinator makes blocking rare, not commits cheap. Spanner's own measurements, across 3 zones. The solid purple line is the mean commit latency and the dashed line is the p99, against the number of participants.

So 2PC is the right tool when every participant is software you run, close together.

Sagas

Hector Garcia-Molina and Kenneth Salem introduced the saga in 1987, for a problem inside one database. Some transactions ran for hours, such as producing a bank's monthly statements, and held their locks the whole time.

Their fix was to split such a transaction into a sequence of smaller ones, T1 to Tn, each of which commits and releases its locks on its own. For each step Ti, the programmer also writes a compensating transaction Ci, which undoes it. The system then guarantees one of two outcomes. Either every step runs, or the steps up to some Tj run and then Cj back to C1 undo them.

The same shape fits a booking across services, where each step is a local transaction in a different service.

A saga that fails at step 3
T1 holds the seat and T2 authorises the card, each committing in its own service, in green. T3, the confirm, finds the hold expired (1). The saga runs C2, which cancels the authorisation (2), then C1, which releases the seat only if this booking still holds it (3). Between T1 and C1, other requests can see the seat as held.T1 holds the seat and T2 authorises the card, each committing in its own service, in green. T3, the confirm, finds the hold expired (1). The saga runs C2, which cancels the authorisation (2), then C1, which releases the seat only if this booking still holds it (3). Between T1 and C1, other requests can see the seat as held.
Each step commits on its own, and the undo steps run in reverse order. T1 holds the seat and T2 authorises the card, each committing in its own service, in green. T3, the confirm, finds the hold expired (1). The saga runs C2, which cancels the authorisation (2), then C1, which releases the seat only if this booking still holds it (3). Between T1 and C1, other requests can see the seat as held.

Two details from the paper matter here.

A compensation undoes a step's meaning, not its bytes. The paper's example is an airline seat. If T1 reserved a seat, C1 cancels it by subtracting one from the flight's reservation count. It can't write back the count from before T1, because other transactions may have booked seats on that flight since.

Other transactions see each step as soon as it commits. The paper says that when a compensation runs, no effort is made to tell the transactions that saw the step it undoes. A saga gives up isolation in return for releasing its locks early.

A saga that fails can finish in two ways. Backward recovery runs the compensations. Forward recovery retries the remaining steps until they succeed. The paper points out that if no step can abort the saga, and every step succeeds when retried, the saga never needs compensations at all.

Steps you cannot undo

Some steps leave your system the moment they run, and no compensation brings them back. The customer has read the email. The payout has reached the seller's bank. The ticket has been scanned at the gate.

The 1987 paper gives the extreme case: a transaction that fires a missile. For gentler cases it suggests a new action that makes up for the old one, such as a second letter explaining the first, or a stop-payment for a cheque. A compensation is a new business action with its own cost, not a rollback.

Card payments show how wide that gap is. Capture is the step that takes the money a card authorisation reserved. Before capture, Stripe lets you cancel a payment at no cost. After it, you can only refund it. A refund can keep Stripe's processing fees, takes about 5 to 10 business days to reach the customer, and can fail, for example on a closed bank account.

So order the steps by how easily they can be undone. The countermeasure model that Lars Frank and Torben Zahle published in 1998 splits a saga into three kinds of step, and runs them in this order.

  1. Steps that can be undone run first, so a failure can still undo them.
  2. The pivot is the one step whose commit decides the outcome. Before it, the saga can go back. After it, the saga only goes forward.
  3. Steps that are retried until they succeed run last. Nothing after the pivot is allowed to say no.

An irreversible step runs at the pivot or after it, never before. So capturing the payment, sending the email and paying the seller wait until the saga can no longer go back.

Orchestration and choreography

Something has to run a saga's steps, and there are two shapes.

Orchestration. One component, the orchestrator, holds the saga's state and tells each service what to do next.

Choreography. No component holds the whole saga, because each service reacts to the event before it and publishes one of its own.

Choreography is built from parts you may already run. The seat service holds the seat and writes a SeatHeld event to its outbox. The payment service reads that event, authorises the card, and publishes PaymentAuthorised. Each hop is one local transaction plus one event.

The costs arrive with the undo path. The saga's state is spread across every service, so answering "where is booking 42?" takes a query to each one. Every service has to know which later failures mean it should undo its own step. The seat service listens for PaymentDeclined, the payment service listens for TicketFailed, and adding a step means changing the services before it. And no service owns a saga that stopped halfway.

An orchestrator owns exactly that. It's a state machine whose state lives in a durable data store, and it moves one step at a time. It calls the seat service and records the result, then calls the payment service and records that result. If it crashes, it reads its record and carries on.

The 1987 paper had already described this. For a database with no saga support, it proposed a table of active sagas. After a crash, a background process scanned the table and ran whatever steps or compensations were left.

You don't have to build that table yourself now. Temporal records every step of a workflow in an event history, and after a crash the workflow picks up from the last recorded event. AWS Step Functions Standard workflows also keep their state between steps. The cost is one more system to run, and if the orchestrator is down, every saga stops where it is. So run it replicated, or use a managed one.

Who runs the saga
On the left, the orchestrator calls each service in turn and records each result in its state table (1), so one row answers where booking 42 is. On the right, each service reacts to the event before it and publishes its own (2). An undo needs the failure event to reach every earlier service (3), and the saga's state is spread across all three.On the left, the orchestrator calls each service in turn and records each result in its state table (1), so one row answers where booking 42 is. On the right, each service reacts to the event before it and publishes its own (2). An undo needs the failure event to reach every earlier service (3), and the saga's state is spread across all three.
An orchestrator keeps the saga's state in one place. On the left, the orchestrator calls each service in turn and records each result in its state table (1), so one row answers where booking 42 is. On the right, each service reacts to the event before it and publishes its own (2). An undo needs the failure event to reach every earlier service (3), and the saga's state is spread across all three.

Choreography is the simplest design for two or three steps in a straight line that never undo anything. Choose orchestration as soon as any step has an undo, because the undo path is where choreography's state is hardest to find.

Pending states, the lock you can see

A saga releases the database's locks after every step. So something else has to stop other bookings taking the seat while this booking is undecided. That something is a status in the seat's own row.

-- step 1: hold the seat if it is free, if an old hold has expired,
-- or if this booking already holds it (a retry)
UPDATE seats
SET status = 'HELD', held_by = 'booking_42',
    held_until = now() + interval '10 minutes'
WHERE event_id = 'evt_7' AND seat_id = 'C14'
  AND (status = 'AVAILABLE'
       OR (status = 'HELD'
           AND (held_until < now() OR held_by = 'booking_42')));

-- step 3, the pivot: confirm only if this booking still holds it
UPDATE seats
SET status = 'SOLD'
WHERE event_id = 'evt_7' AND seat_id = 'C14'
  AND status = 'HELD' AND held_by = 'booking_42'
  AND held_until > now();

-- undo of step 1: release only this booking's own hold
UPDATE seats
SET status = 'AVAILABLE', held_by = NULL, held_until = NULL
WHERE event_id = 'evt_7' AND seat_id = 'C14'
  AND status = 'HELD' AND held_by = 'booking_42';

This is usually called a semantic lock: a lock stored as data and checked by the application, instead of one the database's lock manager holds. Each column does one job, and together they give the half-finished state a name, an owner and a deadline.

  • HELD is the name, so every reader can tell a held seat from a sold one.
  • held_by is the owner, so only this booking can confirm or release it, and a retried hold from the same booking succeeds.
  • held_until is the deadline, so a booking whose orchestrator died gives the seat back on its own. The first statement treats an expired hold as free, so no cleanup job is needed.

All three statements are conditional writes, which succeed only if the row still matches what you expect. That's the single-key linearizable write CAP and What It Actually Constrains puts on a seat hold, scoped to one seat for a few minutes.

The confirm checks the owner and the deadline in the same statement. If it updates no rows, the saga reads the row before deciding anything. SOLD with held_by = 'booking_42' means an earlier try already confirmed it, so the saga carries on. Anything else means the hold expired and someone else may have the seat, so the saga undoes its earlier steps instead of selling one seat twice. The release checks held_by too, so a late undo can't free a hold that now belongs to another booking.

Pat Helland described the same idea in 2007. With distributed transactions, the uncertainty about the outcome sits in locks the transaction manager holds. Without them, it has to live in the business logic.

Card networks built the same thing for money. An authorisation holds the money until a capture takes it or a cancel releases it. Stripe documents that an online card authorisation usually lasts 7 days, and that if you don't capture in time, the funds are released and the payment is cancelled. That's a pending state with an owner and a deadline, run by somebody else.

Back of envelopeHow long a hold must last
The hold has to outlast the slowest booking that should
still succeed, or a customer who is paying loses the seat.
It also keeps the seat off sale for everyone who walks
away. Work out the floor first, then what it costs.
Assumptions to replace with your own: the customer gets 5
minutes to enter card details and approve the payment in
their bank's app, the authorise call times out after 10 s
and is tried 4 times with 1, 2 and 4 s between tries, and
a crashed orchestrator worker is replaced within 60 s.

The slowest booking that should still succeed
  customer, card details and bank approval        300 s
  authorise    4 tries × 10 s + 1 + 2 + 4 s         47 s
  orchestrator worker replaced                      60 s
  ─────────────────────────────────────────────────────
  total                                           407 s
                                          about 7 minutes
  hold, with margin                            10 minutes

What the hold costs in the first minutes of a sale
  holds started                               1,000/min
  abandoned, assumed 30%                        300/min
  seats held by people who have left
    300/min × 10 min                            = 3,000

A hold shorter than 7 minutes takes seats from people who
are paying. So keep 10 minutes, release the hold at once
when a customer leaves checkout, and let the conditional
confirm catch the rare booking that runs past its hold.

What a saga lets other requests see

Each step commits as soon as it runs, so other requests see the saga half done. The AWS guidance on saga orchestration says it in one line: a saga lacks transaction isolation. Three of the isolation anomalies from Consistency Models come back, now between sagas instead of between transactions.

Dirty read. Another request acts on a step that's later undone, such as a seller who withdraws a credit before the debit behind it fails.

Lost update. An undo writes back an old value over a newer change, as in the paper's airline seat count.

Read skew. A saga reads a value in one step and acts on it in a later one, after it has changed.

None of these is fixed by an isolation setting, because no single database sees the whole saga. Each one has a fix in the data instead.

A pending state fixes most dirty reads. A reader that sees HELD knows not to treat the seat as sold, and a report counts sold seats only.

An undo that applies a relative change fixes the lost update. "Add 2 back to the stock" is safe. "Set the stock to 10" erases every saga that ran in between.

For read skew, carry the version you read early into the pivot. Say the price is ₹2,000 when the customer starts and ₹2,400 by the time the seat is confirmed. Make the pivot a conditional write that fails when the version has moved. Then the saga undoes its earlier steps instead of selling at a price that no longer exists.

The last fix is about order. Frank calls it the pessimistic view: run the steps that take something away from someone before the pivot, and the steps that give someone something after it. Debit before you credit. Reduce the stock before you confirm the order. A request that reads in between then sees too little, which is safe, instead of too much, which can be spent.

Two ways to undo a stock reservation
Both rows start with 10 in stock. Saga A takes 2 and saga B takes 3, leaving 5. Then A fails. In the top row, A's undo writes back the 10 it saw first, so B's 3 items can be sold twice, in red. In the bottom row, A's undo adds 2 back, and the count ends at 7, in green.Both rows start with 10 in stock. Saga A takes 2 and saga B takes 3, leaving 5. Then A fails. In the top row, A's undo writes back the 10 it saw first, so B's 3 items can be sold twice, in red. In the bottom row, A's undo adds 2 back, and the count ends at 7, in green.
An undo that writes back an old value erases other sagas' work. Both rows start with 10 in stock. Saga A takes 2 and saga B takes 3, leaving 5. Then A fails. In the top row, A's undo writes back the 10 it saw first, so B's 3 items can be sold twice, in red. In the bottom row, A's undo adds 2 back, and the count ends at 7, in green.

Idempotent steps and retries

Every step of a saga runs at least once, and sometimes twice. The orchestrator calls the payment service, the call times out, and it can't tell whether the authorisation happened, so it calls again. Or it crashes after a step committed and before it recorded the result, so on restart it runs the step again.

So give every step a key. The saga's id plus the step name, such as booking_42:authorise, is the same on every retry and different for every saga. Send it to the card processor as its idempotency key, and use it as the unique key of the row the step writes.

Undo steps need a key too, and one more property. Temporal's guidance on sagas is that every compensation must be idempotent and must cope with the forward step never having run. Its saga examples register each compensation before running the step, so a step that timed out still gets undone. That means cancelling an authorisation that was never created has to count as a success.

The method

  1. List every write and who owns it. Name the data store, and the team or the company that runs it. Only writes in different data stores make a distributed transaction.
  2. Try to move the boundary. If the writes can share one database, or one partition key in a database with transactions, one local transaction does the job. Stop here.
  3. Ask which steps can say no. A step that can only be slow needs a retry and an outbox. Only a step that can refuse makes the steps before it need undoing.
  4. Order the steps: undoable, then the pivot, then retried. Put every step that can refuse at or before the pivot, and every irreversible step at the pivot or after it.
  5. Name the half-finished state. Give each pending row a status, an owner and a deadline longer than the slowest saga that should still succeed.
  6. Key every step and every undo. Use the saga's id and the step name, and make each undo succeed when its step never ran.
  7. Choose who runs it, and who handles what is left. Use choreography for a short line with no undo, and an orchestrator otherwise. Alarm on the age of the oldest unfinished saga, with a person behind the alarm.

Worked examples, start to finish

Here are three systems. In each one, the obvious design fails in a different way.

Booking a seat, where the obvious order charges first

A concert has 50,000 seats. Seats live in a seat service, orders in an order service, and payments go through a card processor such as Stripe. The first version charges the card, then holds the seat, then writes the order, and refunds the card if the seat turns out to be gone.

During an on-sale, the first minutes after tickets are released, thousands of buyers want the same front rows, and many of them find their seat taken after they've paid. Each one becomes a refund. Each refund can keep Stripe's fees, takes days to reach the customer and can fail. And a crash between the charge and the order leaves a customer who has paid and holds nothing.

So the question is what order to run the steps in, and what to hold while they run, so that nothing irreversible happens while the booking can still fail.

Naive

Wrap the whole booking in one database transaction

Open a transaction in the order database. Call the seat service to take the seat, call the card processor to charge the card, insert the order and commit. It reads as atomic, which is why it gets written.

It isn't atomic. The two calls run outside the transaction, so a rollback removes the order row and nothing else. The seat stays taken and the card stays charged. Brandur Leach's write-up on Stripe-like idempotency keys in Postgres puts it this way: once you've made your first change in another system, you're committed one way or another. The transaction also stays open, holding its locks, for as long as the card network takes to answer.

Senior

An orchestrated saga, with the pivot before anything irreversible

Run five steps from an orchestrator, in this order.

  1. Hold the seat, with a 10 minute deadline. The undo releases it.
  2. Authorise the card. The undo cancels the authorisation, which costs nothing.
  3. Confirm the seat, with the conditional write that checks the hold. This is the pivot.
  4. Mark the order confirmed and capture the payment, each retried until it succeeds.
  5. Issue the ticket and send the email, retried until they succeed.

When the saga starts, the orchestrator writes the order as pending in the order service. If the card is declined at step 2, the orchestrator releases the hold and marks the order failed. If step 3 finds the hold lost, the orchestrator cancels the authorisation and runs the release, which frees the seat only if this booking still holds it. After step 3, nothing can say no: writing the order, capturing a valid authorisation and sending an email can only be slow.

The booking saga, in order
The first two steps can be undone, and undoing them costs nothing: release the hold, cancel the authorisation. Confirming the seat is the pivot (1). After it, the order, the capture and the ticket are retried until they succeed, because nothing there may say no (2). A refund, in red, is only needed when the card is captured before the pivot.The first two steps can be undone, and undoing them costs nothing: release the hold, cancel the authorisation. Confirming the seat is the pivot (1). After it, the order, the capture and the ticket are retried until they succeed, because nothing there may say no (2). A refund, in red, is only needed when the card is captured before the pivot.
Everything irreversible runs after the pivot. The first two steps can be undone, and undoing them costs nothing: release the hold, cancel the authorisation. Confirming the seat is the pivot (1). After it, the order, the capture and the ticket are retried until they succeed, because nothing there may say no (2). A refund, in red, is only needed when the card is captured before the pivot.

This is the standard answer, and it has three costs. You run an orchestrator. Holds keep seats off sale for people who walk away, 3,000 at a time in the hold worksheet. And the pending state lives in two services that have to agree.

Staff

Move the boundary so the saga spans two systems, not three

Question why the seat and the order live in different services. They're written together on every booking, and they're both about one event. Put them in one booking service, in one database sharded by event id. Then the hold and a pending order are one local commit, and the confirm marks the seat sold and the order confirmed in another.

Back of envelopeWhere one booking's rows land
A booking writes a seat row and an order row, and both
tables are split across 64 shards. The question is how
often one booking touches two shards, because each one
that does needs 2PC or a saga.

Orders keyed by user_id, seats keyed by event_id
  the two keys pick shards independently
  same shard                              1/64  ≈  1.6%
  two shards                                    ≈ 98.4%

Orders and seats both keyed by event_id
  two shards                                        0%
  ─────────────────────────────────────────────────────
Keying orders by event turns 98 of every 100 bookings
from a write across shards into one local commit. The
cost is the "my bookings" page: a user's 40 orders now
sit on up to 40 shards, so that page reads a by-user
index that an outbox keeps up to date, seconds behind.

The only party left outside is the card processor, and its authorise and capture is already a prepare with a deadline. So the saga now spans two systems: your database and the card processor. If the card is declined, the undo is one local write that releases the hold. If the confirm fails, the undo is cancelling the authorisation, which costs nothing.

What you give up: "my bookings" now reads an index that lags by seconds. A big on-sale also puts all its load on one event's shard, which Partitioning and Sharding treats as a problem of its own. And two teams have to merge their services.

The decision: hold, authorise, confirm, capture, in that order, with the confirm as the pivot. If the team boundaries allow it, put seats and orders for one event in one database. If they don't, run the senior saga, and say which one you chose.

Paying a seller from a buyer's wallet

A marketplace keeps buyer wallets in a wallet service and seller balances in a payouts service, each with its own database. A purchase moves ₹2,000 from a buyer to a seller. If both balances lived in one database with multi-item transactions, such as DynamoDB's TransactWriteItems or Spanner, you'd use one transaction and stop. This example is the case where they don't.

The obvious version credits the seller first, because that's the step the seller is waiting for, and then debits the buyer. Now say the buyer's balance is short. The credit commits. The seller sees ₹2,000 and requests a payout. The debit fails. The saga's undo is to take ₹2,000 back from the seller, but the payout has already gone. Stripe can cancel a payout only while it's pending, and never an automatic one. That's a dirty read with a price: the seller acted on a step that was later undone.

Reverse the order. Debit the buyer first, and in the same local transaction insert a transfer row with the status IN_TRANSIT. Between the two services, the money is now in a row anyone can query. The 1987 paper gives the same advice for money moving between steps: keep it in a table of funds in transit, so an audit can still find all of it. Then credit the seller.

The credit almost never says no, so it's retried until it lands, keyed by the transfer id. A transfer worker scans the IN_TRANSIT rows, retries each credit and marks the transfer DONE when it lands.

A credit can still be refused, rarely: the seller's account is frozen or closed, an identity check is missing, or a balance cap is reached. The worker undoes that from the same row, by crediting the buyer back and marking the transfer RETURNED. The debit runs first, so nothing comes before it to undo. The only undo left moves money inside your own system, so it can't fail the way a payout can.

Two orders for one payment
In the top row, the seller is credited (1) and paid out (2). The buyer's debit then fails (3), and the undo has to take back money that has already left, in red. In the bottom row, the debit and the in-transit row commit together (1), and the transfer worker retries the credit until it lands (2). A credit the seller's account refuses goes back to the buyer from the same row.In the top row, the seller is credited (1) and paid out (2). The buyer's debit then fails (3), and the undo has to take back money that has already left, in red. In the bottom row, the debit and the in-transit row commit together (1), and the transfer worker retries the credit until it lands (2). A credit the seller's account refuses goes back to the buyer from the same row.
Credit first, and the money can leave before the debit fails. In the top row, the seller is credited (1) and paid out (2). The buyer's debit then fails (3), and the undo has to take back money that has already left, in red. In the bottom row, the debit and the in-transit row commit together (1), and the transfer worker retries the credit until it lands (2). A credit the seller's account refuses goes back to the buyer from the same row.

The half-finished state is the IN_TRANSIT row. The status is its name, the transfer id is its owner, and its deadline is an alarm on the age of the oldest one. A credit still retrying after a few minutes means something downstream is broken.

The decision: debit first, with the transfer row in the same commit, and a transfer worker that retries the credit.

Checkout, where an undo fails

An online shop's checkout reserves stock in the warehouse service, books a courier slot, authorises the card, captures the payment and sends the email. The first version is choreographed. Each service reacts to the last event, and a failure publishes an event that tells the earlier services to undo.

Every undo in that version is a call, and a call can fail. If the warehouse service is down for an hour, ReleaseStock fails until it's back. A version that publishes the event once and never retries leaves the stock reserved for good.

An undo with a bug is worse, because it fails every time. The 1987 paper describes this case: a compensation that can never succeed leaves the saga stuck, unable to finish and unable to undo. Its answers were alternative code or a person.

A refund for goods found damaged after delivery is a separate process, started later. It isn't part of this saga.

So the question for this checkout is how many sagas end with a person, and whether anyone finds out.

Back of envelopeHow many checkouts end with a person
Every rate here is an assumption to replace with your own.

  checkouts                                  1,000,000/day
  declined at authorise, 3%                     30,000/day
  each one releases its stock and courier holds

Releases that meet a warehouse outage, 0.1%        30/day
  retried until the warehouse is back, about an hour
  → stock for 30 orders off sale for an hour

Releases that meet a bug and fail every time,
  1 in 100,000                                     0.3/day
  → about 2 a week that no retry clears
  ─────────────────────────────────────────────────────
Retries turn an outage into stock held for an hour, with
no person involved. Only an undo that fails every time
needs a person, about 2 a week.
Naive

Publish an undo event and assume it works

Each service publishes a failure event, and each earlier service undoes its own step when it hears one. Nothing retries a failed undo, and nothing checks that it happened. With the rates in the worksheet, 30 releases a day meet an outage and are lost, so their stock stays reserved for good, and the product page shows it as gone. No dashboard shows any of it, because each service did what its own events told it to.

Senior

An orchestrator that retries every undo, and a queue for the rest

Move the checkout to an orchestrator with durable state, such as Temporal or Step Functions. Register each undo before running its step, and retry undo steps until they succeed, as Temporal's guidance recommends. When an undo keeps failing, record it, carry on with the remaining undo steps, and raise it for a person. Alarm on the age of the oldest unfinished checkout.

Now the 30 releases a day that meet an outage clear on their own when the warehouse is back. Only the 2 a week that hit a bug reach a person. The cost is the orchestrator to run, and a queue that someone on the team owns.

Staff

Let deadlines do the undoing

Question why a failed checkout depends on its undo calls getting through. Reserve stock with a hold like the seat's, one that expires after 15 minutes, and book the courier slot as a hold too. The card authorisation lapses on its own as well. Keep sending the undo calls, the release, the courier cancel and the authorisation cancel, and keep retrying them. But when one can't get through, the deadline undoes the step anyway.

Undo calls against deadlines
In the top row, a declined card sends a release call to the warehouse (1). The warehouse is down, the call fails, and the stock stays reserved, in red. In the bottom row, the reservation carries a 15 minute deadline (2). The same release call fails, and the stock returns to sale anyway when the deadline passes.In the top row, a declined card sends a release call to the warehouse (1). The warehouse is down, the call fails, and the stock stays reserved, in red. In the bottom row, the reservation carries a 15 minute deadline (2). The same release call fails, and the stock returns to sale anyway when the deadline passes.
A hold that expires undoes itself. In the top row, a declined card sends a release call to the warehouse (1). The warehouse is down, the call fails, and the stock stays reserved, in red. In the bottom row, the reservation carries a 15 minute deadline (2). The same release call fails, and the stock returns to sale anyway when the deadline passes.

Make capture the pivot, once every hold is in place, so nothing that can refuse runs after it. Confirming the stock and the courier slot come after it, and both are retried. In the worksheet, stock caught by an outage is back on sale after 15 minutes instead of an hour, and a buggy release can't strand stock while someone fixes the code.

What you give up: stock from abandoned checkouts stays off sale until its hold lapses, and the product page has to subtract live holds from the stock it shows. An authorisation left to lapse also holds the customer's money for up to 7 days. Mastercard charges a fee on some authorisations that are neither cancelled nor captured in that time. So the cancel stays a retried undo, and the lapse is only the backstop.

The decision: an orchestrator that retries every undo, holds that expire as the backstop, and capture as the pivot. Budget a person for the undo that fails every time, because only a fix to the code clears it.

Where it goes wrong

1. The irreversible step runs before the pivot

Capturing the card, sending the email or paying the seller while a later step can still fail turns every undo into a refund, an apology or a loss.

2. A pending state with no deadline

A seat marked HELD with no expiry stays held forever when its orchestrator dies, which is the 2PC blocking failure moved into your own table.

3. Reading a pending state as final

The seat map shows held seats as sold, a revenue report counts authorised payments as captured, or a seller sees a credit that's still in transit. Every reader of a table with pending states has to know which statuses are final. Show and count only those, unless the reader is the saga itself. A HELD row whose held_until has passed counts as available, because nothing resets it until the next hold.

4. An undo that assumes its step ran

An undo that fails because "there's no authorisation to cancel" leaves the saga stuck on a step that did nothing. Make every undo succeed when its step never ran.

5. Choreography that outgrew its first services

Three services passing events in a line is easy to follow. Seven services with undo events flowing backwards is a saga nobody can see. Once any step needs an undo, put an orchestrator in front of it, so that one row says where booking 42 is.

If you memorise nothing else

factwhy it matters
A write across services always has a half-finished stateyou choose where it lives: locks, or rows you own
A 2PC participant holds its locks from its first write to the decisionafter its yes vote it can't release them, so a hot row across regions takes about 26 commits a second
A coordinator that dies after the votes blocks every participantthe half-finished state has an owner and no deadline
Spanner, CockroachDB and Kafka replicate the coordinator's decisionblocking gets rare, commits don't get cheaper
XA needs every participant to support an XA preparea card processor or an HTTP service has no XA prepare
A compensation is a new business action, not a rollbackit undoes meaning, never bytes
Undoable steps, then the pivot, then retried stepsnothing irreversible runs before the pivot
A step that can only be slow needs a retry, not an undoit belongs in an outbox, not a saga
A pending state needs a name, an owner and a deadlineHELD, held_by, held_until
Every step and every undo runs at least oncekey them by saga id and step name, and guard every write with held_by

What is expected at each level

Mid-level

Know why a write across two services can't use one database transaction, and what goes wrong if a process dies between the two writes. Describe 2PC as prepare and then commit, and know that participants hold locks while they wait. Describe a saga as a sequence of local transactions, each with an undo step.

You aren't expected to raise the pivot, isolation anomalies or deadlines on pending states without being asked. The interviewer may ask what happens if the card is declined after the seat is taken. You should answer with an undo step rather than a rollback.

Senior

You lead this part of the discussion, and three things should come up without prompting.

The order of the steps. Say which step is the pivot, and put capture, payouts and emails after it. A design that charges first and refunds on failure has the order backwards.

The pending state. Describe the held seat or the in-transit payment as a status with an owner and a deadline, and say what happens when the deadline passes.

Idempotent steps. Every step and every undo runs at least once. Key each one by the saga's id and the step, and make every undo succeed when its step never ran.

Disqualifying: proposing 2PC across a card processor or another company's API, and an undo that writes back an old value.

Staff+

A correct saga is still the bar. A staff answer also removes the parts of it that don't need to exist.

Move the boundary first. Ask whether the rows that change together can share a database or a shard key. Keying orders by event turns 98 of every 100 bookings into one local commit.

Put the step most likely to refuse first. In the debit-first wallet transfer, the only undo left moves money inside your own system.

Back every undo with a deadline. Holds and authorisations that expire undo themselves when the undo call can't get through.

Size what is left for a person. Work out how many sagas a day will still need a person, and make sure someone owns that queue.

And say what you would not build.

  • A general XA transaction manager across microservices, when a card processor can never take part in it.
  • A home-grown orchestrator with its own state tables, when Temporal or Step Functions already persist every step.
  • A compensation for every step "just in case", when reordering would have left the saga with one undo or none.
  • A 2PC across regions for a hot row, which caps it at about 26 commits a second.

Sources

The papers and vendor documents below are where every attributed figure and design comes from. The lock-time, hold and sharding arithmetic is worked out on the page, with its inputs stated.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.