Layered Architecture for AI Agents: A Practical Guide to Router and Worker Design
This article explains why a layered Router/Worker architecture works better than a single monolithic agent as tasks grow in number and length. It treats the context window as a scarce resource, breaks down coordination versus execution workloads, and details the two structural flaws of a single large agent: cross-task context pollution and synchronous blocking. You will find clear responsibility boundaries and contracts for Router and Worker, three approaches to handling blocking with their trade-offs, guidance on when layering is not worth the cost, and a deployment checklist.
1. The Starting Point: Treating the Context Window as a Scarce Resource
Most teams begin building an agent the same way: pick a capable model, attach a set of tools, write a long system prompt, and let it handle everything. This works well in a demo because there are few tasks, the turns are short, and the context is not yet full. But as the number of tasks grows and individual task chains get longer, problems appear in batches: answers drift off track, old conclusions get cited repeatedly, the interface hangs for a long time, and failed tasks contaminate later decisions.
To understand why a layered architecture like Router/Worker holds up, you first need to drop the intuition of “mimicking an organizational chart.” A manager leading employees is only an analogy. The real driver is resource constraints: the context window has limited capacity, attention gets diluted across long contexts, and every round of inference costs both time and latency. Layering is not about looking more “advanced”; it is about letting different kinds of work consume different kinds of resource budgets.
A single agent run can be split into two types of load:
- Coordination load: needs a global view but has low detail requirements per task. It only cares about identifiers, status, summaries, blockers, and who owns the next step. Its traits are low bandwidth, short turns, and high-frequency decisions.
- Execution load: cares about only one task but needs extremely high bandwidth, including error stacks, attempted solutions, raw tool returns, code snippets, and diffs. Its traits are high bandwidth, long turns, and deep progress.
When the same session carries both types of load, the window gets repeatedly squeezed by two kinds of information with completely different rhythms, and degradation is almost inevitable.
2. Two Structural Flaws of a Monolithic Agent
2.1 Cross-Task Context Pollution
Imagine one session handling task A and task B in parallel. Abandoned attempts in A, large log blocks, and failed command output will occupy the window for a long time. When you switch to B, the model is likely to mistake A’s intermediate conclusions for B’s premises, showing up as “wrong attribution” style reasoning errors.
Relying on the prompt to tell the model to “ignore the previous text” is unreliable, and the reason is straightforward: the prompt is a soft constraint, while the window budget is a hard constraint. A single sentence will not make tokens release automatically. The workable path is physical isolation—each task runs in an independent sub-session, and only structured results are handed back to the upper layer.
A schematic isolation structure:
RootSession(Router)├── task:A -> WorkerSession A (independent window)├── task:B -> WorkerSession B (independent window)└── task:C -> WorkerSession C (independent window)
2.2 Synchronous Blocking
If the main session synchronously waits for a long command to return, such as a full test run or build, then before it returns it can neither accept new requests nor judge the progress of other tasks in parallel. From the user’s side, it feels “stuck.” After layering, the Router dispatches a task and is released immediately, continuing to receive and schedule work; the Worker advances in the background and feeds results back when done.
3. Responsibilities and Contract Design After Layering
The benefit of layering does not come from “splitting” but from “splitting cleanly.” A layered design with blurry boundaries degrades into two hops of forwarding, doubling the cost while the benefit drops to zero.
The Router’s responsibility boundary:
- Task identification and decomposition, maintaining a task list and state machine (pending / in progress / blocked / done / failed).
- Holds only summary-level information: goal, constraints, acceptance criteria, current status, dependencies.
- Dispatch, timeout control, retry and escalation policies.
- Result convergence and conflict resolution, presenting a unified message to the user.
The Worker’s responsibility boundary:
- Single-task closure: read context, call tools, verify results, and produce a structured deliverable.
- Does not perceive other tasks and does not hold global state.
- When it hits a problem that needs a cross-task decision, it throws it upward rather than guessing on its own.
The contract should be fixed with an explicit structure to avoid the semantic drift caused by free text:
{"task_id": "T-102","goal": "Fix the failing test cases in the specified module","constraints": ["Do not change public interfaces", "A single run must not exceed the given time limit"],"acceptance": ["Target cases pass", "No new warnings"],"budget": { "max_rounds": 12, "max_tokens": 60000 },"result": {"status": "done|blocked|failed","summary": "A one-paragraph overview of the root cause and the fix","artifacts": ["diff summary", "verification output summary"],"open_questions": []}}
When feeding results back, only summaries and necessary artifacts are allowed into the Router window; raw long logs stay on the Worker side or are written to external storage and accessed by reference address. This rule is the key gate for controlling window growth.
4. Three Solutions to Synchronous Blocking and Their Trade-offs
- Async dispatch + completion callback: the Router returns immediately, and the Worker feeds results back when done. Suited to tasks that can run in parallel with weak dependencies on each other.
- Bounded wait + status polling: the Router waits for a fixed duration, then switches to background continuation after a timeout and reports progress to the user. Suited to interactive scenarios that need immediate feedback.
- Streaming progress reporting: the Worker periodically reports phase events (start / key step / blocked / end), and the Router only does stream forwarding. Suited to observability needs for long-chain tasks.
Engineering also requires supporting pieces: task-level timeouts and max rounds, idempotent retries, failure isolation (a single task failure does not affect the whole), and a concurrency cap to prevent the number of Workers from spiraling and overwhelming the quota in reverse.
5. When Layering Is Not Worth It
Layering has costs: extra scheduling logic, state persistence, observability work, and debugging complexity. Keep a monolith in the following cases:
- A single task with a short chain and a single-digit number of rounds;
- Strong serial dependencies, where the next step must have all the details of the previous one;
- The team lacks infrastructure such as state storage, logging, and monitoring/alerting, so problems cannot be located after layering;
- A very tight latency budget, where cross-layer serialization and scheduling overhead take up too high a share.
The decision rule can be simplified to one sentence: split only when “context contention” and “mutual waiting” become the main bottlenecks; otherwise, optimize the prompt and tool granularity first.
6. Deployment Checklist
- Have you accounted separately for the information bandwidth needs of global coordination versus single-task execution?
- Is there mutable context shared across tasks, and can it be changed to physically isolated sub-sessions?
- Is the task contract structured, and are the acceptance criteria machine-verifiable?
- Have long commands been changed to async, and can the user continuously see progress?
- Do you have task state persistence, a logging service, and monitoring/alerting so failure causes can be traced back?
- Have you set a concurrency cap, timeouts, and retry limits to avoid resource runaway?
In practice at Baidu AI Cloud, this kind of layering is typically paired with a container platform to carry the elastic concurrency of Workers, a message queue to decouple dispatch and feedback, object storage to hold long-text artifacts, and logging and monitoring/alerting to ensure observability—thereby gaining both isolation and responsiveness under a limited window budget.
