SysDesignAtlas

Agent Architectures

The tool-calling loop, why unbounded autonomy fails, and how to build agents as state machines with checkpoints rather than hopeful while-loops.

HLDHard11 min readaiagentstool-useorchestration
Confidence

#What an agent actually is

Strip away the framing and an agent is a loop:

   while not done:
       response = model(context)
       if response.has_tool_call:
           result = execute(response.tool_call)
           context += [response, result]
       else:
           return response.text

Twelve lines. Everything hard about agents is in what that loop omits: what happens when the tool fails, when the model loops, when the context overflows, when the process crashes on step 14 of 20, when the cost passes a hundred dollars, and when a tool call has an irreversible side effect.

An agent is a distributed system with a nondeterministic scheduler. Like any distributed system, it calls out to services that fail, time out, and change things in the outside world. And the "scheduler" — the part that decides what runs next — is the model, which may choose differently every time you run the same task. Treating it as a prompt engineering problem is why so many agent projects stall at the demo.

#Tool definitions are an API contract

The model chooses tools based entirely on their descriptions. That makes tool definitions the highest-leverage text in the whole system.

   ✗ WEAK
     name: search
     description: Searches for things

   ✓ STRONG
     name: search_customer_orders
     description: |
       Find orders for a specific customer by email or
       customer ID. Returns up to 50 orders, most recent
       first. Use this when the user asks about order
       history, status, or past purchases.

       Does NOT search products — use search_catalog for that.
       Does NOT return payment details.
     parameters:
       customer_identifier: email or customer ID (required)
       status: filter by pending|shipped|delivered (optional)
       since: ISO date, only orders after this (optional)

The principles that matter, in order of impact:

  1. Say when to use it, and when not to. Negative guidance ("does NOT search products") prevents more mistakes than positive guidance adds.
  2. Fewer tools, better described. Past roughly 20 tools, selection accuracy degrades noticeably. Group related operations behind one tool with a mode parameter, or use a two-stage approach: retrieve relevant tools, then present only those.
  3. Return errors the model can act on. {"error": "customer_not_found", "hint": "try search_customer_by_name"} lets it recover. 500 Internal Server Error produces a retry loop.
  4. Make results compact. A tool returning 8,000 tokens of JSON consumes the context budget and buries the signal. Summarise or paginate at the tool boundary.
  5. Standardise the interface where it helps. Tools served over MCP can be shared across agents, with the same contract rules applying.
  6. Constrain the schema. Constrained decoding makes malformed tool calls impossible rather than rare.

#Patterns

PatternShapeBest for
ChainFixed sequence of stepsKnown workflows. Not really an agent, and often the right answer
RouterClassify, then dispatch to a specialised handlerMulti-intent products
ReActReason about what to do, act by calling a tool, observe the result, repeatGeneral tool use; the common default
Plan-and-executeProduce a full plan, then execute stepsComplex tasks; plan is inspectable before running
ReflectionGenerate, critique, reviseQuality-critical output; costs 2–3×
Multi-agentSpecialised agents with a coordinatorGenuinely separable subtasks

#Multi-agent, and when it isn't worth it

   COORDINATOR / WORKER

     Coordinator: decomposes, dispatches, synthesises
        ├── Researcher   (search tools)
        ├── Analyst      (data tools)
        └── Writer       (no tools)

   Genuine benefits:
     · each agent has a small, focused tool set
     · subtasks run in PARALLEL — real latency win
     · separate context windows avoid one giant prompt

   Genuine costs:
     · coordination overhead: every handoff is model calls
     · information loss at each boundary — summarised
       context loses detail the next agent needed
     · errors compound across agents
     · debugging spans multiple trajectories
     · cost multiplies

Parallelism is the strongest argument. Three independent research subtasks running concurrently is a real three-fold latency improvement that a single sequential agent cannot achieve.

Specialisation is the weakest argument. "A writer agent and an editor agent" is usually two prompts to the same model with extra plumbing and lossy handoffs between them. If the subtasks aren't independent enough to parallelise, they probably belong in one agent.

#Termination

Nothing in the loop guarantees it stops. The model decides each step, and a model that has misunderstood the task will keep confidently taking steps forever, billing you for every one. Termination has to be imposed from outside, and each of these limits catches a different way of getting stuck:

   · max iterations           (typically 10-50)
   · max total tokens         (a hard cost ceiling)
   · max wall-clock time
   · max cost in currency
   · no-progress detection    (repeating the same tool call
                               with the same arguments)
   · explicit completion      (the model calls a `finish` tool)

   When any limit trips:
     return partial results with a clear explanation —
     never fail silently, and never keep going

