What is compensatingtransactions?
A compensating transaction is a separate operation that “undoes” the effects of a previous action when the original transaction cannot be completed successfully. Instead of rolling back in place (like a traditional database rollback), you run a new transaction that reverses what was done, restoring the system to its prior state.
Let's break it down
- Transaction: A set of steps that should all succeed together (all‑or‑nothing).
- Distributed system: When those steps run on different services or databases, a single rollback is often impossible.
- Compensating transaction: A follow‑up action that counteracts the earlier step (e.g., crediting back money that was debited).
- How it works: Service A does something, then Service B does something else. If B fails, A runs its compensating transaction to reverse its work.
Why does it matter?
- Keeps data consistent across many independent services.
- Prevents partial updates that could confuse users or break business rules.
- Allows systems that can’t share a single database to still behave reliably.
- Enables “eventual consistency” where the system converges to a correct state over time.
Where is it used?
- Microservice architectures that use the Saga pattern.
- E‑commerce order processing (reserve inventory → charge payment → ship).
- Banking and financial services for multi‑step transfers.
- Travel booking sites (reserve flight, then hotel, then car).
- Any system where a single ACID transaction across all components is impractical.
Good things about it
- Works with heterogeneous services and databases.
- Avoids the need for heavyweight distributed locks or two‑phase commit.
- Makes long‑running business processes possible while still handling failures.
- Gives developers explicit control over how to reverse each step, which can be tailored to business needs.
Not-so-good things
- Adds extra code: you must write and maintain a compensating action for every forward step.
- Increases complexity; tracking which compensations have run can be tricky.
- Only “best‑effort” reversal - some side effects (e.g., sending an email) may not be fully undoable.
- Leads to eventual consistency, meaning the system may be temporarily out of sync, which can confuse users if not handled properly.