Video in progress
How does a compensating transaction differ from a plain rollback?
A rollback wipes out uncommitted changes without a trace. A compensation undoes an already committed operation with a new, reversing business operation: a trace remains, and it doesn't always restore the "exact previous state".
📖 Answer
If you roll back in a database, it's as if nothing happened. In a saga, the payment has already happened: there's a bank record, and an SMS may already have gone to the customer. You can't "delete" it; you can only refund it.
Practical points about compensation:
- It can fail too. If the refund service is down, the compensation has to be retried later. That's why it must be idempotent.
- Some operations can't be undone. You can't take back a sent email; you can only send a second one saying "the order was cancelled". It's good to put such steps at the end of the saga.
- Business rules come in. Is a fee withheld on cancellation? Is the bonus returned? That's a business decision, not a technical one.
// the compensation is a separate, clearly named operation
public void refund(UUID paymentId, String reason) {
Payment p = repo.findById(paymentId).orElseThrow();
if (p.getStatus() == REFUNDED) return; // does nothing on the second call
gateway.refund(p.getExternalId());
p.markRefunded(reason);
}
Sign up to mark studied questions and save your progress.