Distributed Transactions

Keeping data consistent when one business operation spans several databases or services.

What is it?

Inside one database, a transaction is easy to reason about: either all of its changes happen, or none do. Once an operation touches several databases or services (charge a card, reserve stock, create a shipment), there's no single database to guarantee that. One step can succeed while another fails, leaving the system half-done.

There are two broad answers:

- Atomic commit across participants, mainly two-phase commit (2PC). All participants commit or all abort, at the cost of coordination and blocking. - Sagas: run a sequence of local transactions, and if a later step fails, run compensating actions to undo the earlier ones. You give up isolation and immediate consistency in exchange for availability and loose coupling.

Both need a reliable way to say "my local data changed, tell others", which is where the transactional outbox and change data capture (CDC) come in. They solve the dual-write problem: writing to a database and publishing a message are two separate operations, and either can fail without the other.

Explain like I'm 10

2PC is a wedding: the officiant asks each person 'do you?', and only after both say yes does anyone get married. If the officiant faints between the vows and the announcement, everyone stands frozen. A saga is booking a trip yourself: you book the flight, then the hotel, and if the hotel is full you cancel the flight. Briefly, you held a flight with no hotel.

Examples

Orchestrated saga with compensations

interface SagaStep {
  name: string;
  run: (order: Order) => Promise<void>;
  compensate: (order: Order) => Promise<void>;
}

const placeOrderSaga: SagaStep[] = [
  { name: "reserve-stock", run: reserveStock, compensate: releaseStock },
  { name: "charge-card",   run: chargeCard,   compensate: refundCard },
  { name: "ship",          run: createShipment, compensate: cancelShipment },
];

async function runSaga(order: Order, steps: SagaStep[]): Promise<void> {
  const completedSteps: SagaStep[] = [];
  for (const step of steps) {
    try {
      await step.run(order); // each step is a local transaction, idempotent
      completedSteps.push(step);
      await sagaLog.record(order.id, step.name, "done"); // survives restarts
    } catch (error) {
      // Undo in reverse order. Compensations must be idempotent and retried
      // until they succeed; they can't simply "fail".
      for (const done of completedSteps.reverse()) {
        await retryForever(() => done.compensate(order));
      }
      throw error;
    }
  }
}

A real orchestrator persists the saga state so it can resume after a crash; the in-memory list here only shows the control flow.

Transactional outbox

BEGIN;
  UPDATE accounts SET balance = balance - 100 WHERE id = 42;
  INSERT INTO outbox (id, aggregate_id, event_type, payload)
  VALUES ('evt-9f1c', 42, 'AccountDebited', '{"amount":100}');
COMMIT;

-- A separate relay (a poller, or CDC reading the WAL/binlog) publishes
-- outbox rows to the broker, then marks them sent or lets them be pruned.
-- If it crashes after publishing but before marking, it publishes again:
-- delivery is at-least-once, so consumers dedupe on the event id.

The business change and the event either both commit or neither does, because they share one local transaction.

How it works

Two-phase commit (2PC). A coordinator drives the participants:

1. Prepare: the coordinator asks every participant "can you commit?" Each participant does the work, writes it durably (including locks) and votes yes or no. A yes vote is a promise: "I will commit if told to, even after a crash." 2. Commit/Abort: if all voted yes, the coordinator durably logs the decision and sends commit; otherwise it sends abort.

The blocking problem. After voting yes, a participant may not decide on its own. If the coordinator crashes before sending the decision, the participant is in doubt: it can't commit (others may have voted no) or abort (the coordinator may have decided commit). It must hold its locks and wait for the coordinator to recover. 2PC also adds latency (two round trips plus forced disk writes) and needs every participant to support it (XA in many databases and brokers). Running the coordinator itself on consensus, as Spanner does with Paxos groups, removes the single point of failure.

Sagas (Garcia-Molina and Salem, 1987) replace one big transaction with a sequence of local transactions T1..Tn, each with a compensation C1..Cn. If Tk fails, run Ck-1..C1. Two ways to coordinate:

- Choreography: each service listens for events and reacts ("OrderCreated" → inventory reserves → "StockReserved" → payment charges). No central brain, but the flow is spread across services and hard to see, test and change; cycles are easy to create. - Orchestration: a saga orchestrator (a service or workflow engine such as Temporal or AWS Step Functions) tells each participant what to do and tracks state. The flow is explicit in one place, at the cost of a component that knows about everyone.

Sagas are ACD without I: other transactions can see intermediate states (stock reserved but payment not yet taken). Countermeasures include semantic locks (a "PENDING" status), commutative updates, and ordering steps so the ones most likely to fail, or impossible to undo (sending an email), run last or are made pivots.

Transactional outbox. Instead of "write DB, then publish to Kafka" (which loses or duplicates events when one side fails), write the event to an outbox table in the same local transaction. A relay publishes from the outbox afterwards.

Change data capture (CDC) reads the database's own replication log (PostgreSQL logical decoding, MySQL binlog) and streams every committed change as an event. Tools like Debezium do this. CDC is often the relay for an outbox, or used directly to feed caches, search indexes and warehouses with changes in commit order.

