Database Distributed Systems · Lesson 107 of 112

Database Distributed Transactions and Sagas

What you will learn

  • Why a transaction that spans several machines is hard
  • How two-phase commit (2PC) works: prepare, then commit or abort
  • Why 2PC can block when the coordinator fails
  • What a saga is and how compensating steps undo earlier work
  • The trade-offs between the two

All code in this lesson is a simulation that imitates an idea. It is not a real database. You can run each block on its own.

1. The problem

In chapter 6 a transaction on one database was all-or-nothing (atomicity). Now imagine an order that must change data on three separate systems: the orders system, the stock system and the payments system. If stock is reserved but the payment step fails, the data is left half-done. We need all three to agree: either all succeed, or none does. Messages between machines can be lost and machines can crash at any moment, so this is much harder than on one machine.

Two common approaches are two-phase commit and sagas.

2. Two-phase commit

Two-phase commit (2PC) uses one coordinator and several participants. As the name says, it has two phases:

  1. Prepare (voting). The coordinator asks every participant, "can you commit?". Each participant does the work, makes it durable and promises that it can commit if told to. It answers yes or no. After a "yes" it must keep that promise even if it crashes and restarts.
  2. Commit or abort (decision). If all voted yes, the coordinator tells everyone to commit. If anyone voted no, it tells everyone to abort.

The three runs below show success, a refusal and a crash:

class Participant:
    def __init__(self, name, can_commit=True):
        self.name, self.can_commit = name, can_commit
        self.state = "idle"
    def prepare(self):
        # phase 1: promise to commit if asked (and keep the promise even after a crash)
        self.state = "prepared" if self.can_commit else "refused"
        return self.can_commit
    def commit(self): self.state = "committed"
    def abort(self): self.state = "aborted"

def two_phase_commit(participants, crash_before_decision=False):
    votes = [p.prepare() for p in participants]
    print("  votes:", [(p.name, v) for p, v in zip(participants, votes)])
    if crash_before_decision:
        print("  coordinator crashed before sending the decision!")
        return
    if all(votes):
        for p in participants: p.commit()
        print("  decision: COMMIT")
    else:
        for p in participants: p.abort()
        print("  decision: ABORT")

def states(ps): return {p.name: p.state for p in ps}

print("1. Everyone can commit:")
ps = [Participant("orders"), Participant("stock"), Participant("payments")]
two_phase_commit(ps); print(" ", states(ps))

print("\n2. One participant cannot commit:")
ps = [Participant("orders"), Participant("stock", can_commit=False), Participant("payments")]
two_phase_commit(ps); print(" ", states(ps))

print("\n3. Coordinator crashes after the prepare phase:")
ps = [Participant("orders"), Participant("stock"), Participant("payments")]
two_phase_commit(ps, crash_before_decision=True); print(" ", states(ps))
print("  the prepared participants must wait: they cannot commit or abort on their own")
1. Everyone can commit:
  votes: [('orders', True), ('stock', True), ('payments', True)]
  decision: COMMIT
  {'orders': 'committed', 'stock': 'committed', 'payments': 'committed'}

2. One participant cannot commit:
  votes: [('orders', True), ('stock', False), ('payments', True)]
  decision: ABORT
  {'orders': 'aborted', 'stock': 'aborted', 'payments': 'aborted'}

3. Coordinator crashes after the prepare phase:
  votes: [('orders', True), ('stock', True), ('payments', True)]
  coordinator crashed before sending the decision!
  {'orders': 'prepared', 'stock': 'prepared', 'payments': 'prepared'}
  the prepared participants must wait: they cannot commit or abort on their own

