Agent Orchestration
Independent educational resource, not an official Anthropic course. Facts about the API, prices and limits were checked against Anthropic's documentation on 15 November 2026 and the code was run against a local mock of the API, not the live service. Check the linked official pages before relying on a number, and test with your own key.
An agent that works in a demo and an agent that runs every day are separated by plumbing: what happens when the process is killed halfway, when the API returns a 429, when the same job is started twice, or when someone asks what happened last Tuesday. That plumbing is orchestration. It's not glamorous, and it's usually where reliability comes from. This lesson builds a small, tested job runner and then compares it, honestly, with the managed options Anthropic offers.
What you'll learn
- Breaking a job into named steps whose results are saved.
- Resuming after a crash without repeating finished work.
- Retrying transient errors with backoff, and not retrying the rest.
- An event log you can read afterwards.
- Where the Agent SDK and Managed Agents fit, and when to build your own.
Before you start
A job is named steps with saved results
The idea is small: give each step a name, store its output when it finishes, and on a re-run skip any step that is already done. Here's the whole thing, using SQLite so you can try it with no setup (use your real database in production):
import json
import sqlite3
import time
import uuid
from typing import Callable
class TransientError(Exception):
"""Worth retrying: a timeout, a 429, a 5xx. Anything else fails the step straight away."""
class JobStore:
def __init__(self, path: str = ":memory:"):
self.db = sqlite3.connect(path, check_same_thread=False)
self.db.execute("""CREATE TABLE IF NOT EXISTS steps (job_id TEXT, name TEXT, status TEXT, output TEXT, attempts INT,
error TEXT, PRIMARY KEY (job_id, name))""")
self.db.execute("CREATE TABLE IF NOT EXISTS events (job_id TEXT, at REAL, event TEXT)")
def log(self, job_id: str, event: str):
self.db.execute("INSERT INTO events VALUES (?,?,?)", (job_id, time.time(), event)); self.db.commit()
def done(self, job_id: str, name: str):
row = self.db.execute("SELECT output FROM steps WHERE job_id=? AND name=? AND status='done'", (job_id, name)).fetchone()
return (True, json.loads(row[0])) if row else (False, None)
def save(self, job_id: str, name: str, status: str, output=None, attempts: int = 0, error: str = ""):
self.db.execute("INSERT OR REPLACE INTO steps VALUES (?,?,?,?,?,?)", (job_id, name, status, json.dumps(output), attempts, error))
self.db.commit()
def events(self, job_id: str) -> list[str]:
return [r[0] for r in self.db.execute("SELECT event FROM events WHERE job_id=? ORDER BY rowid", (job_id,))]
def run_job(store: JobStore, job_id: str, steps: list[tuple[str, Callable[[dict], object]]],
retries: int = 3, sleep: Callable[[float], None] = time.sleep) -> dict:
"""Run named steps in order. Finished steps are skipped on a re-run, so a crash or a deploy never repeats work
that already happened. Each step gets the outputs so far and must return JSON-serialisable data."""
outputs: dict = {}
for name, fn in steps:
finished, out = store.done(job_id, name)
if finished:
outputs[name] = out
store.log(job_id, f"skip {name} (already done)")
continue
for attempt in range(1, retries + 1):
try:
out = fn(dict(outputs))
store.save(job_id, name, "done", out, attempt)
store.log(job_id, f"done {name}")
outputs[name] = out
break
except TransientError as e:
store.save(job_id, name, "retrying", None, attempt, str(e))
store.log(job_id, f"retry {name} attempt {attempt}: {e}")
if attempt == retries:
store.save(job_id, name, "failed", None, attempt, str(e))
raise
sleep(min(2 ** attempt, 30) * 0.5)
except Exception as e: # noqa: BLE001
store.save(job_id, name, "failed", None, attempt, f"{type(e).__name__}: {e}")
store.log(job_id, f"failed {name}: {type(e).__name__}")
raise
return outputs
Three rules are baked in:
- Saved outputs make restarts safe. If a deploy kills the worker after step one, the next run reads step one's saved output and carries on at step two. Our test does exactly that: it crashes in the second step, runs again, and checks that the first step ran only once.
- Only transient errors retry. A timeout, a 429 or a 5xx might go away. A
ValueError from bad input won't, and retrying it just repeats the failure. We wrap the first kind in TransientError and let everything else fail on the first attempt. Retries wait longer each time (1s, then 2s, then 4s, capped at 15s), and the sleep function is passed in so tests don't actually wait.
- Everything leaves an event. The
events table is a plain list of what happened: done, skipped, retried, failed. It's the first thing you'll open when something goes wrong.
The catch: steps must be safe to repeat
Saving outputs only protects steps that finished. If the process dies after sending an email but before saving the step, a re-run sends it again. Two common fixes:
- Make the step idempotent: use an idempotency key, or check "was this already sent?" before sending.
- Split the step in two, one that decides and one that performs, and save in between.
Treat anything that changes the outside world as suspect until you've asked "what if this runs twice?"
Wiring a model step in
A model call is just another step. Convert API failures that are worth retrying into TransientError:
import anthropic
from jobs import JobStore, TransientError, run_job
def draft_step(done):
try:
run = agent.run(done["extract"]["question"])
except (anthropic.RateLimitError, anthropic.APITimeoutError, anthropic.InternalServerError) as e:
raise TransientError(type(e).__name__) from e
return {"text": run.text, "status": run.status, "tokens": run.state["tokens"]}
store = JobStore("jobs.sqlite3")
outputs = run_job(store, job_id="ticket-1042", steps=[("extract", extract_step), ("draft", draft_step)])
The Anthropic SDK already retries some failures itself (see lesson 2.7), so don't stack many layers of retries on top of each other; two layers each trying three times is nine requests.
Tracing
For every job, you want to answer: what ran, in what order, how long, how many tokens and why it stopped. Save the agent's trace and token count as part of the step output, as the example above does. When a customer says "your assistant said something odd", you look up the job id, read the events, and see the exact tool calls.
Build it, or use a managed option?
Anthropic offers more than the raw API. As of the date we checked the documentation:
- The Agent SDK gives you the agent loop, tools and context management that power Claude Code as a library, so you don't write the loop yourself.
- Managed Agents is a hosted option where Anthropic runs the agent in a managed environment. It was in beta when we looked, and beta features can change, so read the current page before you commit.
- Building your own, as in this module, gives you full control and a clear understanding, at the price of owning the reliability work above.
A reasonable approach: build a small one yourself first so you know what the loop is doing, then decide whether a managed option saves you time or removes control you need. Your choice should depend on how much control, data location and cost visibility your project requires, so check the current pricing and terms for each.
Real-world use case (illustrative scenario)
This scenario is an invented example to show how the ideas fit together. It is not a case study and its details are not measured results.
A shop runs a nightly job that reads the day's support emails, drafts replies and queues them for review. One night a deploy restarts the worker at email 140 of 300. With saved step outputs, the job resumes at email 140 instead of starting over, which avoids paying for 139 model runs twice and avoids drafting duplicates. The event log shows the skip lines, and the morning reviewer sees one draft per email.
Mistakes to avoid
- Retrying everything, including errors that can't improve.
- Steps that change the world and aren't safe to run twice.
- Nested retry layers that multiply requests.
- Saving no trace, so a failure leaves nothing to investigate.
- Choosing a managed service before you know what you need from it.
Security notes
Saved outputs and traces may contain customer data. Store them with the same care as the data itself, set a retention period and keep secrets out of them. If several tenants share the system, scope the job id and its stored data by tenant.
Cost and speed
Resumability saves money: finished steps don't re-run. Retries cost something too, so cap them. Log tokens per step so you can see which step dominates the bill.
Key takeaways
- Break work into named steps and save each result.
- Re-runs skip finished steps; make steps that touch the world safe to repeat.
- Retry only transient errors, with backoff and a limit.
- Keep an event log and a trace for every job.
- Understand the loop by building one; then judge managed options on their current terms.
Lesson recap: save each step, skip finished steps on re-run, retry only transient errors, and keep a trace.
Quick quiz
- What does saving each step's output let you do after a crash?
- Which errors should be retried?
- Why can saved outputs still leave a step running twice?
- Why avoid stacking several retry layers?
- What's one reason to try building a small loop yourself before adopting a managed service?
Answers and explanations
- Resume from the first unfinished step instead of repeating completed work and its cost.
- Transient ones, such as timeouts, rate limits and server errors. Bad input or permission errors won't improve by waiting.
- A crash after the side effect but before the save means the step looks unfinished. Make such steps idempotent or split them.
- Each layer multiplies attempts: three retries inside three retries is nine requests.
- You learn what the loop does and what you actually need to control, which makes the choice better informed.
Official references and further reading
Related tutorials