Agent Layered Architecture: How Router and Worker Solve the Context Bottleneck
This article explains why a single powerful model with a set of tools breaks down as tasks grow, and how a Router/Worker layered architecture addresses two recurring failure modes: cross-task context pollution and synchronous blocking. It covers the rationale for separation, the information needs of each role, a task contract with budget boundaries, a scheduling skeleton, trade-offs, and a practical implementation checklist.
Introduction: Why “One Smart Model Plus a Bunch of Tools” Doesn’t Scale
The most common starting design for an agent system is straightforward: pick a capable model, attach a set of tools, and write one very long prompt that covers every situation, letting a single session handle all responsibilities. This works smoothly in a demo because there are few tasks, the turns are short, and the context window is not yet full.
As the number of tasks grows, execution chains get longer, and concurrent requests increase, two problems reliably reappear. First, information from different tasks interferes within the same context: the model treats an abandoned conclusion from a previous task as a premise for the current one. Second, the main session gets pinned by a single long-running command; while waiting, it can neither accept new requests nor make progress on other tasks.
The Router/Worker layered architecture is a joint solution to both problems. Its essence is not to mimic an organizational hierarchy, nor is it “more complex means more advanced.” It is the coordinated design of context engineering and scheduling engineering: physically separating execution processes that compete for the same window resource, then using explicit contracts to hold the boundaries.
1. The Root Cause of Layering: The Context Window Is a Scarce Resource
To understand layering, start by accepting a fact: the context window is a limited and expensive shared resource. Different roles have completely different demand profiles for it.
The Router (routing/main session) needs a low-bandwidth, short-turn global view. It tracks multiple tasks at once and needs to know what stage each task is in, where it is stuck, and who should handle the next step. It consumes summaries, task identifiers, state machine fields, and key conclusions, not raw logs. Its rhythm is “decide, dispatch, keep receiving.”
The Worker (execution sub-agent) needs a high-bandwidth, long-turn local context. It is the one actually modifying files, running commands, and locating defects. Stack traces, approaches already tried, and raw tool output can each change the next decision. Its rhythm is “load, execute, converge, report.”
If one session plays both roles, the window quickly fills with two kinds of heterogeneous information: the state needed for global coordination gets drowned in noise, and the details needed for local execution get compressed by summaries into something unusable. The first value of layering is giving each bandwidth requirement a suitable information environment.
2. Two Typical Failure Modes of a Monolithic Session
2.1 Cross-Task Context Pollution
Imagine one session handling Task A and Task B in parallel. The abandoned approach in A, along with large stack traces and intermediate artifacts, keeps occupying the window. When it is B’s turn, the model may mistake A’s old conclusion for an existing premise of B, producing output that “looks reasonable but is actually misaligned.”
Relying on a prompt that tells the model to “ignore the preceding text” is unreliable, and the reason is direct: a prompt is a soft constraint, while the window budget is a hard constraint, and the former does not trigger the release of the latter. The workable approach is physical isolation: run each task in a separate sub-session and return only structured results, eliminating cross-contamination by mechanism.
2.2 Synchronous Blocking and Head-of-Line Blocking
If the main session synchronously waits for a full build or a complete test run to return, it can neither accept new user requests nor assess the progress of other tasks in parallel until the result arrives. To the user, the system appears “frozen.” More subtly, there is head-of-line blocking: one slow task holds up the entire scheduling chain, so even later tasks that need very little time get no chance to run.
After layering, the Router dispatches a task and returns immediately, continuing to receive and schedule; the Worker focuses on convergence within its own session. Separating scheduling authority from execution authority is the structural prerequisite for eliminating blocking.
3. The Benefits of Layering: Isolation, Concurrency, and Observability
- Context isolation: Each Worker has an independent window; failures and noise are confined locally and do not pollute global judgment.
- Concurrency and throughput: Multiple Workers can advance non-conflicting tasks in parallel while the Router polls status at low bandwidth, so overall throughput rises with the degree of parallelism.
- Cost control: The Router handles only summaries, so per-turn token consumption is low; high-bandwidth raw information exists only inside the Worker and is discarded after use.
- Observability and replayability: With clear task boundaries, logs, metrics, and traces can be sliced by task, making failure localization and regression verification easier.
- Permission and security convergence: Tool credentials and high-risk operations can be pushed down to the Worker side with least privilege, so the Router never touches the sensitive execution surface directly.
4. Contract Design: The Real Key to Making Layering Work
Layering is not splitting a prompt into two parts; it requires defining stable interface contracts. At minimum, include the following fields:
{"task_id": "t-20240612-001","goal": "Fix the login timeout issue","constraints": ["Do not modify public interfaces", "A single run must not exceed 10 minutes"],"input_refs": ["repo://service-auth", "log://recent-errors"],"budget": { "turns": 30, "tokens": 120000, "wall_clock_sec": 600 },"output_schema": {"status": "done | blocked | failed","summary": "One-sentence conclusion","artifacts": ["diff", "test_report"],"unresolved": ["Migration script that needs manual confirmation"]}}
The contract must hold three boundaries: the information boundary (the Worker returns only summaries and artifact references, not raw long text), the permission boundary (tools and credentials are granted per task with least privilege), and the budget boundary (terminate and report once the turn count, tokens, or wall-clock time is exceeded). The Router uses status to re-dispatch, degrade, or hand off to a human, rather than rereading all the details.
A sketch of the scheduling skeleton is as follows (pseudocode):
def router_loop(inbox):while True:req = inbox.accept() # Low-bandwidth intake, non-blockingtask = normalize(req) # Generate task_id and the contractspawn_worker(task) # Dispatch asynchronously, return immediately# The main loop keeps receiving new requests and status reportsdef worker_loop(task):ctx = load(task.input_refs) # High-bandwidth local contextfor _ in range(task.budget.turns):r = act(ctx) # Call tools, run commandsif r.done or r.blocked:return report(task.task_id, summarize(ctx, r))return report(task.task_id, status="failed", reason="budget_exceeded")
5. Costs and Applicability: When Not to Introduce Layering
Layering is not free. It adds scheduling overhead, contract maintenance costs, and debugging complexity; global insight shared across tasks is weakened because the Router sees only summaries. The following scenarios are better kept monolithic: a single task with a short chain; extreme latency sensitivity with no need for concurrency; a prototyping stage that requires fast prompt iteration; and tasks that are tightly coupled and must share a large amount of intermediate detail.
The decision rule can be summed up in one sentence: introduce layering when context contention and synchronous blocking become the main bottlenecks; stay monolithic when collaboration costs exceed the benefits of isolation. In practice, a compromise is also common: start with “serial isolation” (run only one Worker at a time, but keep an independent session), then gradually evolve toward parallel scheduling.
6. Implementation Checklist
- Define the output contract first, then write the scheduling logic, to avoid writing prompts first and patching the interface later.
- Set a hard budget for each task and terminate on exceedance, preventing a single task from consuming all resources.
- Assemble summaries from structured fields, and avoid letting the model freely generate long text to return.
- Send status reports over a message queue or event bus to decouple the Router from the Workers.
- Write long-running artifacts to object storage and pass only reference addresses in the context.
- Aggregate metrics by
task_idusing a logging service and monitoring alerts to observe blocking and failure rates. - Grant least privilege for tool calls; high-risk operations require a second confirmation or handoff to a human.
- Preserve replay capability: rerun a single task from a contract snapshot to verify that a fix is effective.
Conclusion
The logic behind Router/Worker layering can be compressed into one sentence: use physical isolation to solve context pollution, use the separation of scheduling and execution to solve synchronous blocking, and use contracts to hold the three boundaries of information, permission, and budget. It is neither an organizational metaphor nor a complexity contest. When deploying on the cloud, combining common capabilities such as message queues, object storage, container platforms, logging services, and monitoring alerts is enough to support a layered agent system that is observable, replayable, and cost-controlled; in scenarios with simple, tightly coupled tasks, staying monolithic is the more rational choice.
