Multi-agent systems as state machines

Treating a multi-agent system as an explicit state machine makes its states, transitions, retries and termination visible and testable. A worked state table and a small runnable checker.

A multi-agent system is a set of model calls that hand work to each other. Whether or not the framework says so, it already has states (who holds the work and what has been done), transitions (who gets it next) and an end condition (or the lack of one). Writing those down as an explicit state machine turns several common failure modes into things you can see in a table and test in code.

The failures are well documented. A study of multi-agent LLM systems by Cemri and colleagues built a taxonomy of 14 failure modes grouped into three categories: system design issues, inter-agent misalignment and task verification [5]. Many of the cases a practitioner meets, such as agents repeating each other, a reviewer that never approves, or a run that stops early with an unverified result, are questions a state table forces you to answer before the first run.

What "explicit" means here

There are two ways to let agents coordinate. In the first, a model decides at each step which agent speaks next and when the job is finished. In the second, code holds a finite set of named states and the allowed transitions between them; models do the work inside a state and report an outcome, and code decides where that outcome leads.

In our judgement, the second approach is the right one for any system whose output matters. The model still exercises judgement (it decides that research is insufficient, or that a draft needs revision) but it chooses among transitions that already exist. It cannot invent a new path, skip the reviewer, or keep going after a budget is spent.

Existing tools already use this vocabulary. The Amazon States Language requires a state machine to have a States object and a StartAt field naming exactly one of them; every non-terminal state other than a Choice state must have a Next field; and terminal states are those with "End": true or of type Succeed or Fail [1]. LangGraph builds agent graphs from a typed State, nodes that read state and return updates, and edges, with conditional edges whose routing function returns the name of the next node, and a special END node marking termination [3]. Either gives you a structure to hang agents on. Neither makes you decide how loops are bounded, what the budgets are or where failures go; those decisions stay with the designer.

A worked state table

Consider an illustrative research-and-report system with four agents: a planner that turns a request into research questions, researchers that answer them with search tools, a writer that drafts a report, and a reviewer that checks the draft against the questions and sources. A person approves the final report before it is released.

StateOwnerEntry actionAllowed outcomes and next stateRetry on technical errorLoop capTimeout
RECEIVEDCodeValidate request, create run recordok: PLANNINGn/an/an/a
PLANNINGPlannerProduce 3 to 8 research questions as JSONok: RESEARCHING; invalid or error: FAILED3 attempts, backoffn/a2 min
RESEARCHINGResearchers (parallel)One worker per question, results appended to stateok: DRAFTING; insufficient: PLANNING; error: FAILEDPer worker, 3 attemptsRe-plan at most once15 min
DRAFTINGWriterWrite report from research results onlyok: REVIEWING; error: FAILED3 attemptsn/a5 min
REVIEWINGReviewerCheck each claim against a cited resultpass: AWAITING_APPROVAL; revise: DRAFTING; error: FAILED3 attemptsRevise at most twice5 min
AWAITING_APPROVALHumanShow report and review notesapprove: DONE; reject: CANCELLED; edit: REVIEWINGn/an/a3 days
DONECodePublish internally, close runterminal
FAILEDCodeRecord error, notify ownerterminal
CANCELLEDCodeRecord reasonterminal
BUDGET_EXHAUSTEDCodeRecord which budget, keep partial workterminal

The numbers are placeholders, chosen to make the example concrete. What matters is that each cell is filled in. An "error" outcome means a technical error that is still failing after the state's retries. Three things in the table are easy to leave out of an implicit design.

Every backward edge has a cap. The reviewer-writer loop is the classic place for a multi-agent system to spin. "Revise at most twice" turns an open loop into a bounded one; on the third request for revision the run goes to BUDGET_EXHAUSTED with the latest draft and the reviewer's notes, and a person decides what to do.

Failure has its own terminal states. FAILED, CANCELLED and BUDGET_EXHAUSTED are distinct because they need different follow-up: a defect to fix, a decision to respect, or a limit to reconsider.

The human step is a state, with a timeout. Approval sits inside the machine, so each of its outcomes leads to a defined next state. The design of that step is covered in designing human approval into enterprise AI agents.

Shared state: what each agent may write

Agents coordinate through state, so the state schema is the contract between them. LangGraph makes this concrete: each key in the state has its own reducer, and without one an update replaces the existing value [3]. Choosing reducers is choosing what concurrent agents are allowed to do to each other's work.

