Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 53

Implementing Saga Compensation for Failed Multi-Step Operations

Recommended resources

Introduction

In our previous lessons, we built a robust failure-handling stack for individual agent tasks. We implemented retry logic for transient errors, idempotency to make retries safe, and dead-letter queues to handle terminal failures without blocking the system. However, these patterns primarily address the failure of a single, self-contained action. The agents you're aiming to build will execute complex, multi-step workflows with real-world side effects: charging a credit card, reserving inventory, calling an external API.

What happens if the second step of a three-step process fails? The first step has already succeeded, leaving the system in an inconsistent state. Simply dead-lettering the failed second step is insufficient; we must actively undo the work of the first. This lesson tackles this exact challenge by implementing the Saga compensation pattern. As someone with a strong background in distributed systems, you'll recognize this as a classic architectural pattern for maintaining data consistency across multiple services without using traditional distributed transactions. Our goal today is to adapt and implement this pattern to roll back actions from a failed multi-step agent operation, ensuring your agentic workflows are not just resilient but also logically coherent in the face of partial failure.


1. First Principles: What is a Saga?

The Saga pattern originates from a 1987 database research paper, designed to handle long-running transactions (LLTs) on a single database without holding locks for extended periods. The core idea is to break a large transaction into a sequence of smaller, independent sub-transactions. Crucially, for each sub-transaction, a corresponding compensating transaction must be defined.

The guarantee of a Saga is as follows:

  • If all sub-transactions in the sequence complete successfully, the saga is successful.
  • If any sub-transaction fails, the saga executes the compensating transactions for all previously completed sub-transactions in reverse order. This effectively "rolls back" the work done, returning the system to a semantically consistent state.

This approach trades the strict atomicity of traditional ACID transactions for higher availability and performance, a common trade-off in distributed architectures.

The following video by Caitie McCaffrey provides an excellent explanation of the pattern's origins and logic. It's a foundational talk in the distributed systems community.

Applying the Saga Pattern • Caitie McCaffrey • GOTO 2015

This classic talk from GOTO 2015, "Applying the Saga Pattern," breaks down the pattern from first principles, tracing it back to its original academic paper.

Please watch the segment from Sagas come in. Focus on the definition of a saga as a collection of sub-transactions and compensating transactions, and how the successful and unsuccessful flows are logged and executed. This provides the fundamental theory we will build upon.

The diagram below illustrates this flow for a travel booking agent. The top row shows the forward-moving transaction steps. If any step fails (e.g., Reserve room at hotel H2), the system triggers the compensating transactions in reverse order to cancel the hotel room, then the flights.

This diagram shows the forward flow of an "Operation to create itinerary" and the reverse flow of a "Compensating transaction to cancel itinerary." If a forward step fails, the corresponding counter-operations are executed in reverse to undo the completed work.

2. Implementation Approaches: Orchestration vs. Choreography

When applying the Saga pattern in a distributed system, there are two primary coordination strategies: orchestration and choreography.

  1. Orchestration: A central coordinator (the "orchestrator") is responsible for managing the entire workflow. It explicitly calls each service or executes each step in sequence. If a step fails, the orchestrator is responsible for calling the necessary compensating actions. This approach is centralized, making the logic explicit and generally easier to trace and debug.

  2. Choreography: There is no central coordinator. Each service in the workflow is autonomous. After completing its task, a service publishes an event (e.g., FlightBooked). Other services subscribe to these events and react accordingly. Compensation is also handled through events (e.g., a HotelBookingFailed event might cause the flight service to trigger its own CancelFlight logic). This approach is decentralized and loosely coupled but can be significantly harder to debug and visualize the overall state of the workflow.

The diagram below illustrates the orchestration approach, which is often a better fit for building a controllable and observable agentic system from first principles.

This diagram shows a central "Orchestration controller" managing a sequence of reservations (Airline, Hotel, Car rental). If any step fails, the controller is responsible for invoking the corresponding rollback compensation.

For the rest of this lesson, we will focus on the orchestration pattern, as it gives us explicit control over the workflow, which aligns well with building a core agent engine. The following article provides a clear definition and comparison of these two approaches.

How to Implement the Saga Pattern for Distributed Transactions

This article from OneUptime gives a concise overview of the Saga pattern and a useful comparison between the orchestration and choreography approaches.

First, read the section defining a Saga. Then, review the brief introduction to the two approaches. Finally, examine the table in the section Choreography vs Orchestration to understand the trade-offs.


3. Implementing an Orchestrated Saga

Let's now implement an orchestrated saga in Python. Our goal is to create a simple orchestrator that can execute a sequence of steps and trigger a rollback if any step fails. Each step will be defined by two functions: an execute function for the forward action and a compensate function for the rollback action.