Read the output:

  • Case 1: all three vote yes, so the decision is commit and all three commit.
  • Case 2: stock cannot commit, so the decision is abort and all three abort. Nobody is left half-done: this is the atomic behaviour we wanted.
  • Case 3: all three voted yes, then the coordinator crashed before sending the decision. The participants are all in the prepared state. They have promised to commit if told to, so they cannot abort on their own (the coordinator might have decided to commit), and they cannot commit on their own (it might have decided to abort). They have to wait, holding their locks (lesson 6.6), until the coordinator comes back or is replaced. This is the well-known weakness of 2PC: it can block.
Quick check: why can a participant not simply abort when the coordinator disappears after it voted yes?

Because the coordinator may already have told other participants to commit. If this one aborted, the participants would disagree, which breaks the all-or-nothing promise.

The vote in SQL. This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). The participants are a small table of their own; the coordinator's decision is one statement that looks at all the votes (Reset data removes the table). Case 1: everyone can commit.

CREATE TABLE participants (name TEXT PRIMARY KEY, can_commit INTEGER NOT NULL, state TEXT NOT NULL DEFAULT 'idle');
INSERT INTO participants (name, can_commit) VALUES ('orders', 1), ('stock', 1), ('payments', 1);
UPDATE participants SET state = CASE WHEN can_commit = 1 THEN 'prepared' ELSE 'refused' END;
UPDATE participants SET state = CASE WHEN (SELECT MIN(can_commit) FROM participants) = 1 THEN 'committed' ELSE 'aborted' END;
SELECT name, state FROM participants ORDER BY name;
name      state
--------  ---------
orders    committed
payments  committed
stock     committed
(3 rows)

Case 2: stock cannot commit, so the decision is to abort for everyone:

UPDATE participants SET can_commit = 0, state = 'idle' WHERE name = 'stock';
UPDATE participants SET state = 'idle' WHERE name <> 'stock';
UPDATE participants SET state = CASE WHEN can_commit = 1 THEN 'prepared' ELSE 'refused' END;
UPDATE participants SET state = CASE WHEN (SELECT MIN(can_commit) FROM participants) = 1 THEN 'committed' ELSE 'aborted' END;
SELECT name, state FROM participants ORDER BY name;
name      state
--------  -------
orders    aborted
payments  aborted
stock     aborted
(3 rows)

Case 3: the coordinator crashes after the prepare phase, so the decision statement never runs and everyone is left prepared:

UPDATE participants SET can_commit = 1, state = 'idle';
UPDATE participants SET state = CASE WHEN can_commit = 1 THEN 'prepared' ELSE 'refused' END;
SELECT name, state FROM participants ORDER BY name;
name      state
--------  --------
orders    prepared
payments  prepared
stock     prepared
(3 rows)
CREATE TABLE participants (name TEXT PRIMARY KEY, can_commit INTEGER NOT NULL, state TEXT NOT NULL DEFAULT 'idle');
INSERT INTO participants (name, can_commit) VALUES ('orders', 1), ('stock', 1), ('payments', 1);
UPDATE participants SET state = CASE WHEN can_commit = 1 THEN 'prepared' ELSE 'refused' END;
UPDATE participants SET state = CASE WHEN (SELECT MIN(can_commit) FROM participants) = 1 THEN 'committed' ELSE 'aborted' END;
SELECT name, state FROM participants ORDER BY name;
name      state
--------  ---------
orders    committed
payments  committed
stock     committed
(3 rows)

Case 2: stock cannot commit, so the decision is to abort for everyone:

UPDATE participants SET can_commit = 0, state = 'idle' WHERE name = 'stock';
UPDATE participants SET state = 'idle' WHERE name <> 'stock';
UPDATE participants SET state = CASE WHEN can_commit = 1 THEN 'prepared' ELSE 'refused' END;
UPDATE participants SET state = CASE WHEN (SELECT MIN(can_commit) FROM participants) = 1 THEN 'committed' ELSE 'aborted' END;
SELECT name, state FROM participants ORDER BY name;
name      state
--------  -------
orders    aborted
payments  aborted
stock     aborted
(3 rows)

