--- title: "Saga Pattern vs Two-Phase Commit: Handling Transactions Across Services" author: "Samod Alex" published: "2026-11-19T10:18:44.654Z" updated: "2026-11-19T10:18:44.654Z" url: "https://zyvop.com/saga-pattern-vs-two-phase-commit-handling-transactions-across-services-m1cei" canonical: "https://zyvop.com/saga-pattern-vs-two-phase-commit-handling-transactions-across-services-m1cei" tags: ["two-phase commit","saga pattern","distributed transactions","node.js","Microservices"] --- # Saga Pattern vs Two-Phase Commit: Handling Transactions Across Services How to keep orders, payments, and shipments consistent when each service owns its database, and why most teams reach for sagas over two-phase commit. ![Cover image]() When your whole app lives in one database, transactions feel like magic. You wrap a few statements in `BEGIN` and `COMMIT`, and either everything happens or nothing does. Then you split the app into services, each with its own database, and that safety net disappears. Suddenly "place an order" touches three systems that can't share a transaction. This post compares the two classic answers: two-phase commit and the saga pattern. We'll use one example throughout, an order, a payment, and a shipment, and include a Node.js sketch you can adapt. ## The problem: one action, three databases A customer clicks "Place order". Behind the scenes: 1. The **Order service** records the order. 2. The **Payment service** charges the customer's card. 3. The **Shipping service** creates a shipment. Each service owns its own database, so there's no single `BEGIN ... COMMIT` that covers all three. Now imagine the payment succeeds and the Shipping service is down. The customer has been charged for an order that will never ship. Or the order is saved, but the payment call times out, and you don't know whether the card was charged. These are partial failures. In a distributed system they're normal, not edge cases, so you need a strategy for them. ## Option 1: Two-phase commit (2PC) Two-phase commit is the textbook way to make several databases agree on one outcome. A **coordinator** drives the process in two phases. **Phase 1: prepare.** The coordinator asks every participant, "Can you commit this?" Each one does the work, writes it durably, locks the affected rows, and votes yes or no. **Phase 2: commit or abort.** If every participant voted yes, the coordinator tells them all to commit. If any voted no, or didn't answer, it tells them all to roll back. In our example, the coordinator asks the Order, Payment, and Shipping databases to prepare. Only when all three say yes does it tell them to commit. ```mermaid sequenceDiagram participant C as Coordinator participant O as Order DB participant P as Payment DB participant S as Shipping DB Note over C,S: Phase 1: prepare (locks are held) C->>O: Prepare C->>P: Prepare C->>S: Prepare O-->>C: Vote yes P-->>C: Vote yes S-->>C: Vote yes Note over C,S: Phase 2: commit C->>O: Commit C->>P: Commit C->>S: Commit ``` From the outside it looks like one atomic transaction. You even get strong isolation, because locks are held until the end. ### Where 2PC hurts On paper this is ideal. In a microservice system it runs into trouble: - **Locks are held across network calls.** Between "prepare" and "commit", rows stay locked. Under load that hurts throughput and invites deadlocks. - **The coordinator is a risk.** If it crashes after participants voted yes, they must keep their locks until it recovers, or until someone resolves the in-doubt transaction by hand. - **Availability multiplies down.** Every participant must be up to commit. If each of three services is available 99.9% of the time, the combined transaction is available about 99.7% of the time. - **Not everyone can participate.** 2PC needs each participant to support a prepare step, usually through the XA standard. Many databases don't, and third-party APIs such as payment gateways and shipping carriers won't. - **It couples services tightly.** Every service must be reachable and responsive for every transaction, which undermines the independence you wanted in the first place. The payment gateway point settles it for our example. You can't ask your card processor to "prepare" a charge and wait on a vote from your Shipping database. ### Where 2PC still makes sense 2PC isn't obsolete. It works well when participants are few, trusted, and close together, such as inside a single database cluster. PostgreSQL has `PREPARE TRANSACTION`, MySQL supports XA, and distributed databases like Google Spanner use 2PC internally to commit across partitions. The trouble is specifically using it across independently owned services. ## Option 2: The saga pattern A saga takes the opposite approach. Instead of one big atomic transaction, it breaks the work into a sequence of **local transactions**, one per service. Each commits on its own, immediately. If a later step fails, you can't roll back the earlier ones, because they're already committed. So each step gets a **compensating transaction** that semantically undoes it. The idea comes from a 1987 paper by Hector Garcia-Molina and Kenneth Salem, originally about long-running database transactions. It fits microservices well. For our flow: | Step | Local transaction | Compensation | | --- | --- | --- | | 1 | Order service: create order as `PENDING` | Mark the order `CANCELLED` | | 2 | Payment service: charge the customer | Refund the payment | | 3 | Shipping service: create the shipment | Cancel the shipment | | 4 | Order service: mark the order `CONFIRMED` | None needed | When something fails, you run the compensations for the completed steps in reverse order. Solid arrows are the happy path, and the dotted arrow is what happens when shipping fails: ```mermaid flowchart LR A["Create order (PENDING)"] --> B["Charge payment"] B --> C["Create shipment"] C --> D["Order CONFIRMED"] C -.->|shipping fails| E["Refund payment"] E --> F["Order CANCELLED"] ``` ### Choreography vs orchestration There are two ways to coordinate a saga. **Choreography** has no central controller. Each service listens for events and reacts. The Order service publishes `OrderCreated`, Payment hears it and publishes `PaymentSucceeded` or `PaymentFailed`, and Shipping reacts to `PaymentSucceeded`. Events travel through a message broker, which is left out of the diagram for clarity. ```mermaid flowchart LR O["Order service"] -->|OrderCreated| P["Payment service"] P -->|PaymentSucceeded| S["Shipping service"] S -->|ShipmentCreated| O ``` It's loosely coupled and simple for two or three steps. The downside is that the flow is scattered across services, which makes it hard to see and debug as it grows. **Orchestration** uses a central orchestrator that tells each service what to do and tracks progress. The whole flow lives in one place, so it's easier to reason about, test, and monitor. Here's the shipping failure from our example, as the orchestrator sees it: ```mermaid sequenceDiagram participant Orc as Orchestrator participant P as Payment service participant S as Shipping service Orc->>P: Charge payment P-->>Orc: Charged Orc->>S: Create shipment S-->>Orc: Failed Orc->>P: Refund payment P-->>Orc: Refunded Note over Orc: Mark order CANCELLED ``` The cost is one more component, and the risk of stuffing too much business logic into it. A reasonable rule of thumb: choreography for short sagas with few participants, orchestration once you have more than three or four steps, branching, or a need for visibility. Workflow engines such as Temporal, AWS Step Functions, and Camunda handle the persistence and retries for you. ### A simple orchestrator in Node.js Here's a sketch of an orchestrator for our flow. Each step has a `run` and a `compensate` function: ```javascript const steps = [ { name: "charge-payment", run: (ctx) => payments.charge({ orderId: ctx.orderId, amount: ctx.amount, idempotencyKey: `charge-${ctx.orderId}`, }), compensate: (ctx) => payments.refund({ orderId: ctx.orderId, idempotencyKey: `refund-${ctx.orderId}`, }), }, { name: "create-shipment", run: (ctx) => shipping.createShipment({ orderId: ctx.orderId, address: ctx.address, idempotencyKey: `ship-${ctx.orderId}`, }), compensate: (ctx) => shipping.cancelShipment({ orderId: ctx.orderId, idempotencyKey: `cancel-ship-${ctx.orderId}`, }), }, ]; async function placeOrder(ctx) { await orders.create({ id: ctx.orderId, status: "PENDING" }); const attempted = []; try { for (const step of steps) { attempted.push(step); // record first: a timed-out step may still have applied await step.run(ctx); } } catch (err) { for (const step of [...attempted].reverse()) { // compensate() must be safe to call even if run() never applied await retry(() => step.compensate(ctx)); } await orders.setStatus(ctx.orderId, "CANCELLED"); return; } await retry(() => orders.setStatus(ctx.orderId, "CONFIRMED")); } ``` `retry` stands in for a helper with exponential backoff, and `payments`, `shipping`, and `orders` are clients for your services. This is a sketch, not production code. In production the saga's progress must be stored durably so it survives a crash, and each call needs timeouts. ## What makes sagas work in production The orchestrator above is the easy part. These four things decide whether a saga holds up under real failures. ### 1\. Reliable messaging with the outbox pattern Updating your database and publishing an event to a broker are two separate writes. If the process crashes between them, the order exists but no event is ever sent. The fix is the **transactional outbox**. Write the event to an `outbox` table in the same local transaction as the business change: ```javascript import { randomUUID } from "node:crypto"; await knex.transaction(async (trx) => { await trx("orders").insert({ id: orderId, status: "PENDING", total }); await trx("outbox").insert({ id: randomUUID(), topic: "order.created", payload: JSON.stringify({ orderId, total }), }); }); ``` A separate relay process reads unsent rows, publishes them to the broker, and marks them as sent. It may publish a message twice, which brings us to the next point. ### 2\. Idempotent steps and consumers Brokers typically deliver messages at least once, and retries are part of the design. Charging a card twice because a message was redelivered is not acceptable. On the calling side, pass an idempotency key, such as one derived from the order ID, so repeated calls have the same effect as one. On the receiving side, record processed message IDs in a table with a unique constraint, in the same transaction as the work. A duplicate then fails the insert and gets skipped. ### 3\. Compensations that tolerate ambiguity A timeout doesn't tell you whether a step was applied. The charge may have gone through even though the response never arrived. That's why the orchestrator above records a step as attempted before running it. It's also why compensations must be safe to run when there's nothing to undo: "refund the payment for order 42, if one exists". Compensations also need retrying until they succeed. A refund that fails once and is forgotten leaves you right back where you started. ### 4\. Durable saga state The orchestrator needs to know which steps are done, so that after a crash it can resume or compensate. Store that state in a database, or use a workflow engine that does it for you. ## Sagas don't give you isolation An ACID transaction gives you atomicity, consistency, isolation, and durability. A saga gives you atomicity (through compensation), consistency, and durability, but not isolation. Other requests can see the in-between state. A customer's order page might show a paid order a moment before shipping fails and the payment is refunded. Here's the life cycle of an order in our example: ```mermaid stateDiagram-v2 [*] --> PENDING PENDING --> CONFIRMED: all steps succeed PENDING --> CANCELLED: a step fails, compensations run CONFIRMED --> [*] CANCELLED --> [*] ``` Ways to cope: - **Use explicit states.** Statuses like `PENDING`, `CONFIRMED`, and `CANCELLED` make it clear that an order is mid-flight. Show "Processing" in the UI, not "Order placed". - **Add semantic locks.** A flag that says "this record is mid-saga" lets other operations refuse or wait. For example, don't allow edits to a `PENDING` order. - **Order steps wisely.** Put the hardest-to-undo steps late. On that last point, a common refinement is to **authorize** the payment first (hold the funds), create the shipment, and only then **capture** the payment. Voiding a hold is much cleaner than refunding a charge. The capture then comes last, after the shipment, and it rarely fails once the funds are held. Holds do expire, so capture soon after. Some things can't be undone at all. An email that went out or a package that left the warehouse can only be followed by a new action, like an apology email or a return label. ## Side by side | | Two-phase commit | Saga | | --- | --- | --- | | Atomicity | All-or-nothing | Eventually all-or-nothing, via compensation | | Isolation | Strong, locks held | None by default, handled in app code | | Latency | Higher, waits for every participant | Each step commits quickly | | Availability | All participants must be up | Steps can be retried later | | Coupling | Tight | Looser, via events or an orchestrator | | External APIs | Rarely possible | Works fine | | Where the complexity lives | In the protocol and infrastructure | In your application code | ## Which one should you use? Use **2PC** when: - Participants sit inside one trusted boundary, such as a single database cluster. - Every participant supports XA or an equivalent prepare step. - Transactions are short and you genuinely need strong isolation. Use a **saga** when: - The flow crosses service boundaries or calls external APIs. - It can take seconds, minutes, or longer. - You can tolerate temporary inconsistency and handle it in your design. Before choosing either, question the boundary. If two pieces of data must always change together atomically, maybe they belong in the same service and the same database. The best distributed transaction is often the one you design away. ## Key takeaways - A single database transaction can't span services that own separate databases, so partial failures need a deliberate strategy. - 2PC gives atomicity and isolation, but it holds locks across network calls, can block if the coordinator fails, and doesn't work with most third-party APIs. - A saga replaces one atomic transaction with local transactions plus compensations, trading isolation for availability and loose coupling. - Choreography works for short flows. Orchestration is easier to follow once the flow grows. - Production sagas depend on the outbox pattern, idempotent steps, compensations that tolerate ambiguity, and durable state. - Handle the lack of isolation with explicit states, semantic locks, and sensible step ordering. ## Further reading - Hector Garcia-Molina and Kenneth Salem, ["Sagas"]() (SIGMOD, 1987). The original paper, also available as a [Princeton tech report](). - Pat Helland, ["Life Beyond Distributed Transactions: An Apostate's Opinion"](). A classic argument for avoiding distributed transactions, first published in 2007. - Chris Richardson, ["Pattern: Saga"]() and ["Pattern: Transactional outbox"]() on microservices.io. Both are covered in more depth in his book, _Microservices Patterns_. - Microsoft Azure Architecture Center, ["Saga distributed transactions pattern"](). Includes the compensable, pivot, and retryable step model. - Stripe docs, ["Idempotent requests"](). A real-world example of idempotency keys for safe retries. - PostgreSQL docs, `PREPARE TRANSACTION`. What a database-level prepare step looks like. The docs note it's meant for transaction managers, not application code. - Martin Kleppmann and Chris Riccomini, [_Designing Data-Intensive Applications_, 2nd edition]() (O'Reilly, 2026). Covers transactions and distributed systems in depth.