This prompt is for platform engineers implementing saga patterns across multi-agent workflows. Use it when you need an LLM to generate a structured compensation plan for each step in an agent execution graph, including undo actions, state reversal logic, and ordering constraints for rollback. The primary job-to-be-done is converting a failed workflow state into an executable, ordered set of compensating transactions that return the system to a consistent state without manual intervention. The ideal user is an orchestration engineer or reliability engineer who already has a defined workflow DAG with unique step identifiers, recorded execution context per step, and a known failure point. You should reach for this prompt only after a step failure is detected and before rollback execution begins—it belongs in the error-recovery path of a workflow orchestrator, not in the happy-path execution flow.
Prompt
Workflow Rollback and Compensation Prompt

When to Use This Prompt
Defines the exact scenario, required context, and boundaries for using the workflow rollback and compensation prompt in a production agent orchestrator.
This is not a prompt for simple retry logic or idempotency keys. If your failure mode can be resolved by replaying the same step with the same inputs, use a retry-with-backoff pattern instead. Do not use this prompt when the workflow is stateless, when all steps are read-only, or when you lack a complete execution trace showing which steps succeeded and what side effects they produced. The prompt assumes you can provide: a list of workflow steps with their types and identifiers, the execution status of each step (completed, in-progress, not-started), the step where the failure occurred, the error payload, and any recorded state mutations or external calls made by completed steps. Without this context, the LLM cannot produce a safe compensation plan—it will hallucinate undo actions or miss irreversible side effects entirely.
Before wiring this prompt into production, ensure your workflow orchestrator can enforce the compensation plan it receives. The LLM's output is a plan, not an execution—your system must validate that every compensation step maps to a real handler, that the ordering constraints are satisfiable, and that no compensation step introduces new side effects that themselves require rollback. For high-risk workflows involving financial transactions, provisioning, or data deletion, always route the generated compensation plan through a human approval step before execution. The next section provides the exact prompt template you can adapt and the harness logic required to make it production-safe.
Use Case Fit
Where the Workflow Rollback and Compensation Prompt fits into your agent orchestration stack and where it creates more risk than it resolves.
Good Fit: Saga Pattern Orchestration
Use when: You have a multi-step agent workflow where later steps depend on earlier ones, and a mid-workflow failure requires undoing previously committed side effects. Guardrail: Ensure every forward step has a corresponding compensation handler defined before execution begins.
Bad Fit: Stateless or Idempotent Pipelines
Avoid when: Every agent step is idempotent, read-only, or operates on ephemeral state that does not require reversal. Adding compensation logic to stateless pipelines introduces unnecessary complexity and latency. Guardrail: Audit your agent graph for actual side effects before introducing rollback prompts.
Required Inputs
What you must provide: A complete execution trace showing each agent step, its input/output, and the side effects it produced. The prompt cannot infer what happened without this structured history. Guardrail: Instrument your agent harness to capture step-level traces with timestamps and resource identifiers before invoking the compensation planner.
Operational Risk: Irreversible Side Effects
What to watch: Some agent actions—sending emails, triggering deployments, or creating external accounts—cannot be truly undone. The prompt may generate compensation steps that are logically correct but operationally impossible. Guardrail: Maintain a registry of irreversible actions and require human approval before executing any compensation plan that touches them.
Operational Risk: Partial Compensation Drift
What to watch: If the system state changes between the original failure and compensation execution, the generated undo plan may be stale or cause new conflicts. Guardrail: Re-validate the current state before each compensation step and abort with an escalation if preconditions no longer hold.
Operational Risk: Ordering Constraint Violations
What to watch: Compensation steps often have a strict reverse-order dependency. A generated plan that proposes parallel or out-of-order rollback can corrupt state further. Guardrail: Include explicit ordering constraints in the prompt template and validate the generated plan against the original execution DAG before applying it.
Copy-Ready Prompt Template
A reusable prompt for generating a compensation plan when an agent workflow step fails, enabling safe rollback.
This prompt template is designed to be injected into your orchestrator's error-handling path when a workflow step fails and a saga-based rollback is required. It instructs the model to analyze the failed step, the preceding successful steps, and the overall workflow context to produce a structured compensation plan. The plan must include undo actions, state reversal logic, and strict ordering constraints to safely return the system to a consistent state. The prompt uses square-bracket placeholders so you can wire in dynamic context from your workflow engine, state store, and agent logs.
textYou are an expert workflow reliability engineer. Your task is to generate a precise compensation and rollback plan for a failed agent workflow step. # WORKFLOW CONTEXT - Workflow ID: [WORKFLOW_ID] - Workflow Definition (DAG): [WORKFLOW_DEFINITION] - Current Execution State: [EXECUTION_STATE] # FAILURE DETAILS - Failed Step ID: [FAILED_STEP_ID] - Failure Reason: [FAILURE_REASON] - Error Payload: [ERROR_PAYLOAD] # COMPLETED STEPS (in execution order) [COMPLETED_STEPS_LIST] # CONSTRAINTS - [CONSTRAINTS] # INSTRUCTIONS 1. Analyze the failed step and all preceding completed steps. 2. For each completed step that produced a side effect, define a corresponding compensation action (an undo operation). 3. If a completed step is irreversible, flag it explicitly and propose a manual intervention or notification action. 4. Define the strict reverse-order sequence for executing compensation actions. 5. Identify any state variables that must be rolled back to their pre-workflow values. 6. Output the plan as a valid JSON object conforming to the schema below. # OUTPUT SCHEMA { "rollback_plan": { "workflow_id": "string", "failed_step_id": "string", "compensation_steps": [ { "step_id": "string", "original_action": "string (description of what the step did)", "compensation_action": "string (description of the undo operation)", "is_reversible": boolean, "irreversibility_reason": "string | null (explain if not reversible)", "required_state_rollback": { "key": "string", "previous_value": "string" } | null } ], "execution_order": ["string (ordered list of step_ids to execute compensation)"], "final_state_assertions": ["string (list of conditions that must be true after rollback)"] } } # RISK LEVEL [RISK_LEVEL]
To adapt this template, replace the placeholders with live data from your workflow engine. The [WORKFLOW_DEFINITION] should be a serialized representation of your agent graph, and [EXECUTION_STATE] should capture the current values of all relevant state variables. The [COMPLETED_STEPS_LIST] must include the step ID, its input/output payload, and a description of any external side effects (e.g., database writes, API calls). Before deploying, test this prompt against a golden dataset of known failure scenarios to ensure the generated compensation steps are correct and that the JSON output strictly conforms to the schema. For high-risk workflows, always route the generated plan to a human approval queue before execution.
Prompt Variables
Required inputs for the Workflow Rollback and Compensation Prompt. Each placeholder must be populated before the prompt can produce a reliable compensation plan. Missing or malformed inputs are the most common cause of incomplete rollback coverage.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[WORKFLOW_DEFINITION] | Complete ordered list of saga steps with step IDs, descriptions, and success criteria | Step-1: ReserveInventory, Step-2: CapturePayment, Step-3: ShipOrder | Must be a valid JSON array of step objects. Reject if steps are missing IDs or if ordering is ambiguous. Parse check: array length >= 1. |
[STEP_COMPENSATION_MAP] | Mapping from each step ID to its compensating action, including required parameters and preconditions | {"CapturePayment": {"action": "RefundPayment", "params": ["transactionId"], "precondition": "transactionId != null"}} | Must be a valid JSON object. Every step in [WORKFLOW_DEFINITION] must have a corresponding entry. Reject if any step lacks a compensation handler. Schema check: required fields are action, params, precondition. |
[FAILED_STEP_ID] | Identifier of the step where execution failed, triggering the rollback | CapturePayment | Must match exactly one step ID from [WORKFLOW_DEFINITION]. Reject if null, empty, or not found in the step list. Parse check: string match against step IDs. |
[FAILURE_CONTEXT] | Error message, exit code, or state snapshot at the point of failure | {"error": "PaymentGatewayTimeout", "exitCode": 504, "timestamp": "2025-01-15T10:23:00Z"} | Must be a valid JSON object with at least an error field. Null allowed if failure is silent but [FAILED_STEP_ID] is known. Schema check: error field is required string. |
[EXECUTED_STEPS_STATE] | Record of which steps completed successfully and their output artifacts before the failure | [{"stepId": "ReserveInventory", "status": "completed", "output": {"reservationId": "RES-987"}}] | Must be a valid JSON array. Each entry requires stepId, status, and output fields. Status must be one of completed, skipped, or in_progress. Reject if array is empty when [FAILED_STEP_ID] is not the first step. Schema check: enum validation on status. |
[IRREVERSIBLE_STEPS] | List of step IDs that have permanent side effects and cannot be compensated automatically | ["SendEmailNotification"] | Must be a valid JSON array of step ID strings. Each ID must exist in [WORKFLOW_DEFINITION]. Null or empty array is allowed if all steps are reversible. Parse check: array elements must be strings matching step IDs. |
[COMPENSATION_ORDERING] | Direction for rollback execution: forward, reverse, or custom ordering with explicit sequence | reverse | Must be one of forward, reverse, or a valid JSON array of step IDs in desired execution order. If custom array, every completed step from [EXECUTED_STEPS_STATE] must appear exactly once. Enum check: forward, reverse, or array validation. |
Implementation Harness Notes
How to wire the Workflow Rollback and Compensation Prompt into a production-grade saga execution engine.
This prompt is not a standalone utility; it is a critical safety component inside a saga orchestrator. The harness must call this prompt before any agent step executes, generating a compensation plan that is stored alongside the step's execution context. The plan must be treated as a required artifact—if the prompt fails to produce a valid plan, the step should not proceed. The harness is responsible for mapping each compensation action to a concrete, idempotent function (e.g., a refund API call, a state reversion in a database, a cancellation message to a downstream agent). The prompt produces the what and why; the harness enforces the how and when.
To integrate this prompt, wrap it in a pre-execution hook within your workflow engine. The hook should provide the prompt with the proposed step's intent, the current system state, and the list of available compensation tools. The output must be validated against a strict JSON schema that includes: a step_id, an ordered list of compensation_actions (each with a tool_name, payload, and idempotency_key), and a rollback_ordering_constraint (e.g., 'strict_reverse' or 'parallel'). If validation fails, the harness must retry the prompt once with the validation errors injected into the [CONSTRAINTS] block. After a second failure, the workflow must halt and escalate to a human operator via the escalation queue, as proceeding without a valid compensation plan violates the saga's safety guarantees.
For irreversible side effects (e.g., sending an email, invoking a physical process), the prompt should flag them with a compensation_type of manual or irreversible. The harness must enforce a policy check here: if an irreversible action is detected, the workflow must pause and request explicit human approval before executing the step, even if the compensation plan is otherwise valid. Log every generated plan, validation result, and approval decision to an immutable audit store. This trace is essential for debugging failed rollbacks and proving to auditors that the system followed its defined safety procedures. Do not rely on the model's memory of prior plans; always pass the full workflow context and previously executed steps into the prompt to prevent context drift.
Expected Output Contract
Defines the structured JSON payload the model must return for each compensation plan. Use this contract to validate outputs before executing rollback actions.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
compensation_plan_id | string (UUID v4) | Must match regex for UUID v4. Reject if missing or malformed. | |
workflow_run_id | string | Must match the [WORKFLOW_RUN_ID] input exactly. Reject on mismatch. | |
generated_at | string (ISO 8601 UTC) | Must parse as valid ISO 8601 datetime in UTC. Reject if unparseable or non-UTC. | |
steps | array of objects | Must be a non-empty array. Reject if empty or not an array. Each element must conform to the step schema below. | |
steps[].step_id | string | Must match a step_id from the [WORKFLOW_DEFINITION] input. Reject on unknown step_id. | |
steps[].compensation_action | string | Must be a non-empty string describing the undo operation. Reject if null or whitespace only. | |
steps[].state_reversal_logic | string | Must describe how state is reverted. Reject if it contains only generic phrases like 'revert state' without specifics. | |
steps[].ordering_constraint | string (enum) | Must be one of: 'before', 'after', 'parallel', 'independent'. Reject on invalid enum value. | |
steps[].depends_on_step_ids | array of strings | If ordering_constraint is 'after', this field must be a non-empty array of valid step_ids. Reject if constraint is 'after' and this is empty or missing. | |
steps[].irreversible_side_effects | array of strings | Must be an array. If empty, implies no known irreversible effects. Each string must describe a specific side effect. Reject if null. | |
steps[].requires_human_approval | boolean | Must be true if irreversible_side_effects is non-empty or if the step involves external financial/legal actions. Flag for review if true but no irreversible effects listed. | |
uncompensatable_risks | array of strings | Must be an array. Each string must describe a risk that cannot be compensated. Reject if null. Flag for human review if non-empty. |
Common Failure Modes
Production rollback and compensation prompts fail in predictable ways. These are the most common failure modes and the guardrails that prevent them.
Missing Compensation Handlers
What to watch: The prompt generates a rollback plan that skips steps with irreversible side effects (e.g., sent emails, external API calls with no undo endpoint). The model assumes compensation exists where it doesn't. Guardrail: Require the prompt to explicitly mark each step as 'reversible,' 'compensatable,' or 'irreversible' and halt plan generation when irreversible steps lack a manual intervention path.
Incorrect Compensation Ordering
What to watch: The model proposes running compensation actions in parallel or in the wrong sequence, violating the reverse-order requirement of saga patterns. Step 3's compensation runs before Step 2's, corrupting state. Guardrail: Include an explicit ordering constraint in the prompt: 'Compensation actions MUST execute in strict reverse order of the original steps. Validate that no compensation action depends on state restored by a later compensation.'
Idempotency Gaps in Compensation
What to watch: The generated compensation actions are not idempotent. Retrying a failed compensation could double-refund, re-send a cancellation, or apply a state reversal twice. Guardrail: Add an idempotency check to the prompt output schema. Require each compensation step to include an idempotency key strategy and a 'safe to retry' flag with explicit preconditions.
Stale State Assumptions
What to watch: The compensation plan references state values from the original execution without verifying they are still current. A refund amount calculated from a stale balance causes an overdraft. Guardrail: Require the prompt to produce a 'state freshness check' for each compensation step. Before executing compensation, the handler must re-read current state and validate that the compensation parameters are still valid.
Partial Rollback Inconsistency
What to watch: The workflow fails mid-rollback, leaving the system in an inconsistent state where some steps are compensated and others are not. The prompt provides no guidance on resuming or completing a partial rollback. Guardrail: Include a 'rollback resume' contract in the output. The compensation plan must be restartable from any step, with each compensation action checking whether it has already been applied before executing.
Compensation Side Effects Not Tracked
What to watch: Compensation actions themselves produce side effects (logs, events, notifications) that downstream systems react to, triggering unintended workflows. A refund event triggers a false fraud alert. Guardrail: Require the prompt to list expected side effects of each compensation action and include a suppression or correlation strategy so downstream consumers can distinguish compensation events from original events.
Evaluation Rubric
Criteria for evaluating the quality of a generated rollback and compensation plan before integrating it into a production saga execution engine.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Compensation Coverage | Every forward step in [WORKFLOW_STEPS] has a corresponding compensation action defined in the plan. | A forward step is listed without a matching compensation action, or the action is described as 'none' or 'irreversible' without an explicit human approval flag. | Parse the output JSON. For each step in the input [WORKFLOW_STEPS] array, assert that a corresponding entry exists in the output's compensation_plan array. |
Ordering Constraint Validity | Compensation actions are listed in strict reverse order of the forward steps, with explicit ordering constraints. | Compensation actions are listed in the same order as forward steps, or the ordering_constraints field is empty or missing. | Extract the sequence of step IDs from the forward plan and the compensation plan. Assert the compensation sequence is the exact reverse of the forward sequence. |
State Reversal Logic | Each compensation action includes a state_reversal field that specifies the exact state to restore, not just the action to take. | A compensation action only describes an API call (e.g., 'call refund API') without specifying the target state (e.g., 'set order.status to CANCELLED'). | For each compensation action, assert that the state_reversal object is present and contains at least one key-value pair representing the target state. |
Irreversible Step Handling | Any step flagged as irreversible includes a human_approval_required field set to true and an escalation_policy reference. | An irreversible step is marked with a null compensation action but does not trigger an approval or escalation workflow. | Scan all compensation actions. For any where is_reversible is false, assert that human_approval_required is true and escalation_policy is a non-empty string. |
Idempotency Guarantee | Each compensation action includes an idempotency_key constructed from the forward step's unique identifier and a version. | The idempotency_key field is missing, null, or uses a non-deterministic value like a random UUID or timestamp. | For each compensation action, assert that idempotency_key is a non-empty string that contains the corresponding forward step's [STEP_ID]. |
Failure Mode Enumeration | The plan includes a failure_modes array for the overall saga, listing at least one scenario where compensation itself might fail. | The failure_modes array is empty, missing, or only describes forward-step failures without addressing compensation-step failures. | Assert that the output contains a top-level failure_modes array with at least one entry where the scope is 'compensation'. |
Context for Human Review | The plan includes a human_handoff_summary string that explains what happened, what will be undone, and what requires a decision. | The human_handoff_summary field is missing, is an empty string, or contains only technical jargon without a clear decision request. | Assert that human_handoff_summary is a non-empty string. Use an LLM-as-judge check to confirm it contains a description of the failure and a clear question or decision prompt for the operator. |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Add a strict output schema for the compensation plan, including ordering constraints, dependency tracking between compensation actions, and a rollback state machine. Wire in validation that checks every forward step has a corresponding compensation handler.
codeOutput as JSON matching [COMPENSATION_SCHEMA]: { "workflow_id": "[WORKFLOW_ID]", "steps": [ { "step_id": "[STEP_ID]", "forward_action": "[ACTION]", "side_effects": ["[EFFECT_1]", "[EFFECT_2]"], "compensation": { "action": "[UNDO_ACTION]", "depends_on": ["[PRIOR_COMPENSATION_STEP_ID]"], "is_idempotent": true, "max_retries": 3 }, "irreversible": false, "requires_human_approval": false } ], "rollback_order": ["[STEP_ID_3]", "[STEP_ID_2]", "[STEP_ID_1]"], "failure_mode": "[FORWARD_RECOVERY | BACKWARD_RECOVERY | MANUAL]" }
Watch for
- Silent format drift in compensation action descriptions
- Missing dependency edges causing out-of-order rollback
- Irreversible steps without human approval gates
- Compensation actions that aren't idempotent (double-execution risk)

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us