Case 3: the coordinator crashes after the prepare phase, so the decision statement never runs and everyone is left prepared:

UPDATE participants SET can_commit = 1, state = 'idle';
UPDATE participants SET state = CASE WHEN can_commit = 1 THEN 'prepared' ELSE 'refused' END;
SELECT name, state FROM participants ORDER BY name;
name      state
--------  --------
orders    prepared
payments  prepared
stock     prepared
(3 rows)
CREATE TABLE participants (name TEXT PRIMARY KEY, can_commit INTEGER NOT NULL, state TEXT NOT NULL DEFAULT 'idle');
INSERT INTO participants (name, can_commit) VALUES ('orders', 1), ('stock', 1), ('payments', 1);
UPDATE participants SET state = CASE WHEN can_commit = 1 THEN 'prepared' ELSE 'refused' END;
UPDATE participants SET state = CASE WHEN (SELECT MIN(can_commit) FROM participants) = 1 THEN 'committed' ELSE 'aborted' END;
SELECT name, state FROM participants ORDER BY name;
name      state
--------  ---------
orders    committed
payments  committed
stock     committed
(3 rows)

Case 2: stock cannot commit, so the decision is to abort for everyone:

UPDATE participants SET can_commit = 0, state = 'idle' WHERE name = 'stock';
UPDATE participants SET state = 'idle' WHERE name <> 'stock';
UPDATE participants SET state = CASE WHEN can_commit = 1 THEN 'prepared' ELSE 'refused' END;
UPDATE participants SET state = CASE WHEN (SELECT MIN(can_commit) FROM participants) = 1 THEN 'committed' ELSE 'aborted' END;
SELECT name, state FROM participants ORDER BY name;
name      state
--------  -------
orders    aborted
payments  aborted
stock     aborted
(3 rows)

Case 3: the coordinator crashes after the prepare phase, so the decision statement never runs and everyone is left prepared:

UPDATE participants SET can_commit = 1, state = 'idle';
UPDATE participants SET state = CASE WHEN can_commit = 1 THEN 'prepared' ELSE 'refused' END;
SELECT name, state FROM participants ORDER BY name;
name      state
--------  --------
orders    prepared
payments  prepared
stock     prepared
(3 rows)

Other costs of 2PC: it needs several message round trips, so it is slower; locks are held during both phases; and every participant must support the protocol. Real systems reduce the blocking problem by making the coordinator itself fault tolerant (lesson 14.7), but the protocol is still seen as expensive across many machines or across organisations.

3. Sagas

A saga takes a different approach. Instead of one big all-or-nothing transaction, it splits the work into a sequence of small local transactions, each committed on its own. If a later step fails, the saga does not roll back (the earlier steps are already committed). Instead it runs compensating steps that undo the effect of each completed step, in reverse order.

def run_saga(steps, fail_at=None):
    done = []
    for i, (name, action, compensation) in enumerate(steps):
        if i == fail_at:
            print(f"  step '{name}' FAILED")
            for done_name, comp in reversed(done):
                print(f"  compensating: {comp}")
            return False
        print(f"  step '{name}': {action}")
        done.append((name, compensation))
    return True

steps = [
    ("create order", "order 17 created", "cancel order 17"),
    ("reserve stock", "2 items reserved", "release the 2 reserved items"),
    ("take payment", "500 taka charged", "refund 500 taka"),
    ("book delivery", "courier booked", "cancel courier booking"),
]
print("Saga, everything works:")
print("  result:", run_saga(steps))
print("\nSaga, delivery booking fails:")
print("  result:", run_saga(steps, fail_at=3))
Saga, everything works:
  step 'create order': order 17 created
  step 'reserve stock': 2 items reserved
  step 'take payment': 500 taka charged
  step 'book delivery': courier booked
  result: True

