Skip to content

Part 4 · Blueprint 18

Distributed Transactions: 2PC vs. Saga Orchestration

14 min reading · Sources · Editorial review pending

Independent local commits do not create one atomic cross-service transaction.

More
20px
Reading list
Page details

Published date · Last edited:

Draft edition. Editorial review and supplementary reading recommendations are still being completed.

Format: Architecture walkthrough. Prerequisites: the beginner bootcamp. Chapter prerequisites: Idempotency Keys & Distributed Retries, Distributed Consensus: Raft & Multi-Paxos.

Sixty-second mental model

Problem: Independent local commits do not create one atomic cross-service transaction.

Use: Choose coordination or compensation from the invariant that must survive.

Design boundary: Separate atomic commitment from business compensation. Two-phase commit coordinates a transaction decision under its recovery model; a saga records a sequence of local effects and compensations that may remain externally visible.

Layer 1 · Intuition

Hypothetical scenario: Northwind is designing distributed transactions. Maya represents product requirements, Dev implementation and Priya reliability. The team must agree what one transition means and which component owns the workflow invariant.

Think of several reservations with explicit confirmation and cancellation. Separate the requester from workflow invariant, then identify the retained evidence needed after failure.

Authority
The entitled state owner.
Invariant
A rule preserved across concurrency and failures.
Atomicity
The all-or-nothing visibility or effect of a defined operation unit. Analogy: A package exchange that completes together or is canceled.
Outbox
A durable record of pending publication written atomically with application state in one transaction. Analogy: An outgoing tray filled at the same time as the official ledger.
Saga
A multi-step workflow using local transactions and defined compensating actions for failures. Analogy: Several reservations coordinated with explicit cancellation actions.
Transaction
A group of operations governed by a commit or rollback boundary. Analogy: A coordinated exchange accepted as one unit.

Architecture and worked reasoning

Design boundary: Separate atomic commitment from business compensation. Two-phase commit coordinates a transaction decision under its recovery model; a saga records a sequence of local effects and compensations that may remain externally visible.

Responsibilities on the request path

Distributed transactions: responsibilities and request directionSeparate atomic commitment from business compensation. Two-phase commit coordinates a transaction decision under its recovery model; a saga records a sequence of local effects and compensations that may remain externally visible.Order intentInventory holdPayment attemptWorkflow journal
Separate atomic commitment from business compensation. Two-phase commit coordinates a transaction decision under its recovery model; a saga records a sequence of local effects and compensations that may remain externally visible.

Workload and limiting resource

Hypothetical stay checkout reserves stock for 10 minutes and payment authorization takes up to 2 minutes in the chosen policy. Eight minutes remain for later work, but that arithmetic alone does not make booking atomic. If 50 checkouts/s hold inventory for 120 seconds on average, a steady-state estimate is 50 × 120 = 6,000 active holds, assuming stable arrivals and durations.

Keep the units attached to each intermediate result. The assumptions above describe a hypothetical exercise, not observed vendor capacity. A real capacity decision also needs a measured service curve, skew, recovery traffic and an explicit admission policy for overload.

Mutation or publication path

Distributed transactions: mutation boundaryPersist the workflow and identities. Then: Acquire reversible commitments in a declared order. Then: Finalize or compensate from recorded outcomes rather than assumptions about timeouts.Step 1
Persist the workflow and identities.
Step 2
Acquire reversible commitments in a declared order.
Step 3
Finalize or compensate from recorded outcomes rather than assumptions about timeouts.
Persist the workflow and identities. Then: Acquire reversible commitments in a declared order. Then: Finalize or compensate from recorded outcomes rather than assumptions about timeouts.
  1. Persist the workflow and identities.
  2. Acquire reversible commitments in a declared order.
  3. Finalize or compensate from recorded outcomes rather than assumptions about timeouts.

Observation and recovery path

Distributed transactions: observation boundaryRead the workflow state and participating evidence. Then: Expose pending/uncertain outcomes honestly. Then: Reconcile stalled steps and failed compensation.Step 1
Read the workflow state and participating evidence.
Step 2
Expose pending/uncertain outcomes honestly.
Step 3
Reconcile stalled steps and failed compensation.
Read the workflow state and participating evidence. Then: Expose pending/uncertain outcomes honestly. Then: Reconcile stalled steps and failed compensation.
  1. Read the workflow state and participating evidence.
  2. Expose pending/uncertain outcomes honestly.
  3. Reconcile stalled steps and failed compensation.

Failure that changes the decision

Hypothetical scenario: Payment succeeds while booking confirmation is lost. Retrying with a new identity can charge twice; compensation itself can fail and needs durable retry/reconciliation.

