Distributed Transactions

Keeping a multi-step action correct when the steps live in different services or databases.

Distributed transactions in 30 seconds

  • Problem: one business action spans several services/databases, and you need them to agree — all succeed or all undo.
  • 2PC (two-phase commit): a coordinator asks everyone to 'prepare', then 'commit'. Strong, but it locks resources and blocks if the coordinator dies.
  • Saga: break it into local steps, each with a compensating undo; on failure, run the undos backward. Looser, more available, eventually consistent.
  • Most modern systems prefer sagas over 2PC across microservices.
  • Make every step idempotent — retries and redeliveries are guaranteed.
  • Best move: avoid the need — keep data that changes together in one service/database when you can.

The travel agent with three phone calls

Imagine booking a holiday through an old-school travel agent. In one go they must charge your card, reserve a flight seat, and book a hotel room — three separate businesses, three separate phone lines. If the card goes through and the flight is reserved but the hotel turns out to be fully booked, the agent can't just shrug and keep your money. They have to phone back and undo: cancel the flight, refund the card, so you end up as if nothing happened. There's no single magic 'cancel everything' button — the agent walks back each step by hand.

On a single database, that walk-back is automatic: one transaction wraps every step and a ROLLBACK erases them all at once. The moment your steps live in different systems, that shared undo button disappears — and you're back to being the travel agent making undo calls one at a time. Distributed transactions are the disciplined ways to do exactly that.

The problem, told simply

Booking a trip in one tap: charge the card, reserve the flight, book the hotel. Three different systems, and they must agree. If the card is charged but the hotel is full, you can't just leave the money gone — you have to give it back. On a single database, a transaction handles this with one neat commit-or-rollback. Spread those steps across services and there's no shared 'undo' button. That gap is what distributed transactions try to fill.

On one database, BEGIN...COMMIT makes every step atomic. Across services, this wrapper is gone.

Why the single-database trick doesn't carry over

  • Each service owns its own database — no shared transaction to wrap them all.
  • The network can fail between steps, leaving you half-done.
  • A step can succeed but its 'success' message gets lost, so you don't even know where you are.
  • You can't hold a lock across many services for long without grinding everything to a halt.

So the goal shifts. You can't get the instant all-or-nothing of a local transaction across services. The best you can realistically achieve is: either every step eventually succeeds, or every completed step eventually gets undone — with the system passing through some visible in-between states along the way. The two classic approaches, 2PC and sagas, are two very different bargains for reaching that goal.

Approach 1 — Two-phase commit (2PC)

2PC appoints a coordinator and does it in two rounds:

  • Phase 1 — Prepare: the coordinator asks every participant 'can you commit?' Each does the work tentatively, locks what it needs, and replies yes/no.
  • Phase 2 — Commit: if everyone said yes, the coordinator tells all to commit; if anyone said no, it tells all to abort.
The 2PC coordinator's two rounds (pseudocode)
def two_phase_commit(participants):
    # Phase 1 — Prepare: everyone does the work tentatively and locks
    votes = []
    for p in participants:
        votes.append(p.prepare())        # returns YES or NO

    # Phase 2 — decide, then tell everyone the same thing
    if all(v == "YES" for v in votes):
        for p in participants:
            p.commit()                   # release locks, make it real
        return "COMMITTED"
    else:
        for p in participants:
            p.abort()                    # anyone said NO -> all undo
        return "ABORTED"
    # Danger: if the coordinator crashes here, participants are stuck
    # holding locks, unsure whether to commit or abort (blocking).

The gap 2PC can't fill: it blocks