No-progress detection catches the most common real failure. An agent calls search("customer orders"), gets nothing useful, and calls search("customer orders") again. Hash the last few (tool, arguments) pairs; if a repeat appears, inject an explicit observation — "you have already tried this and it returned nothing; try a different approach" — or terminate. This one check eliminates a large fraction of runaway loops.

#Failure and recovery

Agents fail mid-trajectory — partway through the sequence of model calls and tool calls that make up one run — and the interesting question is what state you're left in.

FailureHandling
Tool returns an errorFeed it back as an observation; the model can often recover
Tool times outRetry with backoff, then report failure as an observation
Model produces invalid tool callConstrained decoding makes this impossible; otherwise, repair and retry once
Context overflowsCompact history, or fail cleanly — don't silently truncate
Process crashesRequires durable state. See below
Infinite loopIteration and no-progress limits
Model gives up earlyPrompt for persistence; check completion criteria before accepting

#Human in the loop

Some actions should not be autonomous. The design is a policy, not a feature:

   AUTO-APPROVE     read-only: search, fetch, analyse
   NOTIFY           low-risk writes: create a draft, add a comment
   APPROVE FIRST    external effects: send an email, make a payment,
                    modify production, delete anything
   NEVER            outside the agent's remit entirely

   The approval gate must:
     · pause DURABLY — the agent may wait hours for a human
     · show what will happen, in terms a human can evaluate
     · allow modify-and-continue, not just yes/no
     · time out with a defined default (usually: don't do it)

Durable pausing is the requirement that forces the architecture. An agent waiting for approval cannot be an in-memory loop in a request handler — it needs persisted state and a resumption path, which is the subject of agent infrastructure.

#Evaluating agents

Harder than evaluating a single response, because the trajectory matters as much as the answer:

  • Task success rate — did it accomplish the goal? Needs a checkable definition of success per task.
  • Trajectory efficiency — how many steps and tokens versus optimal?
  • Tool selection accuracy — right tool, right arguments, measurable per call.
  • Recovery rate — when a tool failed, did it recover or spiral?
  • Cost distribution — the p99 matters more than the mean. A handful of runs that loop for 200 steps barely move the average, but they show up in the p99 and dominate the bill.

Build a fixed set of tasks with verifiable outcomes. Not "did it write a good summary" but "did the file get created with the right content", "did the test pass", "was the correct customer record updated". Verifiable outcomes make regression testing possible, and without them agent development is anecdote-driven.

#Check yourself

What is an agent, architecturally?Show answer
A loop — call the model, execute any tool call, append the result, repeat — that behaves like a distributed system with a nondeterministic scheduler. The hard parts are failures, loops, overflow, crashes, cost and side effects.
What makes a good tool definition?Show answer
Say when to use it and when not to, keep the tool count modest (selection degrades past ~20), return actionable errors, keep results compact, and constrain the schema.
Why prefer the most constrained agent pattern?Show answer
Chains and routers have predictable cost, are debuggable and testable, and encode what you know about the task. If you can write the workflow down, write it down.
When is multi-agent worth it?Show answer
When subtasks are independent enough to run in parallel — a real latency win. Specialisation alone adds lossy handoffs, compounding errors and cost.
What termination limits does an agent need?Show answer
Maximum iterations, tokens, wall-clock time and spend, an explicit finish tool, and no-progress detection — hashing recent (tool, arguments) pairs to catch repeats.
How do you make agent side effects safe to recover?Show answer
Idempotency keys enforced in every mutating tool, a durable trajectory log written before each next step, and compensation or human approval for irreversible actions.
How should human approval work?Show answer
By policy: auto-approve reads, notify for low-risk writes, require approval for external effects. The pause must be durable, show the effect clearly, allow edits and default to "don't" on timeout.
How should agents be evaluated?Show answer
Task success on verifiable outcomes, trajectory efficiency, tool-selection accuracy, recovery rate and the cost p99, where runaway loops live.

#What to carry forward

  • An agent is a distributed system with a nondeterministic scheduler, not a prompt.
  • Tool descriptions are the highest-leverage text; negative guidance prevents more errors than positive guidance fixes.
  • Prefer the most constrained pattern that works. If you can write the workflow down, write it down.
  • Multi-agent earns its cost through parallelism, rarely through specialisation.
  • Every loop needs explicit limits, including no-progress detection.
  • Side effects are not replayable — idempotency keys, a durable trajectory log, and approval gates.
  • Evaluate on verifiable outcomes, and watch the cost p99, not the mean.
00:00
/ 11m