Numerical examples are illustrative unless explicitly sourced.
Error handling means finding out what went wrong and deciding what to do next. Recovery means getting the task back to a known state. If a refund request times out, check whether the payment service already sent the refund before retrying. If the service denies permission, stop and tell the user what blocked the action.
Find where the request failed, stop further work if its effects are unclear, then check the recorded outcome before resuming.
Learn to classify a failure before choosing a recovery
An agent is software, so ordinary exception handling remains necessary. What changes is that successful execution of a function is not always successful completion of the user's task. A search tool can return HTTP 200 with no useful evidence; a payment call can time out after charging; a model can repeatedly call a real tool with the wrong argument.
Separate four questions. Did the request reach the service? Did the operation complete? Was the result valid for the task? Did the overall task achieve its intended outcome? Different evidence answers each question. A try/catch block can catch a network exception, but it cannot prove that the returned policy applies to this customer.
Classify errors into categories with explicit responses: transient transport failure, invalid input or schema, authorization denial, invalid business result, uncertain side effect, and lack of progress. Some can be retried, some need corrected input, some must stop, and some require external reconciliation. Sending every failure back to the model with “try harder” ignores those distinctions.
Follow a failed booking attempt
The agent proposes a date in the wrong format. The executor rejects the schema before making a reservation and returns a concise typed error showing the accepted format. The agent can repair the argument within a bounded correction budget. No reservation was attempted, so this is different from a timeout after submission.
On the next attempt, the booking service reports that the room is unavailable. This is a valid business outcome, not a broken API. The agent may search alternatives within the user's constraints or ask for a changed requirement. It should not repeat the same unavailable booking indefinitely.
Now suppose the reservation request times out. It may have succeeded. Preserve the same operation identity and query the authoritative reservation state or use the receiver's deduplicating retry contract. Do not create a new reservation just because the receipt was not received. If the outcome remains unknown, pause for reconciliation.
A useful tool result separates status and evidence:
status: rejected | completed | unknown
error_class: invalid_argument | unavailable | permission_denied | transient
operation_id: stable identity when a write may have been attempted
retry_allowed: policy decision with conditions, not model permission
evidence: receipt or authoritative lookup reference when available
This is a conceptual contract; actual implementations should expose only the fields and data the caller is allowed to see.
Recover the plan without losing control
Model-assisted correction can use an actionable error to choose a different permitted plan. Give it enough information to fix the problem without leaking credentials or treating untrusted error text as governing instructions. Enforce attempt, time, and spending budgets outside the model.
Detect loops by observing repeated actions and lack of meaningful state change, not only identical strings. Two differently worded searches can repeat the same failed strategy. Conversely, a repeated status query can be legitimate polling. Define progress in terms of the task and use a bounded wait or handoff when it stalls.
Checkpoints preserve recorded state for resumption. They do not reverse real-world effects. A recovery plan should say which work can repeat, which results can be reused, and which outcomes need verification. Remember classify, contain, correct, verify: the model can help correct a plan, while the application remains responsible for containment and verification.
One failure, several possible meanings
A tool says “request failed.” Before asking the model to try harder, ask what happened. An invalid order ID is different from an unavailable server, and neither establishes whether a payment committed.
| Failure | First response | Avoid |
|---|---|---|
| Invalid schema or missing field | Validate; allow a limited repair with a clear error | Repeatedly sending the same malformed request |
| Authentication/authorization denied | Stop and resolve identity or permission through the application | Asking the agent to find a bypass |
| Rate limit or temporary outage | Backoff with jitter within a shared retry/deadline budget | Nested retries multiplying load |
| Read returned incomplete or stale data | Check version, completeness, and authoritative source | Equating HTTP 200 with correct data |
| Write timed out | Mark outcome unknown and reconcile | Retrying with a new operation ID |
| Valid tool calls but no progress | Detect repeats; stop, change strategy, or hand off | An unlimited self-correction loop |
Make the recovery decision explicit
Read diagram source
flowchart TD
F[Failed or questionable outcome] --> C[Classify using execution evidence]
C -->|Invalid arguments| A[Bounded correction and validation]
C -->|Temporary safe-to-retry failure| R[Deadline-aware backoff]
C -->|Denied operation| S[Stop action and report required authority]
C -->|Uncertain external write| Q[Reconcile stable operation ID]
C -->|Valid output but no progress| P[Revise strategy within budget]
A --> V[Verify resulting business outcome]
R --> V
Q --> V
P --> V
V -->|Known complete| D[Record completion]
V -->|Still unresolved| H[Return partial result or operator handoff]
Store job ID, input version, completed results, operation IDs, pending approvals, attempt count, deadline and error category in a durable backend if recovery must survive a restart. The sequence is:
- Preserve the last known state and any possible side effect.
- Choose recovery from the error semantics.
- Check remaining authority, time and resource budget.
- Perform the bounded recovery step.
- Verify and record its outcome, including uncertainty.
Prevent retries from amplifying an outage
Choose one layer to own retries where practical. If four nested layers each allow three attempts, one top-level request can trigger 3⁴ = 81 calls to the failing dependency. “Three attempts” includes the original call; “three retries” would mean four attempts per layer.
For an eligible read, an example exponential-backoff policy samples a delay uniformly between zero and min(cap, base × 2^retryIndex). With a 200 ms base, the first three upper bounds are 200, 400 and 800 ms. These are chosen example values, not a standard for every service. Honor applicable server retry guidance and stop when the remaining deadline cannot accommodate another attempt. Check SDK defaults so hidden retries do not exceed the shared budget.
A circuit breaker can temporarily stop calls to an unhealthy dependency; a concurrency limit contains in-flight work; a retry budget limits extra load. These address different problems. Scope controls to the relevant dependency or tenant, and define recovery probes so one failing route does not unnecessarily disable unrelated work. A fallback must preserve the required semantics: cached availability is not proof that a room can still be booked.
Retries of writes require an established idempotency or reconciliation contract, regardless of the backoff policy. See Temporal activity retry and idempotency semantics.
What self-correction can and cannot do
A model can propose a better search query or correct a malformed argument. Give it the relevant, sanitized error and remaining budget. Do not feed arbitrary raw exception text back as trusted instructions: errors can contain secrets or attacker-controlled content.
A verifier model is an additional signal. For a financial total, recompute arithmetic; for a reservation, query the booking system; for an access check, call the authorization service. A fluent explanation is not verification.
Checkpoint restoration rewinds application state. It does not undo emails, payments, or database writes. A compensating action is a separate operation with its own authorization, idempotency, and failure handling. Temporal activity semantics.
Prevent the endless loop
Use several independent limits: wall-clock deadline, maximum attempts per operation, total tool calls, token/cost budget, and lack-of-progress detection. Count equivalent normalized requests, not only identical strings. A changed search spelling can still be the same failed strategy.
Set the step and time budgets for the expected work. A two-minute support task and a multi-hour research job can need different limits. Bound parallel work too: stopping the parent must propagate cancellation where possible, while already-committed effects still need reconciliation.
The manager decision
For a low-risk answer, return a partial result with clear missing information. For an uncertain irreversible action, pause. Staff the exception queue and give the operator the intended action, actual evidence, attempted operations, known effects, and safe next choices. Do not hand over only a huge chat transcript.
Track first-attempt success, recovery success, unresolved outcomes, duplicate effects, manual minutes, and total cost per successful task. If most first attempts fail but retries succeed, investigate which dependency fails first and why. Overall completion can hide the delay and extra calls.
Practice without looking
A verifier approves a wrong total—what changes? Add deterministic arithmetic and source reconciliation; evaluate the verifier against labeled mistakes.
The worker restarts after sending an email—what now? Inspect the provider's delivery/operation record and deduplication contract. A local checkpoint cannot unsend it.
The agent keeps trying a denied tool—what stops it? The tool gateway rejects it regardless of model output, and the orchestrator ends the attempt under policy.
See Durable execution for the full crash-window walkthrough and LangGraph persistence for persistence boundaries.
Interview questions with developed answers
Q1: Why is try/catch alone insufficient for agent recovery?
Program exceptions tell you where code raised an error. A tool can return an empty search result or an incorrect invoice total without raising one. Give each outcome a category and choose what happens next. Repair invalid arguments when possible, stop denied actions, and check whether an uncertain write took effect. Cap recovery by time, attempts, and cost.
Follow-up: Which errors should never simply be retried unchanged? Invalid inputs, authorization denials, and uncertain writes without a safe receiver contract.
Q2: How do you handle silent failures where a tool returns 200 but the result is wrong?
- Check field types, identifiers, ranges, and business rules. For example, recompute an invoice total from verified line items.
- For a write, check the receipt or the record in the service that performed it.
- Use source evidence or a calibrated reviewer for judgments that code cannot settle. Record the failure category and add a regression case for the actual outcome.
Follow-up: How would you validate an invoice total? Recompute it from verified line items, taxes, and discounts under the applicable rules.
Q3: How do you stop an agent from looping?
- Set limits on steps, time, tokens, and tool calls in the application.
- Inspect repeated calls and their results. If a missing field or an unclear tool error keeps sending the agent back to the same step, repair the input or choose another permitted path within the budget.
- If progress stops, return completed work and the blocker, or hand the task to someone who can resolve it.
Follow-up: Can repetition be valid? Yes, for bounded polling or retries under a defined policy.
Q4: What should happen after a payment timeout?
- Mark the payment outcome as unknown and save the operation ID. Prevent other workers from issuing a new payment for the same task.
- Look up the operation at the payment service. Retry with the same key only if the service documents how it handles duplicate requests.
- If you find the payment, recover its receipt. If the outcome stays uncertain, pause for reconciliation and tell the user that payment status is unresolved.
Follow-up: Does cancelling the task prove no payment occurred? No; the remote effect may already have committed.
Q5: What information makes a human handoff effective?
Give an authorized reviewer the task goal, constraints, evidence links, and the actions that finished or still have unknown outcomes. Include each operation ID so the reviewer can check the external record before retrying. List recovery steps already attempted, the decision needed next, and who owns the queue and deadline.
Follow-up: How do you measure handoff quality? Resolution time, avoidable rework, duplicate actions, and reviewer feedback on missing information.
60-second interview answer
- Classify the result. Retry temporary read failures within a limit, correct invalid requests, and stop denied actions.
- If a payment times out, preserve the operation ID and check the payment service before attempting it again.
- Save completed work. If recovery cannot finish within its budget, hand off the known results, unresolved actions, and decision needed next.