Picture the exact moment it goes wrong. All three participants have said 'yes, prepared' and are holding their locks, waiting for the coordinator's final word. The coordinator crashes. Now each participant is frozen: it can't commit (maybe someone else said no and it just didn't hear), and it can't abort (maybe everyone said yes and the decision was to commit). It can only wait, holding its locks, blocking every other transaction that needs those rows — possibly for minutes until the coordinator is restarted. This 'blocking on coordinator failure' is the fatal flaw that pushes microservice architectures toward sagas instead.

Approach 2 — Sagas

A saga gives up on one atomic moment and instead chains local transactions, each with a matching compensating action that undoes it:

  • Do step 1 (charge card). It commits locally and emits an event.
  • Do step 2 (reserve flight). Commits, emits an event.
  • Step 3 (book hotel) fails — no rooms.
  • Run the compensations backward: cancel the flight, refund the card. The system ends in a consistent state, just not instantly.
A saga: run local steps, compensate backward on failure (javascript)
// Each step is a local commit paired with its undo
const steps = [
  { do: chargeCard,     undo: refundCard },
  { do: reserveFlight,  undo: cancelFlight },
  { do: bookHotel,      undo: cancelHotel },
];

async function runSaga(ctx) {
  const done = [];
  try {
    for (const step of steps) {
      await step.do(ctx);   // make each call idempotent — retries happen
      done.push(step);
    }
  } catch (err) {
    // A step failed: unwind the ones that succeeded, in reverse
    for (const step of done.reverse()) {
      await step.undo(ctx);
    }
    throw err;
  }
}
2PC locks and commits together; a saga undoes step-by-step on failure.

Why every step must be idempotent

A saga leans on messages and retries, and messages get redelivered. If a 'charge card' step runs twice because an ack was lost, you've double-charged the customer — the saga made things worse. The fix is idempotency: design each step so running it twice has the same effect as running it once. The usual trick is a stable key (an order ID, a request ID) that the step checks before acting: 'have I already done this exact operation? Then do nothing and report success.'

An idempotent step keyed by a stable request id (python)
def charge_card(ctx):
    key = ctx.saga_id + ":charge"      # stable, derived from the saga
    if payments.already_applied(key):  # did a retry already do this?
        return payments.result_for(key)   # yes -> return the SAME result
    result = gateway.charge(ctx.card, ctx.amount)
    payments.record(key, result)       # remember it, atomically with the charge
    return result
# A lost ack causes a retry, but the key makes the second attempt a no-op.
# Same idea for the compensations: refunding twice must not double-refund.

Orchestration vs choreography

Sagas come in two flavors. In orchestration, one central coordinator service calls each step in turn and triggers compensations on failure — easy to follow and debug, but it's a component you must build and keep alive. In choreography, there's no central brain: each service listens for events and emits its own, so the saga emerges from the chain of reactions — more decoupled, but the overall flow is scattered across services and harder to trace. Small sagas often start choreographed; complex ones usually grow into an orchestrator.

OrchestrationChoreography
Control flowOne coordinator drives every stepEach service reacts to events
VisibilityEasy — the flow lives in one placeScattered across services; harder to trace
CouplingServices coupled to the orchestratorLoosely coupled via events
Best forComplex sagas, many steps, clear ownershipSimple flows, few steps, high autonomy

2PC vs Saga, side by side

2PCSaga
ConsistencyStrong, immediateEventual (converges after compensations)
AvailabilityBlocks if coordinator diesStays available; no global lock
ComplexitySimple idea, fragile in practiceYou must design every compensating action
Best forA few nodes in one trusted clusterMicroservices spanning many services

Distributed transactions are really about one uncomfortable truth of microservices: the moment you split the database, the tidy all-or-nothing commit you took for granted disappears, and you have to rebuild that guarantee by hand.

Why it matters

  • It's how a multi-step business action — pay, reserve, confirm — stays correct when each step lives in a different service.
  • It decides whether a half-finished operation quietly leaves the system in a broken state or cleanly unwinds itself.
  • It forces an honest conversation about your service boundaries: what truly belongs together versus what you split apart.

If ignored

  • Partial failures: the card is charged but the order never books, and money vanishes with no automatic undo.
  • A crashed 2PC coordinator leaves participants holding locks, frozen between commit and abort.
  • Duplicate side effects when a step is retried without being idempotent — a second charge, a double shipment.

Where it fits

  • Sits in the orchestration layer that coordinates a business workflow across several services.
  • Leans on an event bus or message queue to carry steps and compensations reliably between services.
  • Is the thing you try hardest to design away — ideally by keeping co-changing data in one service.

Related topics

  • ACID transactions: the single-database guarantee this pattern tries to recreate across services
  • Idempotency: every saga step must be safe to retry, or compensations go wrong
  • Message queues: the reliable pipe that carries saga steps and their undos
  • Consensus: the lower-level agreement a 2PC-style coordinator depends on

Interview lens

Questions it unlocks

  • How do you keep a multi-service booking consistent?
  • Why do microservices usually avoid two-phase commit?
  • What's a saga, and what does 'compensating transaction' mean?

60-second answer

When one action spans several services, I first ask whether the data should live together in one service so a plain local transaction suffices. If the boundaries are real, I prefer a saga over 2PC: break the action into local steps, each with a compensating undo, and run the undos backward on failure. That stays available and avoids the blocking problem where a crashed 2PC coordinator leaves participants holding locks. I make every step idempotent because retries are inevitable, I decide between an orchestrator and event choreography for driving it, and I treat 2PC as fine only inside a single trusted cluster.

Common traps

  • Using 2PC across microservices and hitting the coordinator-crash blocking problem.
  • Forgetting to design a compensating action for each saga step.
  • Distributing a transaction that should have been one service in the first place.

Search topics

↑↓ to move · Enter to open · Esc to close