← Back to Home

🔗 Distributed Transactions: 2PC, Sagas and the Outbox

Two-phase commit run for real across two PostgreSQL databases, sagas with compensations and their isolation anomaly, and the transactional outbox tested with 1,000 orders and random crashes.

Inside one database, a transaction makes several changes all-or-nothing, as Transactions and Isolation Levels showed. But a business operation often spans more than one system: placing an order writes the orders database, reserves stock in the inventory service, charges a card at a payment provider, and publishes an event to a message broker. No single BEGIN ... COMMIT covers all of that.

This article covers the three tools for that gap, each tested against PostgreSQL with failures injected on purpose:

It relies on the idempotency techniques from the previous article: every approach here retries something, so everything must tolerate duplicates.

The Dual-Write Problem

Start with the most common case. A service saves an order and publishes an OrderPlaced event so that the shipping service can act on it. Two writes, to two systems:

db.cursor().execute("INSERT INTO orders VALUES (%s, %s)", (oid, 100))
maybe_crash("after DB commit, before publish")
r.xadd("events", {"data": json.dumps({"event_id": f"o{oid}", "order_id": oid})})

The process can die between the two lines: a deploy, an out-of-memory kill, a node failure, a network timeout to the broker. To measure it, 1,000 orders were placed with a 5% chance of a "crash" (abandoning the rest of the work, as a killed process would) between the writes, in both orders:

dual write (DB, then publish)            orders=1000  events=958   missing shipments=42   shipments for unknown orders=0    duplicate shipments=0
dual write (publish, then DB)            orders=952   events=1000  missing shipments=0    shipments for unknown orders=48   duplicate shipments=0

Either way you lose. Write the database first and 42 customers paid for orders that never ship. Publish first and the warehouse ships 48 orders that don't exist. Real crash rates are far below 5%, but at a million orders a day even 0.01% is a hundred broken orders a day, and nobody notices until a customer complains.

Retrying doesn't fix it (the process that would retry is the one that died), and neither does reordering. You need the two writes to be atomic, or to turn them into one write.

Two-Phase Commit

2PC makes several databases commit or abort together. A coordinator runs two phases:

  1. Prepare: each participant does its work and then prepares: it writes everything durably and promises it can commit, even after a crash, but doesn't commit yet. It votes yes or no.
  2. Commit: if every vote was yes, the coordinator durably records "commit" and tells everyone to commit. Any no vote, and it tells everyone to roll back.

PostgreSQL supports the participant side with PREPARE TRANSACTION, COMMIT PREPARED and ROLLBACK PREPARED (enable it with max_prepared_transactions). Here's a coordinator across an orders database and an inventory database:

def place_order(order_id, sku, crash_after_prepare=False):
    gid = f"order-{order_id}"
    oc, ic = o.cursor(), i.cursor()
    # Phase 1: each participant does its work and PREPAREs: a durable promise that it can commit.
    votes = {}
    oc.execute("BEGIN"); oc.execute("INSERT INTO orders VALUES (%s, %s, 'placed')", (order_id, sku))
    oc.execute(f"PREPARE TRANSACTION '{gid}-orders'"); votes["orders"] = "yes"
    ic.execute("BEGIN")
    try:
        ic.execute("UPDATE stock SET qty = qty - 1 WHERE sku = %s", (sku,))
        ic.execute(f"PREPARE TRANSACTION '{gid}-inventory'"); votes["inventory"] = "yes"
    except psycopg2.Error as e:
        ic.execute("ROLLBACK"); votes["inventory"] = f"no ({e.diag.message_primary})"
    print(f"  phase 1 votes: {votes}")
    if crash_after_prepare:
        print(f"  coordinator CRASHES before phase 2; prepared transactions: {prepared()}")
        return
    # Phase 2: commit everywhere only if everyone voted yes, otherwise roll back everywhere.
    decision = "COMMIT" if all(v == "yes" for v in votes.values()) else "ROLLBACK"
    for name, cur in (("orders", oc), ("inventory", ic)):
        if votes[name] == "yes":
            cur.execute(f"{decision} PREPARED '{gid}-{name}'")
    print(f"  phase 2: {decision}")