A workable layout for the example:

KeyWritten byUpdate rule
requestCode at RECEIVEDSet once, read-only after
questionsPlannerReplace (a re-plan supersedes the old list)
findingsResearchersAppend, keyed by question id
draftWriterReplace; previous versions kept in history
review_notesReviewerAppend
countersCode onlyIncrement
statusCode onlySet by the transition function

Two rules follow. Agents never write status or counters; only the transition function does. And parallel workers append rather than replace, so that two researchers finishing at once cannot overwrite each other.

Retries: technical errors and bad outputs are different

A state can fail in two ways, and they need different handling.

A technical error is a timeout, a rate limit or a network failure. The same call may succeed if repeated. Here the established retry patterns apply directly. Step Functions is a useful reference: a retrier matches error names, waits IntervalSeconds (default 1) before the first retry, multiplies the wait by BackoffRate (default 2.0) and stops after MaxAttempts (default 3); MaxDelaySeconds caps the wait, and JitterStrategy: FULL randomises it to spread out simultaneous retries [2]. With an interval of 2 seconds, a rate of 2 and three attempts, the waits are 2, 4 and 8 seconds [2]. When retries run out, a catcher routes the run to a named fallback state [2].

A bad output is a response that arrived but failed validation: malformed JSON, a plan with zero questions, a draft citing a source that is not in findings. Repeating the identical call is a weak remedy because the model will often produce a similar answer. A better pattern is a bounded repair: send the validation error back with the request, allow one or two repair attempts, and then take the state's failure transition. Count repairs separately from technical retries so that one cannot consume the other's budget.

Retries also have a side-effect problem. If a state sends an email and then times out before recording success, a retry sends it twice. Any state with external side effects needs an idempotency key derived from the run and state, or the side effect has to be moved into a separate state that runs once.

Termination: three layers

A run should stop for one of three reasons, and all three should be enforced by code.

  1. Reaching a terminal state in the table: the normal ending, success or failure.
  2. Exhausting a loop cap on a backward edge, as above.
  3. Exhausting a global budget: steps, wall-clock time or tokens.

The frameworks provide the third layer in different forms. LangGraph's recursion limit sets the maximum number of super-steps in one execution and raises GraphRecursionError when reached [3]; its default is high, so set an explicit limit suited to your graph. AutoGen's AgentChat offers termination conditions including a maximum message count, a token-usage limit, a timeout and an external stop signal, which can be combined with | (stop when either condition holds) or & (stop only when both do) [4]. The Amazon States Language has a top-level TimeoutSeconds, after which the machine fails with States.Timeout [1].

Budgets matter for cost as well as safety. Anthropic reports that, in its data, multi-agent systems use about 15 times more tokens than chats, and that for economic viability they need tasks valuable enough to pay for the extra performance [6]. A token budget in the state machine turns that from a surprise on an invoice into a designed limit.

Checkpoints and resumption

Long runs fail partway through. Anthropic describes building its research system so that it "can resume from where the agent was when the errors occurred", combining the model's adaptability with deterministic safeguards such as retry logic and regular checkpoints [6]. LangGraph's checkpointers persist a thread's graph state as checkpoints, which its documentation lists as the basis for human-in-the-loop workflows and fault tolerance [7].

An explicit state machine makes resumption straightforward: persist the state name, the state object and the counters after every transition. On restart, load them and continue from the recorded state. Without named states, "resume" usually means re-running the whole conversation and hoping it takes the same path, which, given non-deterministic model output, it may not.

A checker you can run

Because the transitions are data, the structure can be tested without calling a model. The snippet below is plain Python, with no dependencies. It checks that every reachable non-terminal state has an exit and can reach a terminal state, and it enforces caps on backward edges.

from collections import deque

TERMINAL = {"DONE", "FAILED", "CANCELLED", "BUDGET_EXHAUSTED"}

# state -> {event: next_state}
TRANSITIONS = {
    "RECEIVED":          {"ok": "PLANNING"},
    "PLANNING":          {"ok": "RESEARCHING", "invalid": "FAILED",
                          "error": "FAILED"},
    "RESEARCHING":       {"ok": "DRAFTING", "insufficient": "PLANNING",
                          "error": "FAILED"},
    "DRAFTING":          {"ok": "REVIEWING", "error": "FAILED"},
    "REVIEWING":         {"pass": "AWAITING_APPROVAL", "revise": "DRAFTING",
                          "error": "FAILED"},
    "AWAITING_APPROVAL": {"approve": "DONE", "reject": "CANCELLED",
                          "edit": "REVIEWING"},
}
# backward edges that form loops, each with its own cap
LOOP_LIMITS = {("REVIEWING", "revise"): 2, ("RESEARCHING", "insufficient"): 1}
BUDGET_EVENTS = {"step_limit", "timeout", "token_limit"}


