Agent Error Recovery

Production-grade guide to agent error recovery covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.

An agent error recovery system ensures that an AI agent continues to make progress toward its goal even when individual steps, external calls, or internal computations fail. It matters when an agent orchestrates a multi-step workflow—such as processing a customer onboarding request, validating a contract, or generating a quarterly report—where a single failure can stall the entire process. Recovery mechanisms must handle transient issues (e.g., network timeouts), permanent errors (e.g., invalid input schema), and stateful resumption after failures, ensuring that agents do not lose progress or duplicate work.

Error Detection and Reporting

Agents detect errors through explicit error handling, exception propagation, and diagnostic logging. Errors are reported as structured events with a common schema: a timestamp, error_type, message, agent_id, step_id, and optional context (a JSON object containing input, output, and execution state at the time of failure).

When an agent step fails, it emits an error event to a central logging stream:

{
  "timestamp": "2024-05-17T12:34:56.789Z",
  "error_type": "ValidationFailed",
  "message": "Customer address is missing required field 'postal_code'",
  "agent_id": "onboarding-agent-v3",
  "step_id": "validate_customer_details",
  "context": {
    "input": {
      "customer_id": "cust-12345",
      "name": "Alice Johnson",
      "address": {
        "street": "123 Main St",
        "city": "Seattle",
        "state": "WA"
      }
    },
    "output": null,
    "execution_duration_ms": 217,
    "attempt": 2
  }
}

Errors may be surfaced via standard tools:

The agent framework must support try-catch blocks around individual steps. In code, a typical recovery pattern uses a with block to wrap a function call:

try:
    customer = validate_customer(customer_data)
except ValidationError as e:
    log_error(
        error_type="ValidationFailed",
        message=str(e),
        context={"input": customer_data, "attempt": 2}
    )
    raise

The context object captures the state at failure, enabling later recovery.

Retry Strategies

Agents use retry strategies to recover from transient failures. Retries are configured with a policy: a combination of max_attempts, initial_delay, backoff, and retry_on.

The most common backoff is exponential with jitter:

{
  "max_attempts": 5,
  "initial_delay_ms": 100,
  "backoff": "exponential",
  "jitter": "full",
  "retry_on": [
    "NetworkError",
    "TimeoutError",
    "ServiceUnavailable",
    "ValidationError"
  ]
}

Each retry attempt is recorded in the agent’s execution history. After a failure, the agent updates the attempt field in context, and the next retry uses the updated state. The agent may also increase the delay between attempts:

The agent may pause execution during retries, and a step is considered retriable if the error type is in the retry_on list. A step that fails with TimeoutError is retried; one failing with InvalidSchemaError is not.

If an agent uses a task queue (e.g., RabbitMQ, AWS SQS, or Redis Streams), tasks are requeued with a delay field set by the retry logic. The queue assigns a next_attempt_at timestamp based on the backoff schedule.

State Persistence and Checkpointing

To recover from crashes or restarts, agents persist state between steps. Each agent execution is a series of steps, and the state is saved after every step.

State is stored as a JSON object in a durable store: a database, a file system, or a key-value store. The agent writes state at each step:

{
  "agent_id": "onboarding-agent-v3",
  "execution_id": "exec-78901",
  "current_step": "generate_contract",
  "state": {
    "customer": {
      "id": "cust-12345",
      "name": "Alice Johnson",
      "status": "validated"
    },
    "contract": {
      "template": "standard-2024",
      "generated_at": "2024-05-17T12:35:01Z"
    }
  },
  "history": [
    {
      "step": "validate_customer_details",
      "status": "completed",
      "timestamp": "2024-05-17T12:34:56Z"
    },
    {
      "step": "fetch_customer_records",
      "status": "failed",
      "error": {
        "type": "NetworkError",
        "message": "Connection timed out after 5s"
      },
      "timestamp": "2024-05-17T12:35:10Z"
    }
  ],
  "last_updated": "2024-05-17T12:35:11Z"
}

State is written to a database table agent_executions:

INSERT INTO agent_executions (
  execution_id,
  agent_id,
  current_step,
  state,
  history,
  last_updated
) VALUES (
  'exec-78901',
  'onboarding-agent-v3',
  'generate_contract',
  '{"customer": {...}, "contract": {...}}',
  '[{"step": "...", "status": "completed", ...}]',
  '2024-05-17T12:35:11Z'
) ON CONFLICT (execution_id) DO UPDATE SET
  current_step = EXCLUDED.current_step,
  state = EXCLUDED.state,
  history = EXCLUDED.history,
  last_updated = EXCLUDED.last_updated;