The article "Event-Driven AI Agents: Patterns That Scale" provides a remarkably clean and effective async implementation of this pattern.

Event-Driven AI Agents: Patterns That Scale - DEV Community

This article from DEV Community demonstrates several patterns for scalable agents. We'll focus on its excellent implementation of Saga Orchestration.

First, read the brief introduction to the pattern under the heading Saga Orchestration. Then, carefully study the Python code under the "Implementation" sub-heading. Finally, review the console output to see the rollback in action.

Let's break down the key components from that code:

  1. SagaStep: This data class represents a single unit of work. It holds the name, the execute callable, and the compensate callable. This enforces the core contract of the Saga pattern: every action must have a defined undo action.

    @dataclass
    class SagaStep:
        name: str
        execute: Callable
        compensate: Callable
        status: StepStatus = StepStatus.PENDING
        ...
    
  2. Saga.run(): This is our orchestrator logic. It iterates through the list of steps.

    • It maintains a completed list to track which steps have succeeded.
    • Inside a try...except block, it calls step.execute().
    • If successful, it marks the step as COMPLETED and adds it to the completed list.
    • If an exception occurs, it catches the error, marks the step as FAILED, and immediately calls the _compensate() method.
  3. Saga._compensate(): This is the rollback logic.

    • It takes the list of completed steps.
    • Crucially, it iterates over this list in reverse (reversed(completed)).
    • For each completed step, it calls the step.compensate() function to undo the work.

This simple structure elegantly implements the orchestration pattern. The orchestrator has complete knowledge of the workflow and is solely responsible for coordinating both forward execution and backward compensation.


4. Production Considerations: Idempotency and Compensation Failures

The implementation above is a solid foundation, but a production-grade system requires us to consider more complex failure modes. Your background in distributed systems will make these considerations intuitive.

Idempotency of Compensating Actions

What happens if the compensate action itself fails? For example, the refund_card call might time out. A robust orchestrator will retry the compensating action. This leads to a critical requirement we've discussed before: compensating actions must be idempotent. If we retry a non-idempotent refund_card action, we might issue multiple refunds to the customer. This reinforces the importance of designing idempotent tool actions, not just for forward retries but especially for rollback safety.

Failure of Compensation

What if a compensating action terminally fails, even after retries? This is a catastrophic failure for the saga. For instance, if refund_card fails permanently, the system is left in an inconsistent state (card charged, but goods not shipped).

In this scenario, the saga cannot proceed automatically. The orchestrator's only remaining option is to:

  1. Persist the state of the entire saga, including which steps completed and which compensations failed.
  2. Route this failed saga state to a dead-letter queue for manual intervention.
  3. Trigger an alert to a human operator.

This seamlessly integrates the Saga pattern with the dead-lettering mechanism we designed in the previous lesson. The DLQ becomes the final backstop for unrecoverable workflow inconsistencies.

The following video segment explains the necessity of these additional constraints when moving the Saga pattern from a theoretical model to a real-world distributed system.

Applying the Saga Pattern • Caitie McCaffrey • GOTO 2015

This segment of Caitie McCaffrey's talk explains the additional constraints required to make Sagas work in a distributed world.

Please watch the clip from what do we need. Pay close attention to the discussion of why compensating requests must be idempotent to handle retries safely, and how the system must handle the "unsafe state" when an SEC (Saga Execution Coordinator) crashes mid-request. This mirrors our own orchestrator's failure modes.


Conclusion

Today, you've implemented one of the most powerful reliability patterns for agentic systems. By integrating the Saga pattern, you've moved beyond handling single-task failures to ensuring the logical consistency of complex, multi-step workflows that have real-world side effects. This is a significant step towards building production-grade agents that can operate autonomously and gracefully recover from partial failures.

Key Takeaways:

  • Saga for Multi-Step Consistency: The Saga pattern manages consistency across a sequence of operations by defining a compensating action for each forward action.
  • The Saga Guarantee: A saga ensures that either all steps in the workflow succeed, or all completed steps are rolled back, preventing the system from being left in a partially complete, inconsistent state.
  • Orchestration Provides Control: The orchestration approach, with a central coordinator, offers explicit control over the workflow logic, making it easier to implement, debug, and observe.
  • Compensation Must Be Robust: For a production system, compensating actions must be idempotent to allow for safe retries. Failures in compensation itself are critical events that typically require dead-lettering and human intervention.

Preview of the Next Lesson:

We have now concluded our module on agent reliability and recovery. We've built a solid foundation for making our agents robust against a wide variety of systemic and execution failures. In our next module, Safety, Guardrails, and Human Oversight, we will shift our focus from internal robustness to external threats and constraints. We'll begin by tackling a critical security vulnerability in LLM-based systems: prompt injection. You will learn to implement input sanitization and detection mechanisms to protect your agents from being hijacked by malicious user inputs.