1. Home
  2. Blog
  3. Custom Software

Custom Software

What Is the Saga Pattern and Distributed Transactions? Compensation, Step Order and Failure Math Guide

What is the saga pattern? Run a distributed transaction across services consistently with compensating actions: types, step order, idempotency and failure math.

Contents 14 sections
  1. What Is the Saga Pattern and a Distributed Transaction?
  2. Why Is a Single ACID Transaction Not Enough, and Why Is Two-Phase Commit Hard?
  3. Saga Types: Choreography or Orchestration?
  4. What Are the Saga Steps and Compensations in an Order Example?
  5. How Do You Handle Steps That Cannot Be Compensated?
  6. Why Is Idempotency Essential in a Saga?
  7. How Do You Handle Timeouts and Stuck Sagas?
  8. How Are Interim States Shown to Users and Other Operations?
  9. How Many Half-Done Records Remain Without a Saga? The Failure Math
  10. How Is Saga State Monitored and Tested?
  11. What Is the Payback of Building a Saga?
  12. How Do You Run a Saga Project?
  13. Custom Software and Integration with İnovabil
  14. Frequently Asked Questions

When an order arrives, the stock service decrements inventory, the payment service holds the card and the shipping service opens a picking order. If the fourth step fails, what happens to the first three? In a single database you would simply roll back. Across four services with four databases, there is no such command. The saga pattern is a way to run a distributed transaction consistently: each step commits its own local transaction, and if a later step fails, a compensating action undoes the earlier ones.

This guide explains why distributed transactions are hard, where two-phase commit falls short, the choreography and orchestration styles, the steps and compensations in an order example, how to place irreversible steps, idempotency, stuck sagas, the failure math, and monitoring and testing. All example figures are illustrative; they are not measurements of any product or industry.

Key takeawayA saga does not imitate rollback; it replaces rollback with a compensation that makes business sense. A stock reservation is released, a card hold is voided, a picking order is cancelled. So the quality of a saga depends less on its steps than on the correctness of its compensations, the order of its steps and its idempotency.

What Is the Saga Pattern and a Distributed Transaction?

A distributed transaction is any operation whose single business outcome must be written to more than one service or database. A saga splits that work into a series of small local transactions: each step commits in its own database and triggers the next. If a step fails midway, the steps that already committed are corrected in reverse order by compensating transactions.

The important difference is that during a saga the system sits in a "half-done" state for a while. Stock is reserved but payment has not yet been taken. That interim state is designed on purpose, made visible and bounded with timeouts. For how services call each other, see our microservices architecture guide; for how events flow between services, see our event-driven architecture guide. This article is only about keeping a shared operation consistent.

We recommend reading: Our custom software service

Why Is a Single ACID Transaction Not Enough, and Why Is Two-Phase Commit Hard?

A single-database ACID transaction gives an "all or nothing" guarantee, but that guarantee cannot cross a boundary once services own their own data. The classic answer, two-phase commit (2PC), uses a coordinator: first everyone is asked "are you ready?", and if all say yes, a "commit" is sent.

The trouble is that during the prepare phase each participant holds its records locked. If the coordinator crashes at that moment, participants cannot learn the outcome and cannot release their locks. An illustrative calculation: with 120 ms for prepare and 40 ms for the commit round, a record stays locked for 160 ms, so at most 1,000 ÷ 160 = 6.25 operations per second can touch the same record. In a saga, if each step finishes its local transaction in 8 ms and releases the lock, the ceiling for the same record is 1,000 ÷ 8 = 125 operations per second. We covered the effect of lock time on throughput in our concurrency and double-selling guide.

Availability suffers too: in 2PC all four participants must be up. If each is 99.9% available, together they are 0.999⁴ ≈ 99.6%, about 173 minutes of downtime in a 30-day month. In a saga, a step for a down service is retried and the whole system does not stop.

TopicSingle database (ACID)Two-phase commit (2PC)Saga
ScopeOne databaseMultiple databasesMultiple services
ConsistencyImmediate, strictImmediate, strictEventually consistent
Lock durationVery shortAcross all rounds (160 ms in the example)Only the step itself (8 ms in the example)
On failureRollbackDepends on the coordinator; can hangCompensating action

Saga Types: Choreography or Orchestration?

A saga runs in one of two styles. In choreography each service publishes an event and the next service listens and performs its step; there is no central manager. In orchestration a coordinator decides which step runs when and, on failure, starts the compensations in order.

TopicChoreographyOrchestration
Who holds the flow?Spread across eventsOne coordinator
As services growWho listens to whom gets tangledThe coordinator grows, but the flow reads in one place
State visibilityHard; reconstructed from event tracesThe coordinator already holds it
Suitable forSimple flows of 2–3 steps4+ steps, branching and complex compensation

Events must not get lost, so you need messaging infrastructure; we explained the basics in our message queue guide.

What Are the Saga Steps and Compensations in an Order Example?

Example: a dealer portal receives 3,000 orders a day. Each order passes through four steps, and each step's local transaction commits in its own service.

