Applied AI SystemsVol. 14B · Part XIV
0 / 0

Shelves / Applied AI Systems

AS·171

Agent Orchestration

Running multi-step AI workflows reliably, like any other distributed workflow: orchestration as an explicit state machine or graph, sequential, parallel (fan-out/fan-in) and branching steps, retries with backoff, timeouts and idempotency, checkpointing after every step and resumability after crashes or deploys, compensation and the saga pattern for steps with side effects, human-in-the-loop interrupts that pause for days, a working checkpointed graph engine built in Python with SQLite, durable-execution platforms (Temporal and friends) vs agent frameworks, and framework awareness: LangGraph, the OpenAI Agents SDK, Google's Agent Development Kit, Microsoft's Semantic Kernel and its successor Agent Framework, plus Spring AI, LangChain4j and others, with guidance on choosing.

22 topics · ~20 min read · 28-question quiz
Updated Suggest a correction

Start here: making multi-step AI work survive failures

An AI task that takes several steps (plan, call tools, wait for approval, send results) can take seconds, hours or days. Somewhere along the way a process will crash, a server will restart, a tool will time out, or a human will take a weekend to approve. Orchestration is the machinery that keeps such work on track: it records progress, resumes after failures, retries safely and waits for people.

Three ideas

  • The workflow as a graph: steps (nodes) and the transitions between them, including branches, loops and "wait for approval".
  • Checkpoints: after each step, save its result in durable storage. After a crash, skip finished steps and continue from the first unfinished one, instead of starting over (and paying for every model call again).
  • Idempotent side effects: a step that charges money or sends an email might run twice (it crashed after acting but before its checkpoint). Give each effect a key so the second attempt is recognised and does nothing.

What the lab measured

A three-step refund workflow (plan with a model, charge, email) was run 200 times as a real process and killed abruptly at a random point, then restarted:

Approach Double charges Double emails Model calls (minimum 200)
restart from scratch 106 37 377
checkpoint after each step 41 48 250
checkpoints + idempotency keys 0 0 257

Checkpoints cut repeated work, but alone they don't prevent duplicates: a crash between doing something and recording it still repeats it. Only the combination gives effectively exactly-once results.

How deep to go in agent orchestration

Volume 17 defines six mastery levels; for orchestration they look like this:

Level You can…
L1 explain workflows as graphs, checkpoints and idempotent effects
L2 build a multi-step AI workflow with a framework that checkpoints state
L3 explain durable execution, replay, retries, timeouts, compensation and human-in-the-loop waits
L4 debug stuck, duplicated or diverged runs from history and checkpoints
L5 choose between agent frameworks and durable execution platforms for a product
L6 operate workflow platforms with versioning, migrations, backfills and SLOs

Why orchestration

An agent turn that calls a model three times and two tools for half a minute is a small distributed workflow: it can crash midway, a tool can time out, a deploy can restart the process, a human approval can take two days, and a step that already sent an email must not run again. Orchestration makes these runs explicit, observable and recoverable, applying the same ideas as chapter 70's sagas and workflow engines.

Two layers usually coexist:

  • Inner loop: the model choosing tools (chapter 168–169).
  • Outer orchestration: the workflow of steps, branches, approvals and checkpoints around it, sometimes with several agents.

Workflows as state machines and graphs

Represent the process as nodes (steps: an LLM call, a tool, a sub-agent, a human task) and edges (transitions, possibly conditional), operating on a shared, typed state.

start classify answer search web search docs query DB join draft review human approval(pause) send simple revise checkpoint after every node → resume anywhere
An agent workflow as a graph. A classifier routes each request; the research branch fans out to parallel searches and joins their results; a drafting step feeds a reviewer that loops back for revisions; a human approval node pauses the run until someone decides; the send step executes the side effect. State is checkpointed after every node so the run can resume after a crash or a long pause.

Why explicit graphs help: each step is testable in isolation; the control flow is visible (and diagrammable); state transitions are logged; retries, timeouts and checkpoints attach to nodes; and you keep control of where autonomy is allowed (an "agent" node can contain a free tool loop while the outer graph stays deterministic).

Control-flow building blocks

