Advanced Agent Architecture and Orchestration
Designing production multi-agent systems, including supervisor/worker orchestration, durable execution, harness selection based on cost and reliability data, and context/memory architecture for long-running agents.
- Multi-Agent Orchestration: supervisor/worker, parallel dispatch, delegation and context-isolation boundaries, inter-agent communication, human-in-the-loop
- Durable Execution and State Management: session persistence, checkpointing, resumability, memory architecture across interruptions and model changes
- Architecture Selection at Scale: evolving between workflow and agentic patterns; harness, framework, and pattern standards for a team
- Context and Memory Architecture: compaction, context editing, persistent memory, cache-safe instruction changes, keeping tool catalogs out of context
Domain overview
Domain 1 accounts for 17% of the CCDV-P exam. Items usually present a running system together with its telemetry, for example a spike in token cost, subagents duplicating work, a session losing state after a restart, or a falling cache hit rate. You must choose the most appropriate architectural change. The domain covers four skill areas:
- Multi-agent orchestration and inter-agent failure modes.
- Durable execution: persistence, checkpointing, resume, and memory that survives restarts and model changes.
- Data-driven architecture selection, and choosing a standard harness/pattern for the team.
- Context & memory architecture.
(Source: CCDV-P Exam Guide, Domain 1)
Multi-agent orchestration
The supervisor/worker pattern (orchestrator-worker)
Anthropic's Research system uses the orchestrator-worker pattern. A lead agent plans, spawns subagents that run in parallel (each with its own context window), and then synthesizes the results.
- The lead uses Claude Opus 4 and the subagents use Claude Sonnet 4. This configuration outperformed single-agent Claude Opus 4 by 90.2% on an internal research eval.
- Token usage explains 80% of the variance in performance.
- Agents use about 4× as many tokens as chat, and multi-agent systems about 15×. Only worth it for high-value tasks.
- A poor fit for tasks that require shared context or have many dependencies between agents. Most coding work falls into this category.
Key point
Multi-agent works because it spends more tokens, in parallel, in separate contexts. If a task can't be split into independent pieces, multi-agent only adds coordination overhead.
Delegation and effort scaling
Every delegation must give the subagent all four of these:
- objective
- output format
- tool/source guidance
- task boundaries
Without them, subagents duplicate work or leave gaps. Agents also judge effort poorly, so the lead's prompt needs scaling rules:
| Query complexity | Number of agents | Tool calls |
|---|---|---|
| Simple fact-finding | 1 agent | 3–10 |
| Direct comparison | 2–4 subagents | 10–15 per subagent |
| Complex research | More than 10 subagents, with clearly divided responsibilities | Varies by branch |
The lead spawns 3–5 subagents at once, and each subagent calls 3 or more tools in parallel. These two layers of parallelism cut research time by up to 90%.
On Managed Agents, the principle is start with self, then add cheaper workers. First, the roster contains only {"type": "self"}, a copy of the coordinator that cannot delegate further. Next, move read-heavy work to workers running a smaller model, such as Claude Haiku 5.5. Worker tokens are billed at the worker model's price.
Context-isolation boundaries and communication
- Each subagent/thread has its own context, and only its report comes back. In Claude Code, a subagent reports only to its parent.
- On Managed Agents, agents share the sandbox, filesystem, and credential vault, but each agent has its own session thread. MCP servers are attached per agent. Web allow-lists across layers are intersected, so disjoint allow-lists make every call fail with
url_not_allowed. - There is only one level of delegation. Putting an agent that itself has
multiagentinto the roster causes a validation error. - Subagents write output to the filesystem/artifact store and send a lightweight reference back to the coordinator, instead of copying large outputs through the conversation history.
Managed Agents enables multiagent with multiagent: {type: "multiagent_20261001"}. The coordinator gets the list_agents and send_to_agent tools. Subagent threads are persistent, so they can receive follow-ups. For agent.thread_message_sent/agent.thread_message_received, direction is relative to the thread that carries the event: the same task is _sent on the primary stream but _received on the child stream.
Limits: a roster of 1–20 agents, at most 25 child threads per session, including idle threads, and finished threads must be archived. For work that is too large, use dynamic workflows: the agent writes a plan that runs many agents in phases. The current limits are 64 concurrent threads per run and a default lifetime of 24 hours, and run threads do not count toward the limit of 25.
The synchronous style (the lead waits for the whole batch to finish) is simple but becomes a bottleneck, because one slow subagent blocks the whole system. The asynchronous style is more parallel but makes state consistency hardest to maintain.
Human-in-the-loop and approval flows
| Permission policy | Behavior | Default for |
|---|---|---|
always_allow |
The tool runs immediately | Agent toolset |
always_ask |
The session goes idle with requires_action and waits for user.tool_confirmation (allow/deny + deny_message) |
MCP toolset |
auto |
The server lets it run, denies it (the client cannot override), or pauses for approval | Must be set explicitly |
Exam trap
"Set auto for irreversible operations" is wrong. auto is not a human checkpoint: calls judged safe run before anyone sees them. If human approval is mandatory (money transfers, deleting prod data), use always_ask for that tool.
Tool Runner provides an approval gate through a per-turn hook. Dynamic workflows have no approval step before a run starts, so you must state in the system prompt when a run may be launched, and set a session budget. The session budget (max_list_cost) can only be set when the session is created (create-only) and is shared by all threads. When the cap is reached, the session pauses with stop_reason: budget_reached rather than being terminated.
Inter-agent failure modes
| Symptom | Root cause | Remedy |
|---|---|---|
| A simple query spawns a swarm of subagents (50 have been observed) | The lead does not know how to scale effort | Put scaling rules in the lead's prompt |
| Subagents duplicate sources and some areas are missed | Vague task descriptions | Delegate with a full objective, format, tools, and boundaries |
| Agent SDK fan-out hits 429 | Dispatching wide all at once | Split into small batches |
| One subagent hangs and the whole session waits | The Agent SDK has no per-subagent deadline | maxTurns in AgentDefinition; stall watchdog CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS |
| One failed item breaks the whole run | The plan lets a thread error end the run (program_error) |
"One agent failing must not fail the run" |
The run is completed but the output is wrong |
Misreading result.type |
completed only means the plan finished running |
Other run errors: timeout_error (lifetime exceeded) and thread_limit_error. Dependency errors (model, MCP, credential) arrive as session.error and do not by themselves end the run.
Exam trap
A Q&A agent answers one question at a time, and the item stresses that "accuracy is the top priority". The option "add a checker/voter roster that re-grades every answer" is a trap, because it multiplies the cost of every answer. The right direction: provide sufficient documents and tools, instruct the agent to check its own work in the system prompt, and raise effort. A code-based check that does not call the model (the quote appears verbatim in the source) is still acceptable.
(Sources: Anthropic Engineering: How we built our multi-agent research system; Anthropic Skills: claude-api — Managed Agents: Multiagent Sessions, Managed Agents: Tools & Skills; Claude Code Docs: Hosting the Agent SDK)
Durable execution & state management
Where does state live?
Claude Agent SDK
query()spawns aclaudeCLI subprocess.- The transcript (
~/.claude/projects/), CLAUDE.md, and artifacts in the cwd live on local disk, so they are lost on restart, scale-down, or a move to another node. - The
SessionStoreadapter mirrors only the transcript, not CLAUDE.md or artifacts. It is best-effort: on a write failure it drops the batch, emits{type: "system", subtype: "mirror_error"}, and keeps running. - Resume with
options: { resume: sessionId, sessionStore }.
Managed Agents ("decoupling the brain from the hands")
- The harness runs separately from the sandbox.
- The session is an append-only log of every model call, tool call, and result, kept outside the process that runs the agent. Resuming needs no database or save point.
- The container is checkpointed when the session is idle.
| Agent SDK hosting pattern | Description | State to store externally |
|---|---|---|
| Ephemeral | One container per task | Usually none |
| Long-running | A container holds many sessions, routed by consistent hashing on sessionId |
Transcript |
| Hybrid | The container sleeps when idle and hydrates when the user returns | SessionStore is required |
Exam trap
"We have SessionStore, so resume after a restart is covered" is not quite right. The store does not carry memory files or artifacts, and it drops batches on write failures. A good answer combines SessionStore with a volume/sync for artifacts and an alert on mirror_error.
Checkpointing & resumability
Agents are stateful, so small errors can compound. Lessons from the Research system:
- Resume from where the agent was when the error occurred, rather than restarting from the beginning. Combine retry logic with checkpoints, and tell the agent which tool is failing so it can adapt.
- Deploying while agents are mid-run: use rainbow deployments, gradually shifting traffic to the new version while the old version keeps running.
- The lead saves its plan to Memory because context beyond 200,000 tokens gets truncated. Near the limit, the agent summarizes the completed phases and then spawns new subagents with clean contexts.
The post "Effective harnesses for long-running agents" concludes that compaction alone is not enough. The harness has two parts:
- An initializer agent creates
init.sh,claude-progress.txt, the first git commit, andfeature_list.json(more than 200 features, all"passes": false). JSON is used because the model is less likely to overwrite JSON than Markdown. - A coding agent in each session reads the progress file and the git log, runs a basic end-to-end test, works on one feature, then commits and updates the progress file.
This design blocks three failure modes: declaring the work done too early, leaving the environment broken or undocumented, and marking features "passing" without end-to-end testing.
Managed Agents clients reconnect without losing events by opening the stream first and only then sending, then fetching history with events.list() and deduplicating by event ID.
Scenario example
A code-migration agent runs for 6 hours on the Agent SDK in an autoscaling container. After every scale-down, the new session redoes features that were already finished and overwrites uncommitted code.
Correct approach: SessionStore for the transcript, plus durable artifacts (git commits, a progress file, a feature list in JSON) that the agent reads at the start of each session. Increasing the context or enabling compaction does not help, because the lost state lives on disk, not in the context.
Memory that survives interruptions
| Mechanism | Scope | Characteristics |
|---|---|---|
Memory tool memory_20250818 |
Messages API, client-side | /memories directory, commands view/create/str_replace/insert/delete/rename; do not store secrets; separate directories per user |
Memory store (beta agent-memory-2026-07-22) |
Workspace, Managed Agents | Mounted at /mnt/memory/<store-name>/; up to 8 stores/session; read_write/read_only; ≤100KB per memory; immutable versions memver_...; attached only at session creation |
| Artifacts (repo, files) | Decided by the harness | Progress file, feature list, git history |
Concurrent writes use a content_sha256 precondition. A hash mismatch returns 409 memory_precondition_failed_error, and the client must re-read and then retry. Dreaming is a scheduled process that reviews sessions and memory stores to curate memories.
Key point
Context editing and compaction work within a session. Memory works across sessions. Long-running agents usually use all three.
Surviving model version changes
- Pin versions. Every agent update on Managed Agents creates an immutable version. Sessions pin
{type: "agent", id, version}for reproducibility and rollback. Concurrent updates return 409 (optimistic concurrency). - The cache is tied to the model. Switching models mid-session loses the entire cache. To use a cheaper model for side tasks, spawn a subagent.
- The harness must evolve with the model. Claude Sonnet 4.5 showed "context anxiety" (rushing to wrap up as the context neared its limit), so the harness added context resets. With Claude Opus 4.5, that behavior disappeared and the resets became mere overhead.
(Sources: Claude Code Docs: Hosting the Agent SDK; Anthropic Engineering: Effective harnesses for long-running agents; Claude Blog: The evolution of agentic surfaces: building with Claude Managed Agents; Anthropic Skills: claude-api — Managed Agents: Memory Stores)
Architecture selection at scale
Workflow or agent: let the data decide
There are three architecture levels:
- Single request: one API call.
- Workflow: code decides the next step, following a predefined order.
- Agent: Claude chooses its own steps and tools.
Start simple. Move up a level only when evals on real data show that the current level falls short of a written definition of "a good result".
- A single request is not enough when fixing one type of input makes another type worse.
- A workflow fits when you can enumerate the steps in advance. Each step can be logged and scored, at the cost of higher latency.
- An agent is only worth it when it meets all four criteria: Complexity, Value (worth the cost and latency), Viability (Claude does this task well), and Cost of error (errors can be caught and recovered from). A single "no" means staying at the simpler level.
Evolution can go in either direction:
- Telemetry shows the agent follows the same sequence of steps for most inputs: move that group back to a workflow.
- The workflow keeps needing new branches for unforeseen cases: a signal to move to an agent, provided the cost of error still qualifies.
Scenario example
A ticket-handling agent: 85% of tickets follow the same sequence of classifying, looking up an article, and drafting a reply, at 6 times the cost of the old workflow with no difference in quality. The remaining 15% (wrong address, refunds) need an order lookup before the next step can be decided.
Best approach: a router sends the 85% back to the workflow, keeps the agent for the 15%, and has a human approve every refund. Switching to a cheaper model or dropping the agent entirely both ignore the data you already have.
Choosing a harness
There are two independent questions: who provides the harness (the loop and context management), and who provides the deployment.
| Option | Harness | Deployment | Choose when |
|---|---|---|---|
| Manual loop (Messages API) | You write it | Self-hosted | You need full control over control flow and no beta dependencies |
Tool Runner (client.beta.messages.tool_runner) |
The SDK provides the loop | Self-hosted | Agents with custom tools that need per-turn hooks (approval, retry) |
| Claude Agent SDK | Claude Code harness + built-in tools (Read/Edit/Bash/Grep…) | Self-hosted | Coding/filesystem agents running on your own infrastructure |
| Managed Agents | Anthropic | Anthropic hosts a sandbox per session | Long-running, stateful agents, versioned config, scheduled runs, dynamic workflows |
Constraints:
- Managed Agents is available (in beta) only on the Claude API and Claude Platform on AWS.
- Multiagent is not ZDR-eligible, except with self-hosted sandboxes.
- If code must stay inside your internal network, there are self-hosted sandboxes; if you need to reach MCP servers on a private network, there are MCP tunnels.
- Because inference runs in parallel with container startup, TTFT drops by about 60% at p50 and by more than 90% at p95.
Hosting the Agent SDK:
- Start with 1 GiB RAM, 5 GiB disk, and 1 CPU per agent. This is a floor; measure the actual peak RSS.
- A container costs about $0.05/hour, while token costs are usually an order of magnitude or more higher.
- Sessions have no timeout, so you must set
maxTurns/max_turns.
Exam tip
Tool Runner is not the Claude Agent SDK. Tool Runner lives in the regular API SDK and only loops over tools you define. The Agent SDK is Claude Code as a library. Both are only harnesses. Only Managed Agents adds managed deployment.
Standardizing for the team
- A default harness, with criteria for exceptions.
- Multi-tenant isolation for the Agent SDK:
settingSources: [].CLAUDE_CODE_DISABLE_AUTO_MEMORY=1, because auto memory is still loaded into the system prompt regardless ofsettingSources.- A separate
CLAUDE_CONFIG_DIR, cwd, and egress for each tenant.
- Reusable patterns: Skills, shared subagent definitions, pinned agent versions.
- End-state evaluation for agents that change their environment, together with LLM-as-judge using a rubric.
Context & memory architecture
Levers when approaching the context limit
| Mechanism | How it works | Parameters |
|---|---|---|
| Context editing | Prunes old tool results/thinking, without summarizing | Beta context-management-2025-06-27; clear_tool_uses_20250919 (option clear_tool_inputs) or clear_thinking_20251015 |
| Compaction | Summarizes old context into a server-side compaction block | Beta compact-2026-01-12, compact_20260112, default trigger at 150K tokens |
| Memory | Reads/writes files outside the context, used across sessions | memory_20250818 or a memory store |
| Subagent / programmatic tool calling | Read-heavy work runs in another context, and only the final result comes back | Roster, PTC |
Exam trap
With compaction, every turn must append the entire response.content, including the compaction block. Appending only the text silently loses the compaction state, and the context keeps growing even though the feature is enabled.
Task budgets (beta task-budgets-2026-03-13, output_config.task_budget, total ≥ 20000) are only advisory. The hard cap is the Managed Agents session budget.
Changing instructions mid-conversation without breaking the cache
The cache matches on prefix, and the render order is tools → system → messages.
| Change | Tools cache | System cache | Messages cache |
|---|---|---|---|
| Add/remove/reorder tools | Lost | Lost | Lost |
| Switch model | Lost | Lost | Lost |
| System prompt content | Kept | Lost | Lost |
tool_choice, images |
Kept | Kept | Lost |
The way to keep the cache is to put changes after the prefix:
- Mid-conversation system message: append
{"role": "system", ...}tomessages[]instead of editingsystem. Supported on Claude Opus 5, Claude Opus 5.5, Claude Opus 4.8, Claude Fable 5, Claude Fable 5.1, Claude Mythos 5, Claude Mythos 5.1, and Claude Sonnet 5.5. Not supported on Claude Sonnet 5 or Microsoft Foundry. For models without support, use a<system-reminder>text block in the user turn. - Tools:
tool_addition/tool_removal(betamid-conversation-tool-changes-2026-07-01). Tools to be added must be declared in advance withdefer_loading: true. - Per-turn reminders: don't "insert and then delete"; use
clear_at: "next_user_message". - Switching models: there is no way to keep the cache; use a subagent.
Claude Code alerts on cache hit rate and declares a SEV when the rate drops. Plan Mode is implemented with tools (EnterPlanMode/ExitPlanMode), not by swapping the tool set. Forked operations such as compaction must use exactly the parent's system, tools, and model. Things that silently break the cache: timestamps in the system prompt, UUIDs, JSON with unsorted keys. Verify with cache_read_input_tokens.
Key point
Never interpolate dynamic data (date and time, mode, user name) into the system prompt. Put it in messages. A message at turn 5 does not invalidate the cache for anything that comes before it.
Keeping large tool catalogs out of the context
- Tool search (
tool_search_tool_regex_20251119ortool_search_tool_bm25_20251119): the remaining tools are markeddefer_loading: true, and Claude loads only the relevant schemas. Schemas are appended, not swapped, so the cache is preserved. You can't defer everything: at least one tool must stay non-deferred, otherwise you get 400All tools have defer_loading set. - Skills: only the description sits in the context up front;
SKILL.mdis read when needed (progressive disclosure). - Programmatic tool calling: intermediate results stay in the code execution container and never enter the context.
Tool search is for discovery (Claude finds tools itself). Mid-conversation tool changes are for control (the application decides).
Exam tip
- "Hundreds of MCP tools, only a few used per turn" → tool search.
- "Switching modes, need to revoke permissions" → tool changes.
- "Large intermediate results across many sequential calls" → programmatic tool calling.
(Sources: Anthropic Skills: claude-api — Agent Design Patterns, Prompt Caching: Design & Optimization, Tool Use Concepts; Claude Blog: Lessons from building Claude Code: Prompt caching is everything)
Quick summary
- Multi-agent beats single-agent by 90.2% on the research eval, but uses about 15× the tokens of chat. A poor fit for tasks that need shared context.
- Delegation needs an objective, output format, tool guidance, and boundaries. Effort-scaling rules must live in the lead's prompt.
- Managed Agents: a roster of up to 20, one level of delegation, 25 child threads per session (idle ones included). For work that is too large, use dynamic workflows.
- The direction of a
thread_message_*event is relative to the thread that carries it. always_askis a human checkpoint;autois not. The session budget is create-only, and reaching the cap pauses the session.- A workflow run that is
completeddoes not mean the work meets requirements. SessionStoremirrors only the transcript, on a best-effort basis (mirror_error). The hybrid pattern requires it.- A Managed Agents session is an append-only event log. Reconnect with
events.list()and then dedupe by event ID. - Long-running agents: initializer + coding agent, progress file + git + feature list JSON, one feature per session.
- Resume from the point of failure instead of restarting from scratch. Use rainbow deployments when deploying while agents are running.
- Memory store: up to 8 per session, ≤100KB per memory,
content_sha256precondition (409). - Four criteria for choosing an agent: complexity, value, viability, cost of error.
- Context editing prunes, compaction summarizes (append the entire
response.content), memory works across sessions. - Keeping the cache: mid-conversation system messages,
tool_addition/tool_removal, tool search. To switch models, use a subagent.