StepServiceForward actionCompensating action
1StockReserve the stockRelease the reservation
2PaymentPlace a hold on the card (authorization)Void the hold
3ShippingOpen a picking and shipping orderCancel the order (if the parcel has not left)
4NotificationSend the customer a confirmation messageNone; a correction message can be sent

A compensation does not have to be the literal reverse of the original action; it is the reverse in business terms. A sent confirmation email "cannot be unsent", but an "your order was cancelled" message counts as compensation. Compensations can fail too, so they must be written so that repeating them does no harm. For the full order lifecycle, see our order management system guide.

How Do You Handle Steps That Cannot Be Compensated?

Not every step can be undone: a sent email, a parcel handed to a carrier, an official document delivered to an outside system do not fit compensation. The solution is to put these steps at the very end of the chain, so reversible steps run first and the irreversible step runs last. If the chain is going to fail, it fails before reaching the irreversible step.

Step typeMeaningExamplePlace in the order
CompensableAn inverse action is definedStock reservation, card hold, order recordAt the start
PivotIf it succeeds, the chain only moves forwardPayment captureIn the middle, the last risky step
RetryableNever fails, only delaysNotification, document deliveryAt the end

In the example, notification comes last because a failure there must not break the chain: if it cannot be sent, it is simply retried. For physical steps such as shipping, define a "last cancellable moment": the shipping order can be cancelled until it is picked in the warehouse, and after the parcel leaves, a return process replaces cancellation. We described error classes and reprocessing in our integration operations guide.

Why Is Idempotency Essential in a Saga?

In a distributed system a message can arrive twice and a reply can be lost; "I did it but you never got my answer" is normal. Without idempotency the same step runs twice: stock is decremented twice, the card is held twice. The fix is a simple rule: every saga gets a unique ID, every step gets a key made of that ID plus the step name, and if a service sees the same key a second time it returns the first result without repeating the work.

The same rule applies to compensation: if "release the reservation" arrives twice, stock must not rise twice. A late forward step for a saga whose compensation has already been processed must also be rejected. For the same problems in webhook and event delivery, see our webhook guide.

How Do You Handle Timeouts and Stuck Sagas?

The sneakiest case is not an error response but silence: a service simply does not answer. Each step needs a written timeout, retry count and wait interval. An illustrative setting: 5 s timeout, at most 3 attempts, waits of 1 s and 2 s between attempts. The worst case for one step is 3 × 5 + (1 + 2) = 18 s, and for four steps 4 × 18 = 72 s.

The stuck-saga threshold must be larger than this worst case; in the example, 120 s. While the median is 3 s, a chain exceeding 120 s is "stuck" and raises an alert. A timed-out step has an unknown outcome: the work may have been done. So query the state first, then decide.

How Are Interim States Shown to Users and Other Operations?

During a saga, the half-done data is visible to other operations. The answer is a semantic lock: the record carries an explicit state meaning "this record is inside a saga". In the example the stock record shows 50 physical units; if three sagas have each reserved 2 units, the reserved quantity is 6 and sellable stock is shown as 50 − 6 = 44. If a saga fails and releases its reservation, sellable stock returns to 50.

Also define a reservation lifetime: in the example, 15 minutes; when it expires, the reservation is released automatically, so a stuck saga never holds stock forever. Reports and screens count interim records separately and do not add them to confirmed revenue.

How Many Half-Done Records Remain Without a Saga? The Failure Math

If each of four steps succeeds 99% of the time, the whole chain succeeds 0.99⁴ ≈ 96.1% of the time; failure is 1 − 0.9606 ≈ 3.94%. At 3,000 orders a day that is 3,000 × 0.0394 ≈ 118 failed chains. Where the failure happens matters: the probability of failing at step k is 0.99ᵏ⁻¹ × 0.01.

Failure pointProbabilityChains per daySteps to compensateCompensations per day
Step 1 (stock)1.00%30.000
Step 2 (payment)0.99%29.7129.7
Step 3 (shipping)0.98%29.4258.8
Step 4 (notification)0.97%29.1387.3
Total3.94%118.2—175.8
Saga failure math: a four-step chain succeeds 96.1% of the time, about 118 failed chains per day, and without a saga about 88 half-done orders and 176 orphan records
Even with each of four steps at 99%, about 118 chains fail per day.

A chain that fails at step 1 leaves no trace. The other three leave half-done work: 29.7 + 29.4 + 29.1 = 88.2 half-done orders, each with 1, 2 or 3 orphan records, 175.8 orphan records in total. Calculate the card holds left open too: the authorization is placed at step 2, so the 29.4 + 29.1 = 58.5 chains that fail at steps 3 and 4 leave a hold open. With an average order of ₺900, that is 58.5 × ₺900 = ₺52,650 held on customer cards every day. With a saga, compensation for these records runs automatically. If the compensation success rate is 99.5%, 175.8 × 0.005 ≈ 0.9 compensations per day fail, about 26 per month; only those go to a person.

How Is Saga State Monitored and Tested?