Block Meaning Notes
Sequential A → B → C Gates between steps (validation, policy checks)
Parallel (fan-out/fan-in) Run independent steps concurrently, join results Bound concurrency; decide join semantics: all, first-k, any; handle partial failure
Branching Choose the next node from state (rules, a classifier, an LLM router) Make conditions explicit and logged
Loops Repeat until a condition (evaluator approves, tests pass) Always cap iterations
Sub-workflows A node that is itself a graph or an agent Isolation of state and context
Map Apply a step to each item of a list (documents, rows) Parallel with rate limits and per-item retries

Retries, timeouts and idempotency

  • Per-node retry policies: transient errors (timeouts, 429, 5xx) retried with exponential backoff and jitter; validation errors not retried blindly (route to a repair step instead).
  • Timeouts per node and per run; long human tasks get their own deadlines and escalation.
  • Idempotency: a node may run more than once (retry after a crash between "did the work" and "saved the checkpoint"). Make side-effecting nodes idempotent with idempotency keys derived from (run id, node id), or check-then-act against the external system (chapter 70, 168).
  • Determinism of replays: if you resume by re-executing code, LLM calls give different answers; store each node's output in the checkpoint and reuse it on resume instead of calling the model again.

Checkpointing and resumability

Save state after every node (plus which node runs next) to durable storage. On crash, deploy or pause, load the latest checkpoint and continue. Checkpoints also enable:

  • Human-in-the-loop pauses of arbitrary length (the process needn't stay alive).
  • Time travel / debugging: inspect or fork a run from any earlier step; replay with a changed prompt.
  • Audit: the full history of state transitions.

Compensation

When a later step fails after earlier steps changed the outside world (ticket created, calendar invite sent, payment authorised), you can't roll back a database transaction across those systems. Use compensating actions in reverse order (the saga pattern, chapter 70): cancel the invite, void the authorisation, close the ticket with a note. Record which side effects happened in the state so compensation knows what to undo; make compensations idempotent too; some actions can't be undone (an email was read), so put approvals before them.

Human-in-the-loop

Patterns:

  • Approve / reject a proposed action (send, pay, deploy).
  • Edit then approve (fix the draft email, adjust the refund amount).
  • Provide input the agent lacks (choose between options, supply a missing value).
  • Review samples of autonomous actions after the fact.

Implementation: the workflow reaches an interrupt node, checkpoints, emits a task to a queue/UI, and stops. When a human responds, the response is written into state and the run resumes from the checkpoint. Deadlines and default outcomes (usually "don't act") handle silence.

A checkpointed graph engine

Python
import json, sqlite3, time, uuid, random
from concurrent.futures import ThreadPoolExecutor

class Interrupt(Exception):
    """Raised by a node to pause the run until external input arrives."""
    def __init__(self, request): super().__init__(request); self.request = request

class Graph:
    def __init__(self, db_path=":memory:"):
        self.nodes, self.edges, self.compensations = {}, {}, {}
        self.db = sqlite3.connect(db_path, check_same_thread=False)
        self.db.execute("CREATE TABLE IF NOT EXISTS checkpoints (run TEXT, seq INTEGER, node TEXT, state TEXT, status TEXT)")

    def node(self, name, retries=2, compensate=None):
        def deco(fn):
            self.nodes[name] = (fn, retries)
            if compensate: self.compensations[name] = compensate
            return fn
        return deco

    def edge(self, src, router):                  # router: state -> next node name (or None to finish)
        self.edges[src] = router

    def _save(self, run, seq, node, state, status):
        self.db.execute("INSERT INTO checkpoints VALUES (?,?,?,?,?)", (run, seq, node, json.dumps(state), status))
        self.db.commit()

    def _latest(self, run):
        return self.db.execute("SELECT seq, node, state, status FROM checkpoints WHERE run=? ORDER BY seq DESC LIMIT 1",
                               (run,)).fetchone()

    def run(self, entry, state=None, run_id=None, resume_input=None):
        run_id = run_id or uuid.uuid4().hex[:8]
        latest = self._latest(run_id)
        if latest:                                                    # resume from the last checkpoint
            seq, node, saved, status = latest; state = json.loads(saved)
            if status == "interrupted": state["human_input"] = resume_input
            elif status == "done": node = self.edges.get(node, lambda s: None)(state)
        else:
            seq, node = 0, entry; state = dict(state or {}, _effects=[])
        while node:
            fn, retries = self.nodes[node]
            for attempt in range(retries + 1):
                try:
                    state = fn(state); break
                except Interrupt as i:
                    state["pending_request"] = i.request
                    self._save(run_id, seq + 1, node, state, "interrupted")
                    return run_id, "paused", state
                except Exception as e:
                    if attempt == retries:
                        self._save(run_id, seq + 1, node, state, f"failed: {e}")
                        self._compensate(state)
                        return run_id, "failed", state
                    time.sleep(0.01 * 2 ** attempt)                    # backoff (short for the demo)
            seq += 1; self._save(run_id, seq, node, state, "done")     # checkpoint after every node
            node = self.edges.get(node, lambda s: None)(state)
        return run_id, "completed", state

    def _compensate(self, state):
        for node in reversed(state.get("_effects", [])):               # undo side effects in reverse order
            if node in self.compensations: self.compensations[node](state)

def parallel(*fns, max_workers=4):
    """Fan-out/fan-in node helper: run sub-steps concurrently and merge their outputs into state."""
    def node(state):
        with ThreadPoolExecutor(max_workers) as pool:
            results = list(pool.map(lambda f: f(dict(state)), fns))
        for r in results: state.update(r)
        return state
    return node

A support workflow: classify, research in parallel, draft, get human approval, create a ticket (a side effect with compensation), then notify (which fails and triggers compensation):

Python
g = Graph()
LOG = []

@g.node("classify")
def classify(s):
    s["intent"] = "refund" if "refund" in s["message"].lower() else "question"; return s

g.node("research")(parallel(
    lambda s: {"policy": "Refunds within 30 days of delivery"},          # e.g. RAG over policies
    lambda s: {"order": {"id": "A17", "delivered_days_ago": 12}},        # e.g. order lookup tool
))

@g.node("draft")
def draft(s):
    ok = s["order"]["delivered_days_ago"] <= 30
    s["draft"] = f"Refund for {s['order']['id']} is {'eligible' if ok else 'not eligible'} ({s['policy']})."
    return s

@g.node("approve")
def approve(s):
    if s.get("human_input") is None:
        raise Interrupt({"type": "approval", "draft": s["draft"]})      # pause; resume later with input
    s["approved"] = s.pop("human_input") == "approve"; return s

def cancel_ticket(s): LOG.append(f"compensate: closed ticket {s['ticket']}")

@g.node("create_ticket", compensate=cancel_ticket)
def create_ticket(s):
    s["ticket"] = f"T-{random.randint(1000, 9999)}"; s["_effects"].append("create_ticket")
    LOG.append(f"created {s['ticket']}"); return s

@g.node("notify", retries=1)
def notify(s):
    raise ConnectionError("email service unavailable")

g.edge("classify", lambda s: "research" if s["intent"] == "refund" else None)
g.edge("research", lambda s: "draft")
g.edge("draft", lambda s: "approve")
g.edge("approve", lambda s: "create_ticket" if s["approved"] else None)
g.edge("create_ticket", lambda s: "notify")

run_id, status, state = g.run("classify", {"message": "I want a refund for order A17"})
status, state["pending_request"]["draft"]            # 'paused' at approval: the process could now exit

run_id, status, state = g.run("classify", run_id=run_id, resume_input="approve")   # days later
status, LOG                                          # 'failed' at notify → ticket created then compensated
[r[1:] for r in g.db.execute("SELECT run, seq, node, status FROM checkpoints WHERE run=?", (run_id,))]

Production engines add what this sketch omits: distributed workers and queues, leases so two workers don't run the same step, durable timers, versioned workflow definitions, visibility UIs, and strict at-least-once semantics with idempotency.

Durable execution platforms vs agent frameworks

Durable execution (Temporal, Restate, DBOS, AWS Step Functions, Azure Durable Functions, Cadence) Agent frameworks (LangGraph, Agents SDKs, ADK, Agent Framework)
Focus Reliable long-running workflows: retries, timers, state, exactly-once-ish semantics via event history LLM-specific abstractions: agents, tools, handoffs, memory, streaming, tracing
Strengths Battle-tested failure handling, workflows lasting months, multi-language SDKs (Go, Java, TypeScript, Python, .NET) Fast development of agent logic; model/tool integrations; built-in human-in-the-loop and checkpointers (varies)
Combine? Commonly: durable workflows orchestrate steps; each step may run an agent loop. Some frameworks integrate with Temporal directly

For short, interactive agents a framework's checkpointer is enough; for business processes spanning hours to weeks with external side effects, run them on a durable execution engine.

Framework awareness

Framework Model Notes
LangGraph (LangChain; 1.x since late 2025) Explicit state graphs: typed state, nodes, conditional edges; checkpointers (in-memory, SQLite, Postgres) per thread; interrupts for human-in-the-loop; time travel; streaming Python and JavaScript; LangGraph Platform for deployment; LangSmith for tracing
OpenAI Agents SDK Agents (instructions + tools), handoffs between agents, guardrails (input/output validation running alongside), sessions for memory, built-in tracing Python and TypeScript; lightweight; works with other model providers through adapters
Google Agent Development Kit (ADK) LLM agents plus workflow agents (Sequential, Parallel, Loop), multi-agent hierarchies, session state and memory services, evaluation tooling Python and Java (and others); integrates with Vertex AI Agent Engine; A2A protocol for agent-to-agent communication
Semantic Kernel → Microsoft Agent Framework Semantic Kernel offered kernels, plugins (functions), planners and agent abstractions; Microsoft Agent Framework (successor to Semantic Kernel and AutoGen) adds graph-based workflows, checkpointing, human-in-the-loop and multi-agent patterns .NET and Python; Azure AI Foundry integration
Spring AI (2.x) ChatClient, advisors, tools, memory, MCP; workflows built with ordinary Spring code or patterns Java/Kotlin; fits Spring Boot services
LangChain4j AI services, tools, memory, RAG, agentic workflows Java
Others CrewAI (role-based crews), LlamaIndex Workflows (event-driven), Pydantic AI (typed agents), Mastra (TypeScript), AutoGen (research; folded into Agent Framework), Haystack pipelines
# LangGraph: typed state, nodes, conditional edges, a checkpointer, and an interrupt for approval
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.sqlite import SqliteSaver
from langgraph.types import interrupt, Command

class S(TypedDict, total=False):
    message: str; draft: str; approved: bool

def draft(s: S): return {"draft": f"Proposed reply to: {s['message']}"}
def approval(s: S): return {"approved": interrupt({"draft": s["draft"]}) == "approve"}   # pauses the thread
def send(s: S): return {}

b = StateGraph(S)
b.add_node("draft", draft); b.add_node("approval", approval); b.add_node("send", send)
b.add_edge(START, "draft"); b.add_edge("draft", "approval")
b.add_conditional_edges("approval", lambda s: "send" if s["approved"] else END)
b.add_edge("send", END)
with SqliteSaver.from_conn_string("checkpoints.db") as saver:
    app = b.compile(checkpointer=saver)
    cfg = {"configurable": {"thread_id": "ticket-981"}}
    app.invoke({"message": "Refund A17"}, cfg)                 # runs until the interrupt
    app.invoke(Command(resume="approve"), cfg)                 # later: resume with the human's decision

Framework APIs evolve quickly; the concepts (state, nodes, edges, checkpoints, interrupts, handoffs, guardrails, tracing) are what to learn, and the current documentation is where to check exact signatures.

Choosing

  1. Can plain code do it? A function calling a model and two tools in sequence doesn't need a framework.
  2. Need durability, long pauses, many side effects? Use a durable execution engine (or a framework with a production checkpointer) and design compensation.
  3. Complex agent logic, branching, human-in-the-loop, streaming UI? A graph framework (LangGraph, Agent Framework workflows, ADK workflow agents) keeps it explicit.
  4. Multi-agent hand-offs with light orchestration: an agents SDK.
  5. Your platform: Java/Spring teams lean on Spring AI or LangChain4j (plus Temporal); .NET on Agent Framework; TypeScript on the Vercel AI SDK, Mastra or LangGraph.js.
  6. Whatever you choose: tracing (chapter 177), evaluations (chapter 175), bounded loops, and idempotent side effects.

Lab: crashing a workflow 200 times

Setup. A ~40-line workflow engine (wf.py) with three steps: plan (stands in for a model call), charge (inserts a refund charge) and email (inserts a sent email), with state in SQLite. A driver runs it as a real child process 200 times per mode; each run is killed with os._exit(9) at one of eight instrumented points chosen at random (before or after each effect, after each step), and a supervisor restarts it until it completes. Crash points are chosen deliberately rather than by timing a kill -9, so every interesting gap gets hit; the effect on durable state is the same as a kill.

Experiment 1: three recovery strategies

Mode Crashes Double charges Double emails Missing charges Steps executed (min 600) Model calls (min 200)
none: restart from the beginning 177 106 37 0 962 377
ckpt: save each step's output; skip saved steps on restart 183 41 48 0 783 250
ckpt + idem: checkpoints and an idempotency key per effect 184 0 0 0 784 257

(Crash counts differ slightly because one in nine chosen points lies beyond the run's last instrumented point.)

What happened in each mode

  • No checkpoints: every crash after the charge led to a second charge on restart, and every model call before the crash was paid for again (377 calls for 200 tasks).
  • Checkpoints removed most repeated work: a crash after a step's checkpoint resumes at the next step. But two gaps remain per effect: crash after the side effect but before the checkpoint, and the restarted step does it again. 41 double charges and 48 double emails came from exactly those gaps.
  • Checkpoints + idempotency keys closed the gap: the key run:charge is unique in the charges table, so the repeat insert fails harmlessly and the step returns as if it had succeeded. The same pattern works against external APIs that accept idempotency keys (most payment APIs do); for those that don't, check-then-act against the external system or a transactional outbox is needed.

This is the core of what durable execution platforms (Temporal, Restate, DBOS, AWS Step Functions, Azure Durable Functions) and agent frameworks with checkpointers (LangGraph and others) provide: persisted step results, deterministic replay, retries with back-off, timers and signals for human input. None of them removes the need for idempotent side effects; they make "at least once" cheap, and your keys make it "effectively once".

Experiment 2: what a wait costs

Because state lives in SQLite, nothing needs to stay running between steps. The crash-and-restart runs above exercised exactly the mechanism a long wait uses: a new process with the same run ID read the completed steps from their checkpoints (including the plan, so the model wasn't called again) and executed only what was unfinished: 784 steps for 200 tasks with 184 crashes, versus 962 without checkpoints. An approval step is the same thing done on purpose: record "waiting", exit, and resume when the decision arrives, whether that's a minute or a week later.

Try it yourself

  1. Add a fourth step that fails permanently 10% of the time and implement compensation: refund the charge and send an apology.
  2. Add a human-approval step: the engine records "waiting", exits, and a separate command delivers the decision.
  3. Change the plan step's code between a crash and the resume. What goes wrong, and how do workflow-versioning features handle it?
  4. Run 20 concurrent workers on the same run ID and make sure only one advances it (hint: a lease row with an expiry).

Revision sheet: agent orchestration

Key ideas

  • Orchestration runs multi-step AI work as an explicit state machine/graph: sequence, branch, loop, parallel fan-out/fan-in, wait.
  • Checkpointing persists step outputs and state so runs resume after crashes, deploys and long waits without repeating paid model calls.
  • Idempotent side effects (keys, upserts, outbox) close the gap between acting and recording.
  • Retries with back-off and jitter, per-step timeouts, overall deadlines, cancellation.
  • Compensation (sagas) undoes earlier effects when a later step fails permanently.
  • Human-in-the-loop: approval nodes, interrupts, edits to state, then resume.
  • Durable execution platforms (Temporal, Restate, DBOS, Step Functions) vs agent frameworks (LangGraph, CrewAI, OpenAI Agents SDK, Google ADK, Microsoft Agent Framework): choose by durability needs, team skills, and determinism constraints.
  • Version workflows; code changes must not corrupt in-flight runs.

Numbers to remember

  • Lab: 200 runs with crashes: no checkpoints → 106 double charges, 377 model calls; checkpoints → 41 double charges, 250 calls; + idempotency → 0 duplicates.

Pitfalls

  • Treating a checkpoint as exactly-once.
  • Non-deterministic code inside replayed workflow logic (time, random, direct I/O).
  • Keeping a process (and a GPU) alive while waiting for humans.
  • Unbounded retries on non-retryable errors.
  • Changing workflow code without versioning in-flight runs.

Glossary

  • Durable execution: execution whose progress survives process failure.
  • Checkpoint: persisted state after a step.
  • Replay: re-running workflow code against recorded history to rebuild state.
  • Saga / compensation: a sequence of steps with undo actions.
  • Interrupt: pausing a graph for external input.