SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
  • The Problem with Distributed Transactions
  • Two-Phase Commit (2PC)
  • Three-Phase Commit (3PC)
  • SAGA Pattern
  • Try-Confirm-Cancel (TCC)
  • Compensating Transactions
  • Outbox Pattern
  • Exactly-Once Processing
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Distributed Systems/Distributed Transactions

Compensating Transactions

You cannot roll back something that already committed, so you undo it with a new action.

⏱ 12 min readIntermediateInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A compensating transaction is a new action that undoes the business effect of an earlier one that already committed. You cannot roll back something that is final, so you do the opposite: a refund for a charge, a cancel for a booking.

  • It is not a rollback. The first action still happened, and the history shows both.
  • It must be idempotent and retryable, because it will be run again after crashes.
  • Steps that cannot be undone (an email sent) should be placed last, after every step that can still fail.

02Concept: What is it?

In one database, a failed transaction is simply rolled back, as if it never happened. Across several services, each service has already committed its own local transaction. By the time a later step fails, the earlier results are real and visible. There is no database to roll them back.

So we write the undo ourselves, as a normal piece of business logic. This is a compensating transaction. It is a semantic undo: it brings the business back to an acceptable state, but not always to the exact same state. A refund returns the money, but the card statement still shows both a charge and a refund. A cancelled booking may still cost a fee.

The SAGA pattern uses compensations as its main tool. This page is about how to design them well: what they must do, what they cannot do, and how to order the steps so the hard ones come last.

Rollback versus compensation
Rollback (one database)
✍️Charge $40not yet committed
↓rollback
🫥Nothing happenedno trace
Compensation (many services)
💳Charge $40committed, visible
↓compensate
💸Refund $40a new, second record
A rollback erases history. A compensation adds a new fact that cancels the effect of the old one.
🧠Undo is a business action
A compensation is not a technical reverse. It is a decision about what the business should do to put things right, and it can have a cost.

03Real-Life Example

🍵Correcting a Bank Statement
A shop charges you $40 by mistake. The bank cannot go back in time and erase it, because it is already on your statement. Instead the shop issues a refund: a new line of +$40. Your balance is right again, but the statement shows both lines. If the shop had also posted a parcel before it noticed, it cannot un-post it. It can only ask for it to come back. Some things have no good undo at all.
The statement
Compensating transactions
A wrong charge on the statement
A committed step
A new refund line, not an erased one
A compensating transaction
Both lines remain visible
The history keeps both actions
The shop retries the refund if the bank is down
Retryable compensation
Refunding twice would cost the shop $80
Why it must be idempotent
A parcel already in the post
A step that cannot be fully undone
Charge the card after the parcel is packed
Put the hard step last
Steps and their undo
📦Reserve stockundo: release
→↓
💳Charge cardundo: refund
→↓
🚚Book courierundo: cancel, small fee
→↓
✉️Email customerno undo

04Why Do We Need It?

🧩No shared database
Each service owns its data, so no single system can roll everything back.
🔓No long locks
Steps commit at once, so other users are not blocked while a long process runs.
🛟A way out of a failure
If step 4 fails, you can still return to a clean business state.
⏳Long-running work
A job that takes hours or days cannot hold a lock. It can only commit and compensate.
🧾A clear record
Both the action and its correction are logged, which is often wanted for audits.
🧠Fits real business
Real companies already use refunds, credit notes and cancellations.
When you cannot roll back, you compensate: do a new action that makes the business right again.

05Where Do We Use It?

🔗Sagas
Each step of a saga has a compensation that runs in reverse order if a later step fails.
🛒Order processing
Release stock, refund payment, cancel the shipment.
✈️Travel booking
Cancel the hotel and the flight if the car hire fails.
🏦Payments and ledgers
A reversal entry is added instead of deleting the original line.
⚙️Workflow engines
Temporal, AWS Step Functions and Camunda have built-in support for compensation steps.
☁️Cloud provisioning
If creating step 5 of an environment fails, tear down steps 1 to 4.

06Types / Parts / How It Works

Common undo patterns

