What are compensating transactions, and how are they used in the Saga pattern?

A compensating transaction is an operation that semantically undoes the effect of a previously completed step in a Saga, used when a later step in the same business process fails.

Key Points: • Each forward step in a Saga that changes state must have a matching compensating action defined up front, not improvised after failure. • Compensation is a best-effort logical undo, such as issuing a refund, rather than a true database rollback, since the original transaction already committed. • Compensations run in reverse order of the steps that succeeded, unwinding the saga back toward its initial state. • Compensating actions must be idempotent, since retries or duplicate messages can cause them to run more than once. • Not all steps are compensatable in the same way; irreversible actions like sending an email are often handled with a corrective follow-up message instead of a true undo.

Example: In a trip-booking Saga, if reserving a flight and a hotel succeed but the car rental step fails, the compensating transactions cancel the hotel reservation and refund the flight booking, in that reverse order, returning the customer's booking state to what it was before the process began.

Interview Tip: A concise interview answer is:

"A compensating transaction is the semantic undo for a step that already committed, like cancelling a reservation instead of rolling back a database transaction. In the Saga pattern, every step that mutates state needs one defined up front, and they run in reverse order when a later step fails, which is how the saga restores consistency without a distributed transaction."