Attempt this decision before reading the explanation

Is refunding a charge the same as rolling back a database transaction?

No. The charge and refund may both be visible, incur costs and have different timing or legal consequences. Define compensable actions and irreversible boundaries explicitly.

Supporting mechanism analysis

Hypothetical scenario: Northwind. Maya represents product, Dev implementation and Priya reliability. The following workflow develops the underlying mechanism.

In short. Name compensation and reconciliation states explicitly. Distinguish prepared transactions from compensatable steps.

Hypothetical scenario. A marketplace reserves an item and then asks a separate payment service to charge the buyer. The payment response is lost. Releasing the item immediately can conflict with a payment that actually succeeded; charging again can repeat the effect. The workflow needs an explicit uncertain state.

A local transaction gives a commit boundary within a particular transactional resource. A business workflow can cross several resources, each with its own authority and failure behavior. Distributed atomic commit and a compensating workflow offer different contracts for that boundary.

Calling two services in order does not create one transaction. After the first succeeds, the second can fail, time out or become unavailable. The first effect may already be visible to other operations. A retry or a rollback function in the caller cannot automatically restore the world as though nothing happened.

Even a local transaction should cover the actual business invariant. If inventory and reservation records can safely share one authoritative store, that may be simpler than dividing them into services and reconstructing their atomicity over a network.

Identify irreversible effects early. An email cannot be made unseen, a shipment cannot always be recalled and a refund is a new financial action with its own timing and failure modes. Describing every corrective step as rollback hides the consequences users can already observe.

In two-phase commit, participating resources first prepare to follow a final commit or abort decision. A prepared participant cannot independently assume abort merely because the coordinator is temporarily unreachable. The decision and recovery protocol determine what happens next.

A saga-style workflow instead commits local steps and records the next action or compensation. It must define intermediate states, concurrent interactions, retries, deadlines and unresolved cases. It does not provide the same isolation as one transaction across all steps.

PostgreSQL 17's PREPARE TRANSACTION reference describes prepared transactions intended for an external transaction manager and warns about leaving them unresolved. The two-phase transaction documentation describes their durable state. A database exposing this mechanism does not mean an arbitrary external provider participates in it.

Northwind wants to reserve inventory and charge a card, but the two state changes belong to different authorities. A local Postgres transaction can protect related rows inside one database boundary. Two-phase commit asks participating resource managers to prepare before a final commit decision. A saga instead accepts intermediate business states and records steps that require completion, compensation or reconciliation.

Prepared is not equivalent to committed. A prepared participant retains the state needed to honor the eventual decision, and unresolved prepared transactions need an external manager and recovery procedure. PostgreSQL's documentation warns that this machinery is intended for such managers. Exposing a prepared state without a durable decision path can leave resources tied up after the initiating process disappears.

In a hypothetical saga, one hundred orders each reserve two items before requesting payment. If ten payment outcomes remain unknown, 10 × 2 = 20 items are associated with unresolved outcomes. That is not evidence of ten declined payments. A policy that releases all twenty items immediately could conflict with later confirmed payments. Define expiry, reconciliation and any corrective action against the original order identity.

Compensation is a new business action, not a reversal of time. A refund can have its own authorization, costs and uncertain result. If its response disappears, repeat reconciliation using the same corrective-operation identity rather than inventing another refund. Start by asking whether the invariant can remain inside one database transaction. Move it across services only when the ownership and workload benefits justify the additional intermediate states and operational burden.

Hypothetical scenario. Choose 100 purchase workflows. Sixty complete both reservation and payment. Twenty fail payment with a definite rejection and require reservation release. Twenty have an uncertain payment outcome and remain pending. The accounting is 60 + 20 + 20 = 100; pending must not be counted as either confirmed success or definite failure.

If each workflow reserves one item, the uncertain group holds 20 items until reconciliation or a declared expiry transition. Releasing them after a chosen five-minute timer is a business rule that must account for payments confirmed after that timer. A timer does not establish that a provider action never occurred.

Suppose reconciliation can inspect ten pending operations per minute while five new uncertain operations arrive per minute. With a backlog of 20, the net drain is 10 − 5 = 5 operations per minute, giving 20 ÷ 5 = 4 minutes under constant rates and successful inspections. Inspections that remain inconclusive do not count as resolved operations.

For a prepared-resource example, choose 30 prepared transactions each holding two distinct row locks. That is 30 × 2 = 60 held locks under the chosen model. Their impact depends on which rows other transactions need, not just the total. One frequently requested row can cause more disruption than many unused rows.