(A first version of this test used the same transaction ID in both databases. They were on the same server, where prepared-transaction IDs must be unique, so the second PREPARE failed and was counted as a "no" vote. Each participant needs its own ID.)

Three runs:

A. Happy path: order a lamp (1 in stock)
  phase 1 votes: {'orders': 'yes', 'inventory': 'yes'}
  phase 2: COMMIT
   orders=[(1, 'lamp', 'placed')] stock=[('desk', 0), ('lamp', 0)]

B. Order a desk (0 in stock): inventory votes no
  phase 1 votes: {'orders': 'yes', 'inventory': 'no (new row for relation "stock" violates check constraint "stock_qty_check")'}
  phase 2: ROLLBACK
   orders=[(1, 'lamp', 'placed')] stock=[('desk', 0), ('lamp', 0)]

In B, the orders database had already prepared its insert, but the inventory vote was no, so the order was rolled back too. Neither database changed: true atomicity across two databases.

Now the failure 2PC is famous for. The coordinator crashes after both participants have prepared, before it sends the decision:

C. Coordinator crashes between the phases
  phase 1 votes: {'orders': 'yes', 'inventory': 'yes'}
  coordinator CRASHES before phase 2; prepared transactions: ['order-3-orders', 'order-3-inventory']
  another request tries to sell a lamp (lock_timeout 2 s)...
  -> blocked, then failed after 2.0 s: canceling statement due to lock timeout
  restarting the database server...
  after restart, still prepared: ['order-3-orders', 'order-3-inventory']
  state seen by others: orders=[(1, 'lamp', 'placed')] stock=[('desk', 0), ('lamp', 5)]
  recovery: the coordinator's log has no COMMIT decision for order-3, so the recovery process rolls back
  prepared now: ['none'] | orders=[(1, 'lamp', 'placed')] stock=[('desk', 0), ('lamp', 5)]

The participants are in doubt. They promised to commit if asked, so they can't roll back on their own; they don't know whether the other participant voted yes, so they can't commit either. Meanwhile they hold their locks: another customer's attempt to buy a lamp blocked until its lock timeout. The prepared transactions even survived a database restart, still holding those locks. Only the coordinator's decision, or a human running ROLLBACK PREPARED, releases them.

That's why 2PC is called a blocking protocol. Its costs:

2PC is alive and well inside distributed databases: Spanner, CockroachDB and YugabyteDB use it between their own shards, with each participant and the coordinator replicated by consensus (Raft), so "the coordinator crashed" means losing a majority of replicas, not one process. Across independently deployed microservices, it's rarely the right tool.

Step Through Both Protocols

Pick a scenario and step through the messages. The state boxes show what each participant knows and whether it's holding locks:

Sagas

A saga gives up on atomic commit. It splits the operation into a sequence of local transactions, each committed immediately in its own service. If a step fails, it runs compensating transactions for the steps already done, in reverse order: a refund for a charge, a release for a reservation, a cancellation for an order.

There are two ways to coordinate one:

Here's an orchestrated saga for placing an order. Each step and compensation is a local transaction keyed by the saga ID, so it's idempotent:

def run_saga(s, cust, sku, amount, slow_payment=0.0, crash_after=None):
    steps = [
        ("create order", lambda: create_order(s, cust, sku, amount), lambda: cancel_order(s)),
        ("reserve stock", lambda: reserve_stock(s, sku), lambda: release_stock(s)),
        ("charge payment", lambda: (time.sleep(slow_payment), charge(s, cust, amount)), None),
        ("approve order", lambda: approve_order(s), None),
    ]
    done = []
    for name, action, compensate in steps:
        try:
            action(); log(s, name, "ok"); done.append((name, compensate))
            if crash_after == name:
                log(s, "orchestrator", "CRASHED"); return "crashed"
        except RuntimeError as e:
            log(s, name, f"FAILED: {e}")
            for cname, comp in reversed(done):           # undo completed steps, newest first
                if comp: comp(); log(s, "compensate", f"undo '{cname}'")
            return "compensated"
    return "completed"

The isolation anomaly

There's one lamp in stock. Alice, whose wallet holds 50, orders the 120 lamp; her payment provider takes a moment to decline. While that's happening, Bob tries to buy the same lamp:

