Sub topic 13
Handling failures, retries, and timeouts
This chapter assumes you can read basic Python and use Git. It also assumes you have read the earlier chapters on the orchestrator-worker pattern, running subagents in parallel, and collecting their results. Here you will learn how to classify subagent failures, retry the ones worth retrying, and stop a subagent that runs too long. You will also learn how to keep one failure from hiding or ruining the rest of the run.
Why delegation adds failure modes
A single agent that fails stops in front of you. An orchestrator that delegates has more ways to go wrong, and some of them are quiet. Each subagent is a separate run with its own model calls, tool calls, and workspace. Any of these can fail without the others noticing.
The orchestrator must therefore treat every subagent as an unreliable call, much like a network request. It decides, for each outcome, whether to accept it, retry it, reassign it, or report it to the user.
A taxonomy of failures
Different failures need different responses. Sort each one before you decide what to do.
| Failure | Typical cause | Usually retry? |
|---|---|---|
| Transient error | Rate limit, network drop, model service returns a 5xx error | Yes, with backoff |
| Timeout | Subagent loops, waits on a hung command, or the task is too big | Rarely, see below |
| Tool or permission error | The subagent needs a tool it was not given | No. Fix the scoping, then rerun |
| Task failure | Tests still fail, or the subagent says it cannot finish | Only with a changed brief |
| Silent wrong result | Status says success, but the work is incomplete or off-scope | No. Catch it in verification |
| Conflict | Two subagents edited the same file or branch | No. Fix the decomposition or workspace |
The last two rows matter most. A crash is visible. A subagent that reports "done" after editing the wrong file is not. The earlier chapter on verification covers how to catch it. Here, the point is that a status: ok field only means the run finished.
Retries: when and how
Retrying helps only when the cause is likely to disappear on its own. Rate limits and dropped connections qualify. A missing permission or an ambiguous brief does not, and rerunning it just spends tokens to reach the same failure.
Follow these rules for retries:
- Cap the attempts. Two or three is usually enough.
- Wait longer between attempts (exponential backoff), and add a small random delay (jitter). Without jitter, several parallel subagents that were rate limited together will all retry at the same moment and be limited again.
- Retry only errors you have classified as transient. Let everything else fail fast.
- Record every attempt, so you can see later that a "successful" task needed three tries.
Timeouts: bounding the damage
A subagent can run for a long time without failing. It may wait on a test suite that never exits, or keep trying fixes that do not work. Without a timeout, one stuck worker holds the whole parallel batch, because the orchestrator waits for the slowest task.
Set two limits where your runtime allows it:
- A wall-clock limit for the whole subagent run.
- A step or tool-call limit, which stops a subagent that is busy but not making progress.
When a timeout fires, the subagent's workspace may contain half-finished edits. Treat a timed-out task as unverified. A timeout usually means the task was too large or the brief was unclear, so a plain retry tends to time out again. Retry only after you have split the task or tightened the brief.
Putting it together in code
This extends the orchestrator from the earlier chapter. Each task runs under a policy that retries transient errors with backoff and jitter, enforces a timeout, and returns a structured result instead of raising. The run_subagent function is a stand-in for your agent runtime. It simulates a flaky task and a slow task so you can see each path.
import asyncio
import random
from dataclasses import dataclass
@dataclass
class Task:
name: str
brief: str
class TransientError(Exception):
"""A failure that may succeed on retry, such as a rate limit."""
async def run_subagent(task: Task, attempt: int) -> dict:
# Placeholder for a call to your agent runtime.
await asyncio.sleep(0.1)
if task.name == "flaky" and attempt < 3:
raise TransientError("rate limited")
if task.name == "slow":
await asyncio.sleep(10) # simulates a stuck subagent
return {"name": task.name, "status": "ok", "summary": f"finished {task.name}"}
async def run_with_policy(
task: Task,
timeout: float = 1.0,
max_attempts: int = 3,
base_delay: float = 0.2,
) -> dict:
for attempt in range(1, max_attempts + 1):
try:
result = await asyncio.wait_for(run_subagent(task, attempt), timeout)
return {**result, "attempts": attempt}
except asyncio.TimeoutError:
# Do not retry: the workspace may hold partial edits.
return {
"name": task.name,
"status": "timed_out",
"summary": f"no result after {timeout}s",
"attempts": attempt,
}
except TransientError as exc:
if attempt == max_attempts:
return {
"name": task.name,
"status": "failed",
"summary": f"gave up after {attempt} attempts: {exc}",
"attempts": attempt,
}
delay = base_delay * 2 ** (attempt - 1) + random.uniform(0, 0.1)
await asyncio.sleep(delay)
except Exception as exc:
# Not classified as transient: fail fast, do not retry.
return {
"name": task.name,
"status": "failed",
"summary": str(exc),
"attempts": attempt,
}
raise AssertionError("unreachable")
async def orchestrate(tasks: list[Task]) -> list[dict]:
return await asyncio.gather(*(run_with_policy(t) for t in tasks))
if __name__ == "__main__":
tasks = [
Task("steady", "Update the README usage section."),
Task("flaky", "Add unit tests for parse_args."),
Task("slow", "Refactor the logging module."),
]
for result in asyncio.run(orchestrate(tasks)):
print(result)Running it prints one result per task. steady succeeds on attempt 1. flaky succeeds on attempt 3 after two backoff waits. slow returns timed_out after one second.
Two details are worth noting. First, run_with_policy catches its own errors, so gather never sees an exception and one task cannot cancel its siblings. The earlier example reached the same goal with return_exceptions=True. Second, wait_for cancels only the Python coroutine. If your subagent is an external process, you must also terminate that process and clean up its workspace yourself.
Deciding what to do with a failed batch
When a batch finishes, some results are good and some are not. The orchestrator should decide using task dependencies, not a blanket rule.
For independent tasks, keep the successful results and report the failures. For dependent tasks, a failure upstream means the downstream tasks have no valid input. Skip them and say why, so the user does not receive work built on a missing piece.
Common mistakes
- Retrying everything. This wastes money on failures that cannot fix themselves, and can repeat side effects.
- No cap on total cost. Retries multiply token use. Set a budget for the whole run as well as a limit per task.
- Swallowing failures. If the final report says "3 of 3 tasks done" when one needed a manual fix, the user will trust a result they should not. Always list failed and timed-out tasks by name.
- Merging partial work. Do not merge a branch from a timed-out or failed subagent without review. Discard it or inspect it first.
- Retrying with the same brief. If a task failed because the brief was unclear, add what was missing, such as a file path or a finish condition, before you rerun it.
Exercise
Exercise
An orchestrator runs three independent subagents in parallel. One hits a rate limit error, one times out after editing two files, and one reports success. Describe what the orchestrator should do with each, and name one thing it must include in the final report.
Show answer
Retry the rate-limited subagent with exponential backoff and jitter, up to a fixed attempt limit, because the error is transient. Do not blindly retry the timed-out one. Its worktree holds partial edits, so treat it as unverified, inspect or reset the workspace, and rerun only after splitting the task or tightening the brief. Run verification (for example, tests and a diff check against the scope) on the subagent that reported success instead of trusting its status. The final report must name the tasks that failed or timed out and the number of attempts used, so the user knows which work is incomplete.