Original stepCompensationNote
Reserve stockRelease the stockClean undo
Charge the cardRefund the cardBoth show on the statement
Book a flightCancel the flightMay cost a fee, or be refused after a deadline
Create a user accountMark it deleted or deactivatedOften not a true delete, because others may refer to it
Send a message to a userSend a correctionThe first message cannot be unsent
Ship a parcelArrange a returnSlow, partial and costly

Three kinds of step in a saga

Not all steps are equal. Sorting them tells you where to put each one.

Compensable, pivot, retryable
Compensable steps
📦Reserve stockcan be undone
💳Authorise paymentcan be undone
Pivot step
🚪Capture paymentthe point of no return
Retryable steps
✉️Send emailretried until it works
🧾Print invoiceretried until it works
Put risky steps first, then the point of no return, then steps that cannot fail for good.
Run first, can be undone Pivot: after this we only go forward After the pivot, retry until done

The rules of a good compensation

🔁Idempotentsafe to run twice
♻️Retryablecan run until it works
🧮Commutative-ishfine if it runs early or late
🙅Never fails for goodno business reason to refuse
VisualizerFail a step and watch the compensations run in reverseChoose which step fails. Then move the email to the front and fail a later step, to see the one step that cannot be undone. Finally turn on a retry with a non-idempotent refund.
Step order
Which step fails?
Refund call is retried?
Refund is idempotent?
📦
1. Reserve stock
Done
Compensated
Release the stock
💳
2. Charge card $40
Done
Compensated
Refund $40
🚚
3. Book courier
Done
Compensated
Cancel booking (courier keeps a $5 fee)
✉️
4. Email the customer
Failed
Nothing to undo
Not compensable
Steps done
3
before the failure
Compensated
3
undone in reverse
Cannot undo
0
left behind
Customer is out
$0
net money
Fees lost
$5
not refundable
  1. Step 1 "Reserve stock" done.
  2. Step 2 "Charge card $40" done.
  3. Step 3 "Book courier" done.
  4. Step 4 "Email the customer" FAILED. Start compensating the steps that finished.
  5. Compensate "Book courier": Cancel booking (courier keeps a $5 fee).
  6. Compensate "Charge card $40": Refund $40.
  7. Compensate "Reserve stock": Release the stock.
The courier booking was cancelled, but the courier keeps a $5 fee. A compensation is a new business action, not a rollback, so the world is not always put back exactly as it was. Budget for the fee, or book the courier later.

A simplified model. Real sagas also keep retrying a compensation until it succeeds, and record progress so a crash in the middle can be resumed.

07How to Use It / Steps / Implementation

Designing compensations

  1. 1
    List every step and ask 'how do I undo this?'
    Write the undo next to each step before you build anything. If you cannot write one, that step is a problem.
  2. 2
    Sort the steps
    Put steps that can fail or be undone first. Put the step that cannot be undone last, after all others have succeeded.
  3. 3
    Find the pivot
    The pivot is the point of no return. Before it you compensate. After it you retry forward until success.
  4. 4
    Give every action a unique id
    The compensation uses the same id, so the service can find the right record and ignore repeats.
  5. 5
    Make compensations idempotent
    Check 'was this id already refunded?' before refunding. Return OK if so.
  6. 6
    Run them in reverse order
    Undo the latest finished step first. Often the order matters, for example release stock before you cancel the order record.
  7. 7
    Retry until it works
    A compensation has no 'give up' branch. Keep retrying with backoff, and alert a human after many failures.
  8. 8
    Handle a compensation that arrives early
    If the undo reaches a service before its original action, remember it and refuse the late action.
💡Semantic locks help
While a saga is running, mark the record as "pending" or "being cancelled". Other users then know not to rely on it, and a compensation can later flip it back.
⚠️Compensations are not free
They cost money (fees), time (a refund takes days), and trust (the user saw the charge). Design the order so compensations are rare.

08Key Terms to Know

TermMeaning in easy words
Compensating transactionA new action that undoes the business effect of an earlier committed action
Semantic undoMaking the business right again, not erasing the past
RollbackA database undoing an uncommitted change, leaving no trace
IdempotentSafe to run again with the same result
RetryableCan be retried until it succeeds
Pivot stepThe step after which the process can no longer be undone and must go forward
Compensable stepA step that has a working undo
Retryable stepA step after the pivot that is retried until it succeeds
Non-compensable stepA step with no undo, such as sending an email
Semantic lockA flag like 'pending' that warns others the record may still change
Reverse orderCompensations run from the latest finished step back to the first