1. Alice (balance 50) orders a 120 lamp while Bob tries to buy the same lamp
      6.8 ms  [A] create order     ok
     13.7 ms  [A] reserve stock    ok
    112.7 ms  [B] create order     ok
    115.9 ms  [B] reserve stock    FAILED: out of stock
    122.0 ms  [B] compensate       undo 'create order'
    319.1 ms  [A] charge payment   FAILED: payment declined
    325.2 ms  [A] compensate       undo 'reserve stock'
    330.5 ms  [A] compensate       undo 'create order'
  results: {'bob': 'compensated', 'alice': 'compensated'}
  orders=[('A', 'CANCELLED'), ('B', 'CANCELLED')] lamps available=1 wallets=[('alice', 50), ('bob', 500), ('carol', 500)]

The saga worked as designed: Alice's failed order was compensated and everything is consistent. But Bob was told the lamp was out of stock because of a reservation that was later undone. The shop ends with both orders cancelled and the lamp unsold.

That's the trade-off. A saga is atomic eventually (all steps happen, or all are compensated), but it isn't isolated: other transactions see its intermediate states. In isolation-level terms this is like a dirty read, at the business level. Countermeasures:

Crashes in the middle

An orchestrator that crashes mid-saga must pick up where it left off. Here it crashes right after reserving stock, then resumes by replaying the saga from the start:

2. Carol buys the lamp; the orchestrator crashes after reserving stock, then resumes
      5.5 ms  [C] create order     ok
     11.3 ms  [C] reserve stock    ok
     14.1 ms  [C] orchestrator     CRASHED
  crashed
  orders=[('A', 'CANCELLED'), ('B', 'CANCELLED'), ('C', 'PENDING')] lamps available=0 wallets=[('alice', 50), ('bob', 500), ('carol', 500)]
     17.3 ms  [C] orchestrator     resumed from saga_log
     20.1 ms  [C] create order     ok
     23.3 ms  [C] reserve stock    ok
     29.7 ms  [C] charge payment   ok
     35.1 ms  [C] approve order    ok
  completed
  orders=[('A', 'CANCELLED'), ('B', 'CANCELLED'), ('C', 'APPROVED')] lamps available=0 wallets=[('alice', 50), ('bob', 500), ('carol', 380)]

Replaying "reserve stock" a second time didn't take a second lamp, because the step checks for an existing reservation with this saga ID first:

def reserve_stock(s, sku):
    with stock_db.cursor() as cur:
        cur.execute("BEGIN")
        cur.execute("SELECT 1 FROM s_reservations WHERE saga_id = %s", (s,))
        if cur.fetchone(): cur.execute("COMMIT"); return      # already reserved by an earlier attempt
        cur.execute("UPDATE s_stock SET available = available - 1 WHERE sku = %s AND available > 0", (sku,))
        if cur.rowcount == 0: cur.execute("ROLLBACK"); raise RuntimeError("out of stock")
        cur.execute("INSERT INTO s_reservations VALUES (%s, %s)", (s, sku)); cur.execute("COMMIT")

This is the core rule of sagas: every step and every compensation must be idempotent, because after any crash the orchestrator will run some of them again. That's what durable workflow engines like Temporal give you: they record each step's result and replay the workflow code after a crash, skipping steps already done.

Designing compensations

Compensations are the hard part of a saga:

The Transactional Outbox

Back to the dual-write problem. The outbox pattern makes it one write: insert the order and the event into the same database, in the same local transaction. The event goes into an outbox table. A separate relay reads unpublished outbox rows, publishes them to the broker, and marks them published:

with db.cursor() as cur:
    cur.execute("BEGIN")
    cur.execute("INSERT INTO orders VALUES (%s, %s)", (oid, 100))
    maybe_crash("inside the transaction")       # rolls back both rows: no order, no event
    cur.execute("INSERT INTO outbox (order_id, payload) VALUES (%s, %s)",
                (oid, json.dumps({"event_id": f"o{oid}", "order_id": oid})))
    cur.execute("COMMIT")