The saga's state is kept in a durable table. In orchestration this table lives in the coordinator; in choreography it is a read model derived from event traces. The table serves both operations and customer support.

StateMeaningNext stepMonitoring
STARTEDSaga openedStock reservationTimer starts
IN PROGRESSSteps running in orderNext stepStep duration
COMPLETEDAll four steps succeeded—Success rate
COMPENSATINGFailure occurred, undo runningRun compensations in reverse orderCompensation delay
CANCELLEDAll compensations doneInform the customerCancellation rate
NEEDS ATTENTIONCompensation failed tooHuman queueAge, owner, alert

Four indicators for the dashboard: success rate (target 96% or higher), the number of stuck sagas (over 120 s; in the example 3,000 × 0.05% = 1.5 per day), compensation success rate (99.5%) and the age of the "needs attention" queue. For general monitoring, see our software monitoring guide.

For testing, build a failure point × step matrix. In the example: failure at each of the four steps (4), "action done but reply lost" at each step (4), failure during compensation (in chains failing at steps 2, 3 and 4 there are 1 + 2 + 3 = 6 compensation steps, each a separate scenario), duplicate message delivery at each step (4) and the happy path (1). That is 4 + 4 + 6 + 4 + 1 = 19 scenarios. The count grows quickly with steps, so run the scenarios automatically.

What Is the Payback of Building a Saga?

Without a saga, people clean up half-done chains. 88.2 × 30 = 2,646 half-done chains a month at 6 minutes each is 15,876 minutes = 264.6 hours; at ₺300 per hour, ₺79,380. With a saga only failed compensations go to people: about 26 × 10 minutes = 264 minutes = 4.4 hours × ₺300 = ₺1,320. Say the saga's monthly running and monitoring cost is ₺12,000.

  • Net monthly gain: ₺79,380 − ₺1,320 − ₺12,000 = ₺66,060.
  • Investment: 40 person-days × ₺9,000 = ₺360,000 (coordinator, compensations, state table, tests).
  • Payback: ₺360,000 ÷ ₺66,060 ≈ 5.4 months.

If order volume halves (1,500), the monthly gain is ₺39,690 − ₺660 − ₺12,000 = ₺27,030 and payback stretches to ₺360,000 ÷ ₺27,030 ≈ 13.3 months. Recalculate with your own numbers.

How Do You Run a Saga Project?

Do not apply a saga to everything; use it only where an operation truly spans several services and the data, such as money or stock, must stay consistent. A six-step path works well.

Six steps to set up a saga: map, order, idempotency, timeouts, state log, test
The six steps of setting up a saga.
  1. Map: Write each step, its owning service and its compensation in a table; flag steps with no compensation.
  2. Order: Compensable steps first, the pivot in the middle, irreversible steps last.
  3. Add idempotency: Make every step and compensation repeatable with a saga ID and step key.
  4. Set timeouts: Write retries, waits and the stuck-saga threshold.
  5. Record state: A durable state table, interim-state visibility and alerts.
  6. Automate tests: Run the failure point × step matrix with every release.

Custom Software and Integration with İnovabil

At İnovabil our focus is building custom software from scratch for your company: custom software, ERP, CRM, e-commerce, web, mobile and integration. In workflows where several systems work together, we recommend writing down in the requirements phase which step commits in which system and what happens on failure; whether a saga-like design is needed becomes clear in that analysis.

We built logistics and shipment planning with wholesale order management for Karyak, warehouse management and a complaint and support management system for Sleepy, and a prepaid cargo system for Kredili Kargo. These are real examples of working with connected order, stock and shipping processes; they are not a claim of a separate saga product or service. Send us a short summary of your processes and we will assess them together.

We recommend reading: Our software development process: step by step from analysis to launch

Frequently Asked Questions

What is the saga pattern, in short?

It is a method that splits an operation spanning several services into steps that each commit with their own local transaction, and corrects earlier steps with compensating actions when something fails. It provides consistency in distributed setups where a single ACID transaction is not possible.

What is the difference between a saga and two-phase commit (2PC)?

2PC keeps all participants locked during the prepare phase and depends on a coordinator; a saga commits each step immediately and runs compensation on failure. In a saga the interim states are visible, but lock time is short and services are more independent.

Should I choose choreography or orchestration?

Choreography is enough for simple flows of two or three steps. With four or more steps, conditional branching or complex compensation, orchestration keeps the flow readable in one place and makes state easier to monitor.

What if a step cannot be compensated?

Put that step at the very end of the chain so that, if the chain is going to fail, it fails before reaching it. Define a correction process (a cancellation message, a return) instead of compensation, and write a "last cancellable moment" for physical steps.

Is data lost when a saga fails?

No, but the interim state is temporarily visible. Steps are tracked in a durable state table; if compensation also fails, the record drops into a "needs attention" queue and a person resolves it. Idempotency prevents duplicate processing.

Let's talk about your project

Tell us briefly about the software you have in mind; we'll listen and prepare a tailored roadmap and proposal.

Get a quote