Agent Layered Architecture: Solving Context Pollution and Synchronization Blocking

    This article explains why a single powerful model with a pile of tools does not scale, and how a Router/Worker layered architecture addresses two core failure modes: cross-task context pollution and synchronous blocking. It covers the resource rationale behind layering, the contracts that keep boundaries clear, the scheduling model that moves waiting off the critical path, when layering is not worth the cost, and a practical checklist for implementation.

    Agent Layered Architecture: Solving Context Pollution and Synchronization Blocking

    Introduction: Why “One Smart Enough Model Plus a Bunch of Tools” Doesn’t Go Far

    In the early stages of agent development, the most common approach is to put a capable model at the center, attach a set of tools, and write a long prompt covering every possible situation so it can handle everything. This structure works smoothly in demos: the chain is short, debugging is intuitive, and tweaking the prompt produces immediate results.

    But as the number of tasks grows, individual tasks get longer, and concurrent requests start to stack up, problems erupt all at once: the model starts “misremembering” the conclusion from a previous task, the main loop becomes unresponsive to the outside world while waiting on a long-running command, and the prompt keeps growing while becoming harder to maintain. These symptoms are not a matter of insufficient model capability; they are resource allocation problems at the architecture level.

    The Router/Worker layered architecture is a joint solution to exactly these problems: it is both a solution for context engineering and a solution for scheduling engineering. The core idea comes down to two sentences—physically separate the parts that compete for the same window resource, then hold the boundary with explicit contracts. It is not meant to imitate an organizational hierarchy, nor is more complex automatically more advanced. Below, the logic behind it is unpacked from the angles of resources, failure modes, contract design, scheduling models, and applicability boundaries.

    1. The Essence of Layering: The Context Window Is a Scarce Resource

    Many people understand layering as an organizational metaphor of “a manager leading employees,” which mistakes the result for the cause. The real reason is that the context window is a limited, expensive resource that cannot be reclaimed at will, while different types of work have completely different demand profiles for it.

    The Router (routing/main session) has a low-bandwidth, short-turn profile. It handles global coordination: what tasks are on hand, what stage each is at, where things are stuck, and who should get the next step. It needs summaries, task identifiers, state machine fields, and a few key conclusions—not the full raw details of any single task. Each of its decisions is short, but decisions come at a high frequency, so it requires the window to stay clean, stable, and quickly scannable.

    The Worker (execution sub-agent) has a high-bandwidth, long-turn profile. It does the actual work: reading files, changing code, running commands, inspecting error stacks, comparing approaches already tried, and digesting raw tool output. This content is large and noisy, but critical for making progress right now. It needs an uninterrupted continuous window to fully absorb the details before advancing one step.

    Cramming both needs into the same session means the window gets alternately squeezed by two kinds of fundamentally different information: on one side, ever-expanding raw logs; on the other, global state that must stay clear. The result is that neither side gets the input quality it needs—the Router’s view is drowned in noise, and the Worker’s context is diluted by unrelated tasks.

    2. Two Typical Failures of a Monolithic Session

    2.1 Cross-Task Context Pollution

    Suppose the same session advances Task A and Task B in parallel. The abandoned approaches from trial and error in A, blocks of logs, and failed command output all keep occupying the window. When processing switches to B, the model is likely to mistake A’s old conclusions for B’s premises, producing “mismatched” reasoning.

    A common but ineffective response is to write “please ignore the preceding content” in the prompt. The problem is that the prompt is a soft constraint, while the window budget is a hard constraint. You cannot make token usage release automatically with a single sentence, nor can you guarantee the model will reliably perform “selective forgetting” over a long context. As turns accumulate, attention gets diluted by history, and instruction-following inevitably degrades.

    The effective approach is physical isolation: each task runs in its own sub-session with an independent lifecycle and non-overlapping context. When a task finishes, only a structured result is handed back to the upper layer, rather than leaving the entire process in the shared window.

    1. # Anti-pattern: shared window
    2. [Task A raw logs × 3000 tokens][Task B requirements][Task A abandoned approach][Task B tool output] ...
    3. # Target pattern: isolation + structured return
    4. Router window: [Task A: status=done, summary][Task B: status=running, pending decision]
    5. Worker-A window: only A's process details (reclaimed when A ends)
    6. Worker-B window: only B's process details

    2.2 Synchronous Blocking

    The second failure comes from the scheduling layer. If the main session synchronously waits for a long command to return—for example, a full test run, a full build, or a batch data processing job—then until it returns, it can neither accept new user requests nor gauge the progress of other tasks. From an external view, the agent is simply “stuck.”

    The cost of synchronous blocking is more than latency; it breaks the interaction contract: users lose feedback, timeout mechanisms get triggered, upstream retries cause duplicate execution, and it can even trigger concurrent write conflicts on the same resource.

    After layering, the Router only needs to dispatch the task and register its status, then immediately return to a responsive state, continuing to receive new requests and collect results. Waiting is moved off the critical path, and long-running work is encapsulated inside the Worker.

    3. Contracts First: Four Boundaries Layering Must Hold

    Layering without contracts just splits the chaos into two copies. What truly makes the architecture work is the interface agreements.

    1. Task contract: Dispatch must carry the goal, constraints, acceptance criteria, and references to known context (not the context itself). Acceptance criteria cannot be omitted, otherwise the Worker cannot self-judge whether it is done.
    2. Return contract: The Worker returns only a structured result, such as status, conclusion, change list, key evidence, and failure reason. The raw process stays in the sub-session and is reclaimed with it.
    3. State contract: Define an explicit state machine for tasks (e.g., pending / running / blocked / done / failed), with state transitions driven by events, avoiding the Router guessing via polling.
    4. Permission contract: Clarify the scope of operations available to the Worker and the limits on irreversible operations; out-of-scope operations must go back to the upper layer for confirmation.

    An illustrative interface description (pseudocode, expressing only the shape of the contract):

    1. class TaskSpec(BaseModel):
    2. task_id: str
    3. goal: str
    4. constraints: list[str]
    5. acceptance: list[str] # acceptance criteria, required
    6. context_refs: list[str] # references, not inline, to control bandwidth
    7. class TaskResult(BaseModel):
    8. task_id: str
    9. status: Literal["done", "blocked", "failed"]
    10. summary: str # low-bandwidth conclusion
    11. changes: list[str] # change list
    12. evidence: list[str] # key evidence, not full logs
    13. reason: str | None = None

    4. Scheduling Model: Moving Waiting Off the Critical Path

    The second dividend of layering is controllable concurrency and backpressure. As the scheduler, the Router needs to explicitly manage concurrency, queuing, and timeouts.

    • Asynchronous dispatch: Dispatch returns immediately, results flow in via events or callbacks, and the Router keeps short turns.
    • Concurrency limit: Cap the number of simultaneously running Workers to avoid resource contention and write conflicts; the excess enters a queue.
    • Timeout and retry: Set a budget for each type of task; after a timeout, mark it blocked and retain diagnostic information; retries must be idempotent.
    • Result merging: Conclusions from multiple Workers are reconciled by the Router for conflicts; when conflicts remain unresolved, expose the choice to the user rather than guessing.
    • Observability: Record state transitions and duration metrics for the task chain, and observe backlog and failure rates through general logging services and monitoring/alerting capabilities.
    1. Router main loop (pseudo-flow)
    2. while True:
    3. event = wait_next_event() # new request / task finished / timeout
    4. if event.type == "request":
    5. task = build_spec(event) # fill in acceptance criteria
    6. dispatch(task) # non-blocking
    7. elif event.type == "finished":
    8. merge(event.result) # structured merge
    9. elif event.type == "timeout":
    10. mark_blocked(event.task_id)

    5. When Layering Is Not Worth It

    Layering has costs: an extra scheduling layer, an extra contract to maintain, and an extra observability setup. Keep the monolith in the following scenarios:

    • The task is single and short, with few interaction turns, and can be completed within one session;
    • There is no concurrency need, and user requests are naturally serial;
    • The team does not yet have state and logging infrastructure, and layering would actually make problems harder to locate;
    • During prototype validation, when fast trial and error is needed, premature layering slows iteration.

    The judgment can be simplified to one sentence: Do not layer prematurely when context contention and waiting blockage are not yet the main sources of failure. Architectural complexity should be driven by real failures, not by what “looks more advanced.”

    6. Implementation Checklist

    1. Can you explicitly list the minimum state fields the Router needs? If you can’t, the boundary isn’t thought through.
    2. Does every task have a decidable acceptance criterion?
    3. Is the Worker’s return a structured summary rather than the raw process?
    4. Are there any code paths that synchronously wait on long commands?
    5. Are the concurrency limit, timeout, and retry idempotency defined?
    6. Is there task-level state tracking and failure diagnostic information?

    Conclusion

    The value of Router/Worker layering is not an extra node on the architecture diagram, but that it separates two conflicting needs: it lets the coordinator keep a clear, low-bandwidth view, and gives the executor a continuous, high-bandwidth space; at the same time, it fixes boundaries with contracts and removes blocking with asynchronous scheduling. It is not the product of an organizational metaphor, but an engineering necessity under resource constraints. Understanding this, you can layer decisively when needed and stay simple when not—which matters more than memorizing any architecture diagram.