def relay(batch):
    """Publish unpublished outbox rows; marks are committed once per batch. A crash loses the uncommitted marks."""
    global published
    with db.cursor() as cur:
        cur.execute("BEGIN")
        cur.execute("SELECT id, payload FROM outbox WHERE published_at IS NULL ORDER BY id LIMIT %s FOR UPDATE SKIP LOCKED", (batch,))
        try:
            for oid, payload in cur.fetchall():
                r.xadd("events", {"data": json.dumps(payload)}); published += 1
                maybe_crash("relay: after publish, before marking")
                cur.execute("UPDATE outbox SET published_at = now() WHERE id = %s", (oid,))
            cur.execute("COMMIT")
        except Crash:
            cur.execute("ROLLBACK")          # the marks are lost; those rows will be published again

The relay can still crash between publishing and marking, so some events get published twice. The outbox gives at-least-once delivery; the consumer must be idempotent. Here the shipping service records each event ID in an inbox table in the same transaction as its work, and skips IDs it has seen:

def consume(dedupe):
    """Shipping service: read every event from the stream and create a shipment."""
    for msg_id, fields in r.xrange("events"):
        ev = json.loads(fields["data"])
        with db.cursor() as cur:
            cur.execute("BEGIN")
            if dedupe:   # inbox: remember processed event ids in the same transaction as the work
                cur.execute("INSERT INTO inbox VALUES (%s) ON CONFLICT DO NOTHING", (ev["event_id"],))
                if cur.rowcount == 0: cur.execute("ROLLBACK"); continue
            cur.execute("INSERT INTO shipments (order_id) VALUES (%s)", (ev["order_id"],))
            cur.execute("COMMIT")

The same 1,000 orders with a 5% crash rate, this time at every step: inside the order transaction, and in the relay between publishing and marking:

outbox, consumer without dedupe          orders=952   events=1009  missing shipments=0    shipments for unknown orders=0    duplicate shipments=57
outbox, consumer with inbox dedupe       orders=952   events=1009  missing shipments=0    shipments for unknown orders=0    duplicate shipments=0
relay batch size 1: 1009 events published for 952 outbox rows

The relay's batching matters too. Committing the "published" marks once per batch of 50 instead of once per event:

outbox, consumer without dedupe          orders=952   events=5051  missing shipments=0    shipments for unknown orders=0    duplicate shipments=4099
outbox, consumer with inbox dedupe       orders=952   events=5051  missing shipments=0    shipments for unknown orders=0    duplicate shipments=0
relay batch size 50: 5051 events published for 952 outbox rows

A crash anywhere in a batch republishes the whole batch. With a 5% crash rate per event (far above reality), that's five times the events. Correctness held thanks to the inbox; efficiency didn't. Batch for throughput, but keep batches small enough that a retry is cheap.

Two ways to build the relay:

Either way, delete old outbox rows regularly, and remember that ordering is only guaranteed per relay partition: if order matters (all events for one order), partition by that key.

The outbox is the workhorse of event-driven systems. It's often combined with a choreographed saga: each saga step is a local transaction that writes its state change and its "next step" event through an outbox.

Choosing an Approach

2PC Saga Outbox + idempotent consumers
Guarantee Atomic and isolated Eventually all-or-compensated; not isolated Event published if and only if the change committed (at least once)
Latency Two round-trips, locks held One local transaction per step One local transaction; event delivered asynchronously
Availability Needs every participant and the coordinator Each step needs only its own service Needs only the local database to accept the change
Failure handling Automatic abort; blocks if coordinator fails You write compensations Retries; consumers deduplicate
Works with external APIs No Yes Yes, as producer or consumer
Good for Shards of one distributed database; a few databases you control Multi-service business processes Notifying other services of a change

A decision guide:

  1. First, can you avoid it? If two pieces of data must change atomically, they probably belong to the same service and the same database. Redrawing a service boundary is often better than any protocol. A modular monolith with one database gets real ACID transactions for free.
  2. Need to change your data and tell others? Outbox, with idempotent consumers.
  3. A multi-step process across services that may need undoing? A saga, orchestrated if it has more than a few steps, with idempotent steps and compensations, designed around the isolation anomaly.
  4. True atomicity and isolation across shards? A database that does 2PC over consensus for you (Spanner, CockroachDB, YugabyteDB), rather than building it yourself.

Key Takeaways

Copied to clipboard!