Two-phase commit

 Coordinator             Participant A          Participant B
     │ ── prepare ─────────►  │                      │
     │ ── prepare ────────────┼────────────────────► │
     │ ◄───────────── yes ─── │                      │
     │ ◄──────────────────────┼─────────────── yes ──│
  log "commit"                │                      │
     │ ── commit ──────────►  │                      │
     │ ── commit ─────────────┼────────────────────► │

  If the coordinator dies after the yes votes and before "commit"
  reaches A and B, both are stuck in doubt, holding locks.

Outbox + CDC

  Service ──(one local tx)──► [orders table] + [outbox table]
                                         │ WAL / binlog
                                         ▼
                                    CDC relay ──► Kafka ──► consumers

Why does it exist?

Microservices and partitioned databases split data that one business operation needs to change together. Without a deliberate strategy you get charged customers with no order, or orders with no payment. 2PC gives atomicity when you control all participants and can tolerate blocking; sagas give a workable model when participants are independent services; the outbox and CDC make "change data and notify others" reliable.

When to use it

- 2PC: a few participants inside one trust and ops boundary, strong atomicity required, low contention (e.g. a sharded database committing across shards, often handled for you by the database). - Sagas: long-running business processes across services (orders, bookings, onboarding) where each step has a sensible undo. - Outbox/CDC: any time a service must update its database and emit an event reliably, or feed downstream stores from a source of truth.

When not to use it

- Don't reach for distributed transactions if you can redraw service boundaries so the data that changes together lives in one database. - Avoid 2PC across services owned by different teams, third-party APIs or high-latency links: it couples availability and holds locks. - Sagas are a poor fit when intermediate states must never be visible, or steps can't be undone or compensated (a released wire transfer). - Don't use the outbox for data that doesn't need guaranteed delivery; a fire-and-forget publish may be fine for metrics.

Common mistakes

  • Writing to the database and then publishing to a broker as two separate calls (the dual-write problem), so a crash in between loses the event or publishes one for a rolled-back change.

  • Assuming a compensation is a rollback. It's a new business action (a refund, a cancellation) that others may already have observed, and it can fail too, so it must be retried and idempotent.

  • Forgetting that sagas lack isolation, so concurrent sagas read each other's half-finished state and produce anomalies like overselling.

  • Making saga steps or outbox consumers non-idempotent, even though both rely on at-least-once delivery and retries.

  • Treating 2PC's coordinator as optional infrastructure. If it isn't highly available, its crash blocks every in-doubt transaction and their locks.

Practice exercises

  1. Easy:

    Explain the dual-write problem with a concrete example, and show how an outbox table fixes it.

  2. Medium:

    Design a hotel + flight + car booking saga. List each step's compensation, choose choreography or orchestration, and justify the order of steps.

  3. Hard:

    In 2PC, a participant voted yes and the coordinator crashed. Explain exactly why the participant can't decide alone, what it must keep holding, and how running the coordinator on a consensus group changes the picture.

Interview questions

What problem do distributed transactions solve?

Keeping changes atomic and consistent when a single logical operation spans multiple databases or services, so you don't end up with some steps applied and others not.

How does two-phase commit work?

A coordinator asks all participants to prepare; each durably prepares and votes yes or no. If all vote yes, the coordinator logs commit and tells everyone to commit; otherwise it tells everyone to abort.

Why is 2PC called a blocking protocol?

A participant that voted yes can't decide unilaterally. If the coordinator fails before delivering the decision, the participant stays in doubt, holding locks, until the coordinator recovers.

What is a saga?

A sequence of local transactions, each with a compensating action. If a step fails, the compensations for completed steps run in reverse order to semantically undo the work.

Choreography vs orchestration for sagas?

Choreography: services react to each other's events, with no central controller; loosely coupled but the flow is implicit and hard to trace. Orchestration: a central orchestrator commands each step and tracks state; explicit, easier to monitor and change, but adds a coordinating component.

What isolation problems do sagas have and how do you mitigate them?

Intermediate states are visible to other transactions, causing lost updates, dirty reads or overselling. Mitigations: semantic locks (PENDING status), commutative updates, re-reading values before acting, and ordering steps so non-compensatable steps come last.

What is the transactional outbox pattern?

Writing an event into an outbox table in the same local transaction as the business change, then having a relay publish outbox rows to a broker. The event exists if and only if the change committed; delivery is at-least-once.

What is change data capture?

Streaming committed changes from a database's replication log (WAL, binlog) as events, in commit order, without changing application code. Debezium is a common implementation.

Your outbox relay can publish the same event twice. How do you make the system correct?

Give each event a unique id and make consumers idempotent: record processed ids in the same transaction as their own state change, or use naturally idempotent operations like upserts with version checks.

When would you accept 2PC in a modern design?

When participants are few, under one operational control, and need atomicity, typically inside a distributed database (e.g. Spanner or CockroachDB committing across ranges) where the coordinator is itself replicated by consensus, so the blocking problem is mitigated.