Saga, delivery booking fails:
  step 'create order': order 17 created
  step 'reserve stock': 2 items reserved
  step 'take payment': 500 taka charged
  step 'book delivery' FAILED
  compensating: refund 500 taka
  compensating: release the 2 reserved items
  compensating: cancel order 17
  result: False

Read the output:

  • When every step works, the saga finishes.
  • When the delivery booking fails, the saga compensates the three completed steps in reverse order: refund the payment, release the stock, cancel the order. The business result is "as if the order never happened", although for a short while the money really was taken.

A saga on real tables, in SQL. Each step is its own small transaction that is committed at once; a compensation is a new statement that undoes the effect of a step. The cells change the sample data of your browser's copy; Reset data puts it back.

The steps: create the order, reserve 2 items of product 2, take a payment of 500. Then the delivery booking fails, and the compensations run in reverse order:

SELECT stock FROM products WHERE product_id = 2;
INSERT INTO orders (customer_id, order_date, status, ship_city) VALUES (1, '2026-10-01', 'pending', 'Leeds');
UPDATE products SET stock = stock - 2 WHERE product_id = 2;
INSERT INTO payments (order_id, paid_on, method, amount) VALUES (2601, '2026-10-01', 'card', 500.0);
SELECT (SELECT stock FROM products WHERE product_id = 2) AS stock_now,
       (SELECT status FROM orders WHERE order_id = 2601) AS order_status,
       (SELECT COUNT(*) FROM payments WHERE order_id = 2601) AS payments;
stock
-----
  150
(1 row)

stock_now  order_status  payments
---------  ------------  --------
      148  pending              1
(1 row)

The delivery booking failed. Compensate: refund, release the items, cancel the order.

DELETE FROM payments WHERE order_id = 2601;
UPDATE products SET stock = stock + 2 WHERE product_id = 2;
UPDATE orders SET status = 'cancelled' WHERE order_id = 2601;
SELECT (SELECT stock FROM products WHERE product_id = 2) AS stock_now,
       (SELECT status FROM orders WHERE order_id = 2601) AS order_status,
       (SELECT COUNT(*) FROM payments WHERE order_id = 2601) AS payments;
stock_now  order_status  payments
---------  ------------  --------
      150  cancelled            0
(1 row)

The steps: debit account 1 by 5.00, then credit account 2 (at "another system"). The credit fails, and the compensation gives the money back:

SELECT account_id, balance_cents FROM accounts WHERE account_id IN (1, 2) ORDER BY account_id;
UPDATE accounts SET balance_cents = balance_cents - 500 WHERE account_id = 1;
SELECT account_id, balance_cents FROM accounts WHERE account_id IN (1, 2) ORDER BY account_id;
account_id  balance_cents
----------  -------------
         1         192400
         2          52078
(2 rows)

account_id  balance_cents
----------  -------------
         1         191900
         2          52078
(2 rows)

The credit step failed. Compensate: put the 5.00 back.

UPDATE accounts SET balance_cents = balance_cents + 500 WHERE account_id = 1;
SELECT account_id, balance_cents FROM accounts WHERE account_id IN (1, 2) ORDER BY account_id;
account_id  balance_cents
----------  -------------
         1         192400
         2          52078
(2 rows)

The steps: enroll student 360 in section 1, reserve a seat (lower the free capacity), charge the fee. The fee payment fails, and the compensations run in reverse order:

SELECT capacity FROM sections WHERE section_id = 1;
INSERT INTO enrollments (student_id, section_id, enrolled_on) VALUES (360, 1, '2026-10-01');
UPDATE sections SET capacity = capacity - 1 WHERE section_id = 1;
SELECT (SELECT capacity FROM sections WHERE section_id = 1) AS capacity_now,
       (SELECT COUNT(*) FROM enrollments WHERE student_id = 360 AND section_id = 1) AS enrolled;
capacity
--------
      25
(1 row)

capacity_now  enrolled
------------  --------
          24         1
(1 row)

The fee payment failed. Compensate: release the seat, remove the enrollment.