The agent must use UPSERT semantics, not INSERT, to avoid overwriting earlier progress.

Recovery from Failure

When an agent restarts—after a crash, a deployment, or a heartbeat timeout—it resumes from the last known state.

The recovery process is triggered by a resume command:

agent resume --execution-id exec-78901 --from-step generate_contract

The agent:

  1. Fetches the execution record from the store.
  2. Loads the state object into memory.
  3. Sets the current_step to generate_contract.
  4. Re-executes the generate_contract step, possibly with a context that includes the previous state.

If a step fails and is retried, the agent updates the history array with the failure details. On success, it appends a new entry.

If an agent fails during a long-running step (e.g., a model inference call), it may write a checkpoint before beginning the step:

def generate_contract(customer):
    # Write checkpoint before running inference
    checkpoint = {
        "step": "generate_contract",
        "status": "running",
        "started_at": now(),
        "checkpointed_at": now()
    }
    save_checkpoint(execution_id, checkpoint)

    # Run inference
    try:
        contract = model.infer(customer)
    except Exception as e:
        log_error(
            error_type="InferenceFailed",
            message=str(e),
            context={"input": customer, "step": "generate_contract"}
        )
        raise

On restart, the agent checks whether a step is already running. If so, it resumes the step from the checkpoint.

Error Handling in Workflows

In a multi-step workflow, agents may define error handlers at different levels: per-step, per-stage, and global.

A step-level handler responds to failures in a single step:

{
  "step": "fetch_customer_records",
  "error_handler": {
    "on_failure": [
      {
        "error_type": "TimeoutError",
        "action": "retry",
        "delay_ms": 500
      },
      {
        "error_type": "NotFound",
        "action": "fallback",
        "source": "local_cache"
      },
      {
        "error_type": "All",
        "action": "send_alert",
        "to": "[email protected]"
      }
    ]
  }
}

The agent evaluates handlers in order. The All type matches every error, so it runs after all other handlers.

A stage-level handler applies to a group of steps, such as “Customer Validation”:

{
  "stage": "customer_validation",
  "error_handler": {
    "on_failure": [
      {
        "error_type": "ValidationFailed",
        "action": "rollback",
        "steps": ["fetch_customer_records", "validate_customer_details"]
      },
      {
        "error_type": "All",
        "action": "notify",
        "message": "Validation failed for customer cust-12345"
      }
    ]
  }
}

On failure, the agent rolls back to the stage’s starting point, re-executing all steps in the stage.

Global error handlers apply to the entire agent execution:

{
  "global": {
    "error_handler": {
      "on_failure": [
        {
          "error_type": "Critical",
          "action": "pause",
          "reason": "High-latency failure in core pipeline"
        },
        {
          "error_type": "All",
          "action": "send_summary",
          "to": "[email protected]"
        }
      ]
    }
  }
}

Silent Failures and Common Pitfalls

Several failure modes silently degrade agent performance:

The agent must validate the error recovery configuration at startup:

agent validate-config --file agent.yaml

This command checks:

Advanced Patterns

For high-throughput agents, error deduplication prevents repeated alerts for similar failures:

{
  "deduplication": {
    "key": "error_type + message + context.customer_id",
    "window_ms": 300000,
    "max_concurrent": 100
  }
}

Two errors with identical error_type, message, and customer_id are considered duplicates and merged.

Agents may also define error thresholds:

{
  "threshold": {
    "error_count": 5,
    "window_seconds": 60,
    "action": "trigger_downtime_alert"
  }
}

When five errors of a type occur within 60 seconds, the agent triggers a downtime alert.

Finally, agents support error correction via recovery actions:

{
  "recovery": {
    "step": "validate_customer_details",
    "on_error": [
      {
        "error_type": "ValidationFailed",
        "actions": [
          {
            "type": "transform",
            "input": "customer.address",
            "output": "customer.address.normalized",
            "pipeline": [
              "normalize_address",
              "add_postal_code"
            ]
          },
          {
            "type": "update_state",
            "key": "customer.status",
            "value": "needs_manual_review"
          }
        ]
      }
    ]
  }
}

On failure, the agent runs a correction pipeline, updates the state, and re-tries the step.

When the agent resumes, it checks whether a recovery action was applied and includes that information in the context.

This completes the agent error recovery system: from detecting a failure to recovering from it, with mechanisms that survive restarts, network outages, and concurrent executions.

This page was rewritten on 13 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.