def check(transitions, start="RECEIVED"):
    """Every non-terminal state has an exit and can reach a terminal state."""
    def reach(s):
        seen, todo = {s}, deque([s])
        while todo:
            for nxt in transitions.get(todo.popleft(), {}).values():
                if nxt not in seen:
                    seen.add(nxt)
                    todo.append(nxt)
        return seen

    reachable = reach(start)
    for s in reachable - TERMINAL:
        assert transitions.get(s), f"{s} has no exits"
        assert reach(s) & TERMINAL, f"{s} cannot reach a terminal state"
    return sorted(reachable)


def step(state, event, loops):
    if state in TERMINAL:
        raise ValueError(f"{state} is terminal")
    if event in BUDGET_EVENTS:
        return "BUDGET_EXHAUSTED"
    nxt = TRANSITIONS[state].get(event)
    if nxt is None:
        raise ValueError(f"event {event!r} not allowed in {state}")
    edge = (state, event)
    if edge in LOOP_LIMITS:
        loops[edge] = loops.get(edge, 0) + 1
        if loops[edge] > LOOP_LIMITS[edge]:
            return "BUDGET_EXHAUSTED"
    return nxt


if __name__ == "__main__":
    print(check(TRANSITIONS))
    state, loops = "RECEIVED", {}
    for event in ["ok", "ok", "ok", "ok", "revise", "ok", "revise", "ok", "revise"]:
        state = step(state, event, loops)
        print(f"{event:>7} -> {state}")
        if state in TERMINAL:
            break

Run with Python 3, it prints the reachable states and then a trace in which the third revision request ends the run in BUDGET_EXHAUSTED. In a real system the events come from validated agent outputs, and the same check function belongs in the test suite so that a new state without an exit fails the build.

Structural checks are only half of testing. Whether each agent does its job well inside its state is an evaluation question, discussed in evaluating AI agents beyond the demo.

Design review questions

  • Can you list every state and every allowed transition on one page?
  • Does each backward edge have a cap, and what happens when it is hit?
  • Are failure, cancellation and budget exhaustion separate terminal states?
  • Is the state schema explicit about who may write each key, and how?
  • Are technical retries and output repairs counted separately?
  • Do side-effecting states have idempotency keys?
  • Are state and counters persisted after each transition, and has resumption been tested?
  • Are step, time and token budgets set explicitly rather than left at framework defaults?

Whether a step should be an agent at all is a prior question, covered in agentic AI and traditional automation. Where these systems run, and how their state stores and queues are operated, is an infrastructure question; our enterprise infrastructure and architecture work covers that side.

Prepared with AI-assisted research and drafting.

Sources

[1] Amazon Web Services, "Amazon States Language" specification, states-language.net, accessed 2026. https://states-language.net/spec.html

[2] Amazon Web Services, "Handling errors in Step Functions workflows", AWS Step Functions Developer Guide, accessed 2026. https://docs.aws.amazon.com/step-functions/latest/dg/concepts-error-handling.html

[3] LangChain, "Graph API overview", LangGraph documentation, accessed 2026. https://docs.langchain.com/oss/python/langgraph/graph-api

[4] Microsoft, "Termination", AutoGen AgentChat user guide, accessed 2026. https://microsoft.github.io/autogen/stable/user-guide/agentchat-user-guide/tutorial/termination.html

[5] M. Cemri, M. Z. Pan, S. Yang, L. A. Agrawal et al., "Why Do Multi-Agent LLM Systems Fail?", arXiv:2503.13657, 2025. https://arxiv.org/abs/2503.13657

[6] J. Hadfield, B. Zhang, K. Lien, F. Scholz, J. Fox and D. Ford, Anthropic, "How we built our multi-agent research system", Anthropic Engineering, 13 June 2025. https://www.anthropic.com/engineering/multi-agent-research-system

[7] LangChain, "Persistence", LangGraph documentation, accessed 2026. https://docs.langchain.com/oss/python/langgraph/persistence