UPDATE sections SET capacity = capacity + 1 WHERE section_id = 1;
DELETE FROM enrollments WHERE student_id = 360 AND section_id = 1;
SELECT (SELECT capacity FROM sections WHERE section_id = 1) AS capacity_now,
       (SELECT COUNT(*) FROM enrollments WHERE student_id = 360 AND section_id = 1) AS enrolled;
capacity_now  enrolled
------------  --------
          25         0
(1 row)

The data ends where it started. In between, other users could have seen the intermediate state, which is the price of a saga.

A compensation is a new action, not a magic undo, so it needs care:

  • Some actions cannot be undone (an email already sent). Put such steps last, or design a different compensation, such as sending a correction.
  • A compensation may itself fail or be retried, so it should be idempotent: running it twice has the same effect as running it once (refunding order 17 twice must not refund twice).
  • Other users can see the intermediate states (for example a reserved item that will be released). A saga gives up the isolation of a normal transaction (lesson 6.3).

4. Comparing the two

Two-phase commit Saga
Result while running nobody sees partial results (locks held) partial results are visible
If a step fails everything aborts together earlier steps are undone by compensations
Blocking participants can block if the coordinator fails no long locks
Speed and scale slower, holds locks across machines faster, works across many services
Complexity in the protocol (usually supplied by the database) in your application (you write the compensations)
Best for a few systems that must be strictly consistent long business processes across services

A good question before using either: can the data be designed so one database owns the whole change? A single local transaction (chapter 6) is simpler and safer than any distributed approach, and is the reason many designs keep related data together (lesson 14.3).

Worked example: deciding for an order

For the order in the simulation:

  1. The orders, stock and payments tables sit in one database. Use one ordinary transaction. Done.
  2. They are separate services owned by different teams. A saga fits: each service commits its own step, with a compensation for each (cancel, release, refund).
  3. Two accounts in two different databases must be moved strictly together, with no visible half-way state. Consider 2PC if both databases support it, and accept the cost.

The order and the services are made up.

Common mistakes

  • Using a distributed transaction when one database could hold the data.
  • Forgetting that compensations can fail or run twice. Make them idempotent and retry them.
  • Ignoring visible intermediate states in a saga. Other users may see an order that will later be cancelled.
  • Assuming 2PC removes all risk. A crashed coordinator can leave participants waiting.

Key takeaways

  • A change across several machines must either happen everywhere or nowhere, and failures make that hard.
  • Two-phase commit: all prepare and vote, then all commit or all abort; it is atomic but can block if the coordinator fails.
  • A saga commits small steps one by one and undoes earlier steps with compensations if a later one fails.
  • Sagas give up isolation and need idempotent compensations.
  • Prefer keeping related data in one database so that one local transaction is enough.

Practice

1. Name the two phases of two-phase commit.

Show answer

Prepare (every participant votes whether it can commit) and then commit or abort (the coordinator decides: commit only if all voted yes).

2. In case 2 of the simulation, why did orders and payments abort even though they had voted yes?

Show answer

Because one participant (stock) voted no, and the all-or-nothing rule requires everyone to abort.

3. What is the blocking problem of 2PC?

Show answer

If the coordinator fails after the participants have prepared, they can neither commit nor abort on their own, so they wait, holding locks, until the coordinator returns or is replaced.

4. What is a compensating step, and why are they run in reverse order?

Show answer

It is an action that undoes the business effect of an earlier committed step (a refund for a payment). They run in reverse order because later steps may depend on earlier ones, so the last thing done is undone first.

5. Why must a compensation be idempotent?

Show answer

Because it may be retried after a failure or a lost message. If running it twice had twice the effect (two refunds), the retry would cause a new error.

6. Which property of ACID does a saga give up, and what is the visible effect?

Show answer

Isolation: other users can see the intermediate results of a saga (for example a reserved item or a charged payment) before the saga finishes or is compensated.