09Pros, Cons and Trade-offs

✅ Pros
  • Works when no rollback is possible
  • No long locks across services
  • Matches how businesses already correct mistakes
  • Leaves a full audit trail
  • Fits long-running processes
⚠️ Cons
  • Not a true undo, the first action was visible
  • Must be designed and written by hand for every step
  • Some actions have no undo
  • Can cost fees or take days
  • Users may see temporary wrong states

Trade-offs

ChoiceWe gainWe lose
Compensate instead of lockSpeed, no blockingIsolation, and users may see in-between states
Pivot step lastFew compensations, simple recoverySlower feedback if the risky step is slow
Delete the record on undoClean dataNo audit trail
Mark as cancelled insteadA full historyMore data to filter out
Retry compensation foreverEventually consistentNeeds alerting for stuck cases

10Common Problems and Mistakes

Common mistakes

  1. Compensations that are not idempotent. A retried refund pays the customer twice.
  2. Doing the step that cannot be undone first. The email goes out, then payment fails, and the customer has a confirmation for nothing.
  3. A compensation that can be refused. If cancelling needs approval, the saga can get stuck half done.
  4. Compensating the step that failed. It never completed, so there is nothing to undo. Compensate only the finished ones.
  5. Running the undo steps in the wrong order. Undo the latest step first.
  6. No timeout or alert. A compensation that keeps failing silently leaves money or stock in limbo.
  7. Forgetting the early compensation. An undo arrives before the original step, which then runs and is never undone.

Things to watch

👀Dirty reads
Others can see the charge before the refund. Use a 'pending' flag when it matters.
💥Failure during compensation
The process itself can crash. Store progress so it resumes where it stopped.
🧾Partial undo
A fee or a returned item means the final state is not exactly the start. Document it.
🔔Human fallback
Some failures need a person. Send them to a manual queue, do not drop them.

11Real-World Examples

🏦Ledgers and accounting
Accountants never erase an entry. They post a reversing entry. This is compensation in its oldest form.
💳Payment reversals
Card networks have 'void' for an unsettled payment and 'refund' for a settled one: two different compensations.
✈️Airline and hotel cancellation
Cancellation rules and fees are the business-level compensation, and they vary by time and fare.
⚙️AWS Step Functions and Temporal
Both let you attach a compensation to each step of a workflow and run them on failure.
🛒E-commerce checkout
Order services release stock and refund payment when a late step fails.
🏗️Infrastructure as code
Tools tear down the resources already created when a later one fails.
📝Note
There is no standard library that does this for you. The undo is business logic, and only your team knows what is acceptable.
Mini case: void or refund?
💳Authorised onlymoney not moved
→↓undo with
🚫Voidfree and instant
→↓but if captured
💸Refunddays, may cost a fee
The right compensation depends on how far the payment got.

12Related Topics to Read Next

SAGA Pattern→

The pattern that runs compensations in order.

Try-Confirm-Cancel (TCC)→

Reserve first so the undo is just a release.

The Problem with Distributed Transactions→

Why we cannot just roll back.

Idempotency→

The rule that makes retried compensations safe.

Outbox Pattern→

Publishing the events that trigger compensations safely.

Exactly-Once Processing→

Making sure a compensation takes effect once.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔Compensation: a new action that cancels the business effect of a committed one.
  • ✔Not a rollback: both actions stay visible in the history.
  • ✔Idempotent and retryable: use an id, check before acting, retry until success.
  • ✔Order: compensate finished steps in reverse. Skip the failed step.
  • ✔Pivot: before it we compensate, after it we retry forward.
  • ✔No undo? Put that step last (emails, shipping labels).
  • ✔Semantic locks: mark records "pending" while a saga runs.
  • ✔One line: “You cannot erase what happened, so add a new action that makes it right.”
← Previous
Try-Confirm-Cancel (TCC)
Next →
Outbox Pattern