Multi-agent Systems & Production
Published
Your bar: decide when multi-agent is justified vs unnecessary; name five ways production agents fail and how to prevent them; design a business agent (billing, support, or SRE) with the right tools, oversight model, and cost controls.
Multi-agent = microservices for agents
production agents fail from loop, cost, and security gaps
business agents need the right tools + oversight
hype says autonomous; reality says HITL
Multi-Agent Systems — microservices for agents
One agent, one context window. Multi-agent = task decomposition + specialization + parallelism. Justified only when you’d split a microservice.
Is A system where a Coordinator Agent decomposes a task and delegates subtasks to specialist Worker Agents, collecting and synthesizing their outputs. Each agent has its own context window and toolset.
Why it exists A single agent’s context window is a hard limit. Some tasks are too large to fit in one context or require parallelism. Multi-agent splits the work across isolated contexts running concurrently.
Like (world) A consulting engagement with a project manager (coordinator) directing a research analyst, a financial modeler, and a writer (workers). Each specialist works independently in parallel; the PM synthesizes the final report.
Like (code) Microservices vs a monolith. The coordinator is the API gateway / orchestrator. Workers are specialized services. Communication is structured outputs, not shared memory.
| Scenario | Use multi-agent? | Why |
|---|---|---|
| Task fits in one context window | No | Single agent is simpler and debuggable |
| Tasks are genuinely parallel (no dependencies) | Yes | Parallelism reduces wall-clock time |
| Different tasks need different toolsets | Yes | Worker specialization; cleaner context |
| Task requires full repo analysis (>context limit) | Yes | Decompose by module/file cluster |
| Sequential steps with shared state | No | Single agent loop handles this naturally |
| You want “more intelligence” | No | That’s a model quality problem, not architecture |
When would you choose multi-agent over a single agent for a coding task?
What are the main failure modes unique to multi-agent systems vs single-agent?
(1) Coordinator failure — misinterprets worker output, sends wrong context to next worker.
(2) Worker isolation — worker doesn’t have enough context to do its job because the coordinator under-specified.
(3) Compounded errors — one worker’s bad output propagates to downstream workers without correction.
(4) Debugging difficulty — which agent made the mistake?
(5) Cost amplification — N agents × M iterations = N×M LLM calls, all billed.
(6) No shared state — workers can’t see each other’s work unless the coordinator explicitly passes it.
Memory check
- What analogy maps coordinator agent → worker agent to a software architecture pattern? → API gateway → microservice; or project manager → specialist consultant.
- Name two scenarios where multi-agent is NOT justified. → Task fits in one context; sequential steps that share state; "want more intelligence" (wrong lever).
- What is the primary coordination cost of multi-agent? → The coordinator must assemble, pass, and synthesize context for each worker — context assembly and output synthesis failures are new failure modes that don't exist in single-agent.
Production Engineering — where agents break in the real world
An agent that works in a demo will fail in production. Infinite loops, $500 bills, and silent data corruption are the real challenges.
Is The set of engineering controls — security, observability, cost control, reliability, and auditability — that distinguish a production agent from a demo. All of these are operational concerns, not model concerns.
Why it exists LLMs are non-deterministic and context-sensitive. Without controls, an agent can loop, overspend, silently corrupt data, or be manipulated by adversarial input. Production requires every one of these addressed.
Like (world) A new employee with company credit card access. You give them expense limits, require receipts, audit the card monthly, and revoke access if something looks wrong. You don’t give unlimited authority on day one.
Like (code) Any stateful distributed service with external I/O. You instrument it (metrics/traces/logs), rate-limit it, add circuit breakers, require auth for writes, and test failure modes — because silent failures in production are more dangerous than loud ones.
Security + Permissions
Principle of least privilege: the agent should only have the permissions it needs for the current task. Never give a read-only reporting agent write access. Prompt injection is real: adversarial content in tool results (e.g. a web page the agent fetched) can override instructions. Defense: validate tool outputs, use a system prompt that ignores instruction-like text in user/tool content, and sandbox risky tools.
Observability + Auditability
Every tool call should emit a structured log: timestamp, tool name, inputs, outputs, agent ID, session ID, cost. This is your audit trail. Without it you cannot debug why the agent made a decision, comply with audits, or detect abuse. Use OpenTelemetry spans or equivalent. Never log PII in tool inputs/outputs.
Cost Control
Token budget per session (hard cutoff). Model tiering: use a smaller/cheaper model for simple steps, reserve the large model for complex reasoning. Cost tracking per user/tenant for SaaS billing. Alert on anomalous spend (3× baseline = incident). For multi-agent: N agents × M iterations compounds fast — set per-agent budgets, not just session budgets.
Reliability + Retries
Exponential backoff for transient tool failures (network timeout, rate limit). Max retry cap (3 attempts, then fail fast with a clear error — not silent degradation). Idempotent tool design: if a tool call is retried, it should not double-charge or double-insert. Circuit breaker: if a tool fails repeatedly, disable it for the session and report to the user.
Loop Prevention
Max iteration cap (e.g. 20 steps). Detect repetition: if the last 3 LLM outputs are semantically identical, the agent is stuck — halt. Human-in-the-loop interrupt: allow the user to pause/stop at any step. Time-box: wall-clock timeout independent of iteration count (some steps are slow, not infinite).
Failure Modes (why agents get stuck)
(1) Context saturation: the context window fills with tool outputs; the agent loses the original goal. Fix: periodic compression or goal re-injection. (2) Tool error spiral: a tool returns an error; the agent retries infinitely without changing its approach. Fix: max retries + different strategy on retry. (3) Hallucinated tool calls: the agent calls tools that don’t exist or with wrong arguments. Fix: strict tool schema validation at the runtime level. (4) Ambiguous task: the agent asks a clarifying question but the user isn’t present to answer. Fix: require task completeness upfront; use async human-in-the-loop for long tasks.
You’re launching a SaaS billing agent that can apply credits, retry charges, and update subscription tiers. What production controls do you put in place before launch?
(1) Least privilege — read-only by default; write operations require explicit capability grant per session.
(2) Dry-run mode — all write operations execute a dry run first and show proposed changes before confirming.
(3) Loop cap — max 15 iterations per task; halt and notify if exceeded.
(4) Cost cap — max $2 in LLM tokens per billing task; alert at 50% of budget.
(5) Structured audit log — every tool call logged with inputs, outputs, user ID, session ID, timestamp — immutable, append-only.
(6) Idempotency keys on all write tools: retried calls are no-ops.
(7) Human approval gate for changes above a threshold (e.g. credits > $100 require human confirmation).
(8) Prompt injection defense — tool outputs are tagged as [TOOL RESULT] and the system prompt instructs the model to treat them as data, not instructions.
How do you detect and prevent an infinite loop in a production agent?
(1) Hard iteration cap (e.g. 20 steps) — the runtime counts and halts.
(2) Semantic repetition detector: if the last N tool calls are identical (same tool, same args), the agent is looping — halt with an error.
(3) Wall-clock timeout: even slow legitimate steps shouldn’t take more than X minutes — hard cap independent of iteration count.
(4) Progress check: every K steps, the agent summarizes what it has accomplished; if no progress detected, escalate to human.
(5) Dead-man switch: a background timer that triggers a halt if the agent doesn’t emit a “still working” heartbeat within Y seconds.
Memory check
- Name the six production controls every agent needs. → Loop cap, token budget, least privilege, dry-run mode, structured logging, circuit breaker/retry policy.
- What is prompt injection and how do you defend against it? → Adversarial instructions embedded in tool results (e.g. a fetched webpage) that override system instructions. Defense: tag tool outputs as data not instructions; validate/sanitize; system prompt tells the model to ignore instruction-like content in tool results.
- Why must idempotent tool design be a requirement for any agent with write access? → The agent runtime retries failed tool calls; without idempotency, a retry causes a double-charge, double-insert, or duplicate action — no explicit dedup mechanism in the loop catches this.
Business Agent Architecture — designing for the org chart
An agent is a job description + a toolset + an autonomy level. Get those wrong and ROI evaporates, or you create a liability.
Is The practice of designing agents for specific business roles by choosing the right toolset, permission level, autonomy setting (full-auto vs human-in-the-loop), and success metric for that role’s risk profile.
Why it exists Generic “do anything” agents are dangerous and expensive. A Billing Agent and an SRE Agent need different write permissions, different oversight thresholds, and different definitions of “done”. Role-specificity is the unit of deployment.
Like (world) An employee’s job description. You don’t give the same authority to an intern and a CFO — even if they use the same office software. The role defines permissions, escalation paths, and accountability.
Like (code) A service account with a specific IAM policy. The agent is the service account; the tools are the allowed API calls; the HITL threshold is the MFA requirement for sensitive operations.
| Agent | Responsibilities | Tools | Autonomy | Key Risk | Human Oversight |
|---|---|---|---|---|---|
| Billing | Apply credits, retry charges, update plans, generate invoices | Stripe API, billing DB read/write, email | Supervised: approve writes >$50 | Double-charge, compliance | Approval gate on all write ops above threshold |
| Support | Answer tickets, look up order status, issue refunds ≤$25 | Ticket system, CRM read, refund API (capped), KB search | Semi-auto: low-value actions auto; escalate complex | Wrong refund, policy violation | Escalation queue for anything outside KB |
| SRE | Read logs, restart services, scale replicas, create incidents | kubectl, CloudWatch, PagerDuty, Slack | Supervised: reads auto; writes require confirm | Service outage from bad action | Approval for any destructive action (delete, scale-down) |
| Product Manager | Draft PRDs, create Jira tickets, summarize user feedback, update roadmaps | Jira, Confluence, Slack read, Mixpanel | High autonomy for drafts; low for publishing | Stale/incorrect specs shipped | Human review before any public artifact is published |
| Engineering | Read code, suggest fixes, run tests, open PRs | Filesystem read, git, Bash (sandboxed), GitHub API | High for read+suggest; supervised for merge | Bad code merge, security vuln | Human code review and approval before any merge |
Your company wants an autonomous SRE agent that can respond to incidents without human approval. What are your concerns and what controls would you require?
Concerns: destructive actions (delete pods, scale to 0, drain nodes) on wrong targets; misdiagnosis of root cause leading to wrong remediation; cascading failures from bad automation.
Required controls:
(1) Read-only phase first — gather all context before any writes.
(2) Dry-run mode for all proposed remediations — show the exact commands before execution.
(3) Blast-radius estimation: if the proposed action affects >N% of capacity, require human approval.
(4) Rollback capability: every write action must have a defined undo.
(5) Auditability: every action logged to an immutable incident timeline.
(6) Human-in-the-loop for anything P1/P0. Start with supervised; earn full autonomy over time on a limited action set.
How do you calculate the ROI of a business agent and what are the most common ways agent ROI is overstated?
Real ROI = (time saved × hourly rate) + (error reduction × cost per error) - (agent cost + build cost + ops cost).
Commonly overstated because:
(1) Build cost is underestimated — prompting, testing, safety controls, and ops tooling are all non-trivial.
(2) Human oversight cost is forgotten — supervised agents still need a human in the loop, just a less skilled one.
(3) Error rates in production are higher than in demos — each LLM error has a cost.
(4) Model costs at scale are not linear — token usage grows with context and multi-agent amplification.
Honest ROI requires measuring production error rate, oversight cost, and total LLM spend — not just demo throughput.
Memory check
- What three things define a business agent's role? → Toolset (what it can call), autonomy level (how much it can do without approval), and job description (what it's responsible for).
- Which business agent type carries the highest risk of a production incident? → SRE agent — it can execute destructive infrastructure operations; billing agent is second (financial impact).
- Why is a "general-purpose do-anything agent" a risky design for enterprise? → Broad permissions amplify blast radius; no clear audit scope; harder to comply with SOC2/GDPR audit requirements; no clear escalation path.
★ Stage 2 executive summary
What you now understand (Stage 2)
Nine modules. Three core insights to carry into every architectural review:
The runtime is not the LLM. The LLM predicts. The runtime orchestrates — loop, tools, state, cost, safety. When an agent behaves badly, look at the runtime first.
Context is the lever. A weaker model with the right context beats a stronger model with noise. Context engineering (retrieval, ranking, assembly, compression) is where the most leverage lives in production.
Autonomy is earned, not assumed. Production agents need six controls before launch (loop cap, token budget, least privilege, dry-run, structured logging, circuit breaker). Multi-agent adds complexity — justify it like you’d justify splitting a microservice. Business agents are job descriptions with IAM policies.
The one diagram to draw
User → Runtime (loop/cost/safety) → LLM (stateless text prediction) → Tools (MCP servers) → back to Runtime. Context selection happens before the LLM call. Memory (3 tiers) is what the runtime injects into the context. That’s the whole machine.
Retrieval practice — Modules 7–9
Q1. Multi-agent is justified when...
Q2. The primary reason production agents create infinite loops is...
Q3. Least-privilege in agent design means...
Q4. The right autonomy level for an SRE agent performing destructive operations is...
Q5. A Billing Agent that issues a refund must have idempotent tool design because...
Interview — pick your bar
Answer out loud in ~60s, then reveal. Core = recall · Senior = trade-offs & failure modes · Staff = synthesis under ambiguity · System Design = open design round (a different axis, not a harder level).
Define a single-agent system versus a multi-agent system, and name the two roles in the multi-agent pattern.
What does the orchestrator (lead agent) do, and what does a subagent (worker) do?
Distinguish a workflow from an agent, and say where memory fits in an agent system.
Name three production controls every agent needs before launch, and what each one prevents.
When does multi-agent genuinely help, and when is it just "more microservices" cargo-culting?
Why is cost the hidden killer of multi-agent systems, and how do you reason about it?
How do you keep an agent from running forever or overspending in production?
A wrong or stuck multi-agent run lands on you. Why is it harder to debug than a single agent, and what makes it tractable?
Design a production multi-agent system with guardrails, observability, and cost controls. What's the skeleton?
An engineer proposes "let's add more agents" to fix quality. Challenge it the way you'd challenge "let's add more microservices."
"Autonomous agents will replace the team — ship it fully auto." Make the principal-level call on autonomy.
- Clarify the job: the agent's responsibilities, the success metric, and the risk profile of its actions.
- Single vs multi-agent: is the work sequential (one agent) or genuinely parallel / separable-context (orchestrator + subagents)? Justify any split.
- Tools & permissions: smallest viable toolset, least privilege, read and write agents separated, typed schemas with argument validation.
- Guardrails: step cap + wall-clock timeout, idempotency on writes, HITL gates on high-risk actions, prompt-injection defense (tool outputs as data).
- Cost controls: per-agent + session token ceilings with a kill switch, model tiering, prompt caching, history compaction, anomaly alerts on spend.
- Observability: full per-step traces (assembled context + output + tool calls + cost), keyed by agent/session; immutable audit log for every mutation.
- Failure modes & degradation: loops, tool-error spirals, context saturation, compounded multi-agent errors — and the fallback path (cache / smaller model / escalate to human).
Design a production SRE incident-response agent — tools, guardrails, and observability — for a team that wants it to triage and remediate alerts.
Design a customer-support agent fleet for a SaaS product — multiple agents, guardrails, and cost controls under real traffic.
★ Stage 2 architecture cheat sheet
AI Buzzword → Engineering translation
| Buzzword | Engineering equivalent | One-line test |
|---|---|---|
| LLM | Stateless text-prediction function | ”Does it have memory?” No. “Does it act?” No. Just f(text)→text. |
| Agent | LLM + tools + loop | ”Can it call code and repeat?” Yes = agent. No = just prompting. |
| Runtime | Agent OS (web server + queue + middleware) | “Who runs the loop and executes tools?” The runtime. |
| Context window | RAM budget per LLM call | ”What fits in one call?” Everything you send. Miss it = not seen. |
| Context engineering | Cache-fill strategy for the LLM | ”What gets loaded into RAM before the call?” That’s context engineering. |
| Working memory | In-flight task scratchpad | ”Where does the current plan live?” Working memory. |
| Long-term memory | Queryable knowledge store (vector DB / SQL) | “What survives session reset?” Long-term memory only. |
| MCP | USB-C for tool integrations | ”Does it work with any MCP agent?” Yes = MCP. Custom = proprietary. |
| MCP Tool | Invocable function with schema | “Can the agent call it and get a result?” Tool. “Can it just read it?” Resource. |
| Coordinator | Orchestrator / API gateway for agents | ”Who decomposes and delegates?” Coordinator. |
| Worker | Specialist microservice agent | ”Who executes one focused subtask?” Worker. |
| HITL | Human approval gate | ”Does a human approve before irreversible action?” Yes = HITL. |
| Loop cap | Max iteration guard | ”What stops the agent from looping forever?” Loop cap. |
| Least privilege | Agent IAM policy | “What can the agent do that it wasn’t supposed to?” If anything: wrong design. |
Three rules to carry into any AI pitch
“The runtime is not the model.” Ask: how does it handle loops? cost? errors? If they can’t answer, the system isn’t production-ready.
“Context quality beats model quality.” Ask: what’s the retrieval strategy? If the answer is “we send everything,” the costs will surprise you.
“Autonomy is earned, not assumed.” Ask: what’s the override mechanism? what’s the audit trail? what’s the blast-radius limit? If there’s no good answer, the risk is not priced in.
★ Architecture review checklists
The review skill in portable form. The unifying lens: an agent request is not a web request — it’s a long-lived, stateful session fanning out to a non-deterministic, sometimes-failing model and to privileged tools. Almost every risk below flows from that.
Architecture review checklist
Is the loop durable/resumable (checkpointed), or is in-flight work lost on crash?
Where does session state live — can any stateless worker resume?
Are provider rate limits identified and managed (queue, multi-key, backpressure)?
Per-tenant isolation — can one tenant starve others’ quota or cost?
Every tool: scope, credentials, worst single call enumerated?
Is authorization in the runtime/policy layer, not the prompt?
Idempotency on every mutating tool?
Loop cap + wall-clock + token budget enforced by the runtime?
Full per-step traces (assembled context + output + tool calls + cost) captured?
Eval harness gating prompt/model changes?
Agent design checklist
Smallest viable toolset; read and write agents separated.
Tools have typed schemas + argument validation.
Retrieval is hybrid + reranked; recall measured independently of end-to-end accuracy.
Context budget allocated per section; history compacted.
Model tiering — cheap model for navigation, strong model for the hard step.
Prompt caching on the stable prefix.
Irreversible actions have approval gates / HITL.
Tool outputs tagged as data, never concatenated as instructions.
Production readiness checklist
Token/cost budget + kill switch per session and per tenant.
Circuit breakers per tool and per provider.
Retries: bounded, backoff + jitter, retryable-vs-not classified, idempotency keys.
Graceful degradation path defined (smaller model / cache / escalate to human).
Immutable audit log for every mutation.
Secret/PII redaction in logs and traces.
Dead-letter + human-escalation queue.
Cost attribution + alerting per tenant.
Canary / rollback for prompt and model changes.
Multi-provider / region failover for the LLM dependency.
Common failure modes
Retry storms · duplicated side effects (charges/emails) from non-idempotent retries · runaway loop → unbounded spend · noisy-neighbor quota starvation · prompt injection via tool/RAG content → exfiltration or unauthorized action · over-broad token → mass deletion · retrieval recall miss → confident wrong answer · lost-in-the-middle · context exhaustion on long tasks · silent degradation · “can’t reproduce it” (no traces) · silent regression from a prompt tweak.
🚩 Red flags in an agent architecture
“Guardrails” that are system-prompt sentences · one omnipotent API key or tool · sync request handling for long tasks · no per-step tracing or assembled-context capture · no eval set (“we test by trying it”) · unbounded retries / no loop cap · no idempotency on writes · always the biggest model, no tiering · full history re-sent with no compaction or caching · no per-tenant cost visibility · tool outputs concatenated straight into instruction context · “the model will know not to do that.”
Questions a VP Engineering should ask in a design review
“What’s the per-step success rate, and therefore the end-to-end task success rate?” (forces the compounding-reliability math: 0.99⁴⁰ ≈ 67%.)
“Enumerate every tool’s blast radius. For each worst case, is the control in the runtime or the prompt?"
- "Where does state live if a worker dies at step 20 of 30?"
- "What’s cost per completed task, and what’s the kill switch on runaway spend?"
- "How do you tell a retrieval failure from a reasoning failure in a wrong answer?”
“I change one prompt line — what automatically catches a 5% regression before it ships?"
- "Show me how you debug a bad action from three days ago without re-running it."
- "What’s the noisy-neighbor story — can one tenant starve the rest?”
★ Review guides & what to learn next
5-minute weekly recall
Recite from memory without looking:
Draw the full stack: User → Runtime → LLM → Tools. Label each responsibility of the Runtime.
- Name the three memory tiers and one production backend for each.
- What does the MCP chain look like from Business Function to LLM tool call?
- Name two scenarios where multi-agent is justified and two where it isn’t.
- Name the six production controls every agent needs before launch.
If you get stuck: read the .rule block for that module, then close it and try again.
30-minute deep dive (when stalled or before a big review)
Runtime internals — Read Anthropic’s “Building effective agents.” Map each pattern (augmented LLM, workflow, agent) to the Runtime module.
Context engineering — Read Simon Willison on context windows. Reproduce the Cursor vs Claude Code comparison table from memory.
MCP — Read modelcontextprotocol.io. Build a hello-world MCP server with one Tool in any language. Nothing cements the concept faster.
Production failures — Read Anthropic’s post-mortems or any public AI agent incident report. Map each failure to one of the six controls.
Business agents — Pick one role from the design table (Billing or SRE). Design it: tools, permissions, autonomy level, HITL threshold, audit log schema. Could you present it to a CTO?
What to learn next
| Topic | Why | Start here |
|---|---|---|
| Evals & testing agents | You can’t improve what you can’t measure. Agent evals are the hardest unsolved problem in production AI. | Anthropic’s eval guide; Braintrust; LangSmith |
| RAG (Retrieval-Augmented Generation) | Long-term memory + context engineering in depth. The foundation of every knowledge-base agent. | pgvector + LlamaIndex; Pinecone docs |
| Prompt engineering at production scale | System prompts, few-shot examples, chain-of-thought, and prompt injection defense become critical at scale. | Anthropic’s prompt engineering guide |
| Agentic security | Prompt injection, tool abuse, data exfiltration via agents. OWASP LLM Top 10. | OWASP LLM Top 10; Anthropic’s responsible scaling policy |
| Build your first agent | Nothing beats shipping. Build the support agent or billing agent from Module 9 with real tools. | Anthropic Claude API + MCP SDK; start with one tool |
These notes reflect my current understanding and are updated as I learn, build, and discover better explanations.