These numbers expose operational obligations rather than asserting a universal throughput or timeout. A workflow diagram without pending counts, recovery capacity and unresolved-state ownership omits a substantial part of the design.

The primary reference establishes this concrete distinction: prepared PostgreSQL transactions require an external manager and unresolved-state handling.

The business may accept a temporary reservation followed by release if payment fails. It may not accept a shipment before payment authority is established. Define the allowed states and which transitions make irreversible commitments. Sometimes reordering steps or using a provider-supported authorization stage reduces exposure.

Compensations can fail and require retries with their own operation identities. They may also race with a late success. Record which decision the workflow has made, which effects are confirmed, and how late evidence is interpreted. Do not allow two independent recovery workers to issue incompatible corrective actions.

Atomic commit can be appropriate when all participants support the chosen protocol and the application requires its contract. It also introduces prepared-state recovery obligations. Replicating the coordinator can protect decision state, but cannot make an unreachable participant receive a decision immediately.

Layer 3 · Internals

Trade-offs and limits

ApproachProvidesRequires
Coordinated commitCan enforce an atomic decision across participating resources under a defined protocol.Locks, blocking and recovery responsibilities depend on the implementation.
Compensating workflowAllows independent local transactions with explicit repair steps.Intermediate states are visible and compensation is not a universal inverse.

Recovery decision

Hypothetical scenario: Payment succeeds while booking confirmation is lost. Retrying with a new identity can charge twice; compensation itself can fail and needs durable retry/reconciliation.

No. The charge and refund may both be visible, incur costs and have different timing or legal consequences. Define compensable actions and irreversible boundaries explicitly.

Write your design before revealing the review

Is refunding a charge the same as rolling back a database transaction?

Evidence you can explain in your own design

Drafts and self-review are stored only in this browser. They are separate from reading completion.

Compare your decision

No. The charge and refund may both be visible, incur costs and have different timing or legal consequences. Define compensable actions and irreversible boundaries explicitly.

Payment succeeds while booking confirmation is lost. Retrying with a new identity can charge twice; compensation itself can fail and needs durable retry/reconciliation.

Check your understanding

Is refunding a charge the same as rolling back a database transaction?

No. The charge and refund may both be visible, incur costs and have different timing or legal consequences. Define compensable actions and irreversible boundaries explicitly.

How would you recover from this failure: Payment succeeds while booking confirmation is lost. Retrying with a new identity can charge twice; compensation itself can fail and needs durable retry/reconciliation.

Start with the exact boundary that failed. Persist the workflow and identities. Acquire reversible commitments in a declared order. Finalize or compensate from recorded outcomes rather than assumptions about timeouts. Then recover evidence through the observation path: Read the workflow state and participating evidence. Expose pending/uncertain outcomes honestly. Reconcile stalled steps and failed compensation. Preserve the distinction between a confirmed state change and an unavailable response.

Which assumption in the worked calculation would a burst or concentrated tenant invalidate first?

Hypothetical stay checkout reserves stock for 10 minutes and payment authorization takes up to 2 minutes in the chosen policy. Eight minutes remain for later work, but that arithmetic alone does not make booking atomic. If 50 checkouts/s hold inventory for 120 seconds on average, a steady-state estimate is 50 × 120 = 6,000 active holds, assuming stable arrivals and durations. Recompute the affected resource rather than multiplying unrelated storage and network budgets by the same factor. Separate atomic commitment from business compensation. Two-phase commit coordinates a transaction decision under its recovery model; a saga records a sequence of local effects and compensations that may remain externally visible.

Which component in this topology could be removed from a smaller first deployment?

Order intent, Inventory hold, Payment attempt, Workflow journal name responsibilities, not a requirement for separate processes. Co-locate responsibilities when their transaction, trust and capacity boundaries permit it. Persist the workflow and identities.

What evidence must a caller have before relying on the observation path?

Read the workflow state and participating evidence. Expose pending/uncertain outcomes honestly. Reconcile stalled steps and failed compensation. No. The charge and refund may both be visible, incur costs and have different timing or legal consequences. Define compensable actions and irreversible boundaries explicitly.

45-minute interview rubric

  1. 00–05: scope transition and workflow invariant.
  2. 05–12: identify the limiting resource and derive the domain workload above, retaining units and assumptions.
  3. 12–28: draw workflow invariant, numbered writes and reads.
  4. 28–40: challenge recovery: Choose coordination or compensation from the invariant that must survive.
  5. 40–45: defend workflow_id placement, observations and remaining assumptions.

Go deeper

Decision log

Choose coordination or compensation from the invariant that must survive.

Preserve transition identity and workflow invariant ownership.

Revisit changed workload, observations or recovery objectives.