Agent Layered Architecture: Solving Context Pollution with Routing and Execution Separation

    This article explains why a single powerful model with tools struggles with complex agent tasks, and how a layered architecture separates a routing layer from execution layers. It covers the core constraint of the context window, two structural failures—cross-task context pollution and synchronous blocking—and how physical isolation, asynchronous dispatch, and contract-based boundaries address them. It also lists the supporting engineering capabilities and the cases where layering is not worth adopting.

    1. The Starting Point: Why “One Smart Model Plus a Set of Tools” Cannot Handle Complex Tasks

    When building agent systems, the most common initial approach is to pick a model capable enough, attach a set of tools, and write a system prompt long enough to let a single session carry all responsibilities. This works well in a demo, because the task is narrow, the turns are short, and context pressure is low.

    Once you move into real business scenarios, the number of tasks grows, execution time stretches, and tool outputs get larger. The single-session model quickly exposes structural flaws. The root cause is not that the model is not smart enough, but that two kinds of work with completely different natures are stuffed into the same context space.

    The approach the industry is converging on is layering: introduce a routing layer (Router) responsible for global coordination, plus several execution layers (Workers) responsible for advancing individual tasks. To be clear, layering is not about imitating the “manager leading employees” idea from organizational management, nor is more complex structure automatically more advanced. It is an engineering conclusion derived from resource constraints and fault isolation needs. Layering also has costs, and later sections give the criteria for judging when it is not worth introducing.

    2. The Essential Constraint: The Context Window Is a Low-Bandwidth Resource That Is Not Automatically Reclaimed

    To understand a layered architecture, you first need an accurate mental model: the context window is not memory. It is a budget with fixed capacity that is not released by semantic instructions.

    The Router and the Worker have needs at two extremes:

    • The routing layer needs low-bandwidth, short-turn judgment information: task identifier, current state, summary, blocking point, and where the next step belongs. It tracks multiple tasks at once, and details from any single task crowd out the global view.
    • The execution layer needs high-bandwidth, long-turn progress information: full error stacks, approaches already tried, raw tool returns, and intermediate artifact paths. This information directly determines whether the next action is correct.

    An illustrative comparison of responsibilities and context characteristics:

    1. Dimension Routing layer (Router) Execution layer (Worker)
    2. Task granularity Parallel tracking of many Exclusive to one task
    3. Context need Low bandwidth, summary High bandwidth, raw detail
    4. Turn rhythm Short turns, frequent Long turns, continuous
    5. judgments progress
    6. Failure impact Global scheduling drift Single task can retry
    7. Termination All tasks converge Current task done

    When the same session plays both roles, the window is alternately filled by two kinds of information, which produces two frequent failures.

    3. Failure One: Cross-Task Context Pollution

    Suppose an agent handles task A and task B in parallel. In task A, abandoned approaches after trial and error, large blocks of logs, and failed command output keep occupying the window. When scheduling switches to task B, the model is likely to mistake A’s old conclusions for B’s premises, producing “wrong attribution” style reasoning errors.

    This pollution has three characteristics that determine it cannot be fixed by prompts:

    1. Invisibility: the polluting content exists as natural language and is formally indistinguishable from the current task description, so the model lacks a reliable signal for identifying its source.
    2. Accumulation: window usage only grows and never shrinks, and the later it gets, the more easily the weight of an erroneous premise is amplified.
    3. Non-reclaimability: writing “ignore the above” in a prompt is only a semantic request, and the budget is not released as a result.

    The effective solution is physical isolation rather than semantic constraint: each task runs in an independent sub-session, the sub-session receives only the inputs the task needs, and at the end it returns only a structured result.

    1. # Illustration: the execution layer runs in a separate session and returns only a structured summary
    2. def run_worker(task: dict, tools: dict) -> dict:
    3. session = create_session(system_prompt=task["prompt"]) # brand-new context
    4. for step in range(task.get("max_steps", 20)):
    5. result = call_model(session, tools=tools)
    6. if result.done:
    7. break
    8. session.append(result.raw) # high-bandwidth detail stays inside the sub-session
    9. return {
    10. "task_id": task["id"],
    11. "status": "done" if result.done else "failed",
    12. "summary": summarize(session), # only the summary goes back to the routing layer
    13. "artifacts": result.artifacts, # artifacts are passed by reference, not by content
    14. }

    The key point is that high-bandwidth content never enters the routing layer; the routing layer holds only references and summaries.

    4. Failure Two: Synchronous Blocking and Throughput Collapse

    The second structural problem comes from synchronous waiting. If the main session waits synchronously for a long command to return, such as a full test run, a full build, or batch data processing, then before it returns the main session can neither accept new requests nor judge the progress of other tasks. From the user’s side, this feels like “it is stuck.”

    After layering, the routing layer dispatches a task and returns immediately, continuing to receive new requests and make scheduling decisions, while the execution layer advances long-turn work in the background and reports back as an event or callback when done.

    1. # Illustration: the routing layer dispatches without blocking, and the execution layer reports asynchronously
    2. def router_loop(inbox, workers):
    3. while True:
    4. msg = inbox.get()
    5. if msg.kind == "new_task":
    6. worker = workers.pick(msg.task) # choose an execution layer
    7. worker.submit(msg.task) # return immediately, do not wait
    8. continue
    9. if msg.kind == "worker_report":
    10. state.update(msg.task_id, msg.summary) # update only state and summary
    11. if state.all_converged():
    12. return state.finalize()

    The benefit is a simultaneous improvement in throughput and responsiveness: the duration of long tasks no longer turns into system-level latency, and concurrency is determined by the number of execution layers rather than by the serial capability of a single session.

    5. Boundary Design: Hold the Layering with Contracts, Not Prompts

    Physical separation solves only half the problem; the other half is the discipline of inter-layer communication. If the routing layer and the execution layer communicate in free text, pollution flows back in another form. So the boundary needs to be contractual:

    • Input contract: the execution layer receives only the task goal, constraints, a whitelist of available tools, and a timeout limit, and does not receive the history of other tasks.
    • Output contract: fixed fields for status, summary, artifact references, and failure classification; returning raw large objects is prohibited.
    • Permission contract: tool and data access is granted minimally per task, to avoid one execution layer reaching other tasks’ resources beyond its authority.
    • Quota contract: set step, duration, and context limits for each execution layer, and terminate and report on exceeding them, to prevent a single task from dragging down the whole.
    1. {
    2. "task_id": "T-1024",
    3. "status": "failed",
    4. "failure_class": "tool_timeout",
    5. "summary": "The build timed out during dependency fetching and was retried once",
    6. "artifacts": ["ref://log/T-1024/build"],
    7. "next_action_hint": "rerun_with_cached_deps"
    8. }

    The value of contracts is that they turn the soft constraint of “hoping the model understands” into a hard constraint that can be validated, tested, and monitored.

    6. Supporting Engineering Capabilities

    For a layered architecture to run stably, it usually needs general cloud capabilities to work with it. Only general categories are described here: use a message queue to carry task dispatch and result reporting, achieving peak shaving and decoupling; use object storage to hold large intermediate artifacts, so layers pass only references; use a container platform to carry elastic scaling and fault restart for the execution layer; use logging services and monitoring alerts to build observability for step counts, durations, and failure classifications. Together these capabilities keep layering controllable under concurrency and failure scenarios.

    7. When Layering Is Not Worth Introducing

    Layering is not the default answer. Prefer a single session in these cases:

    • The task is narrow and turns are short, and context pressure is far from reaching the limit;
    • End-to-end ultra-low latency is required, and the extra dispatch and aggregation overhead is unacceptable;
    • The team lacks a foundation in contract design and observability, and layering would only turn implicit coupling into distributed failures;
    • In the prototype validation stage, the value of fast trial and error outweighs structural completeness.

    The criterion can be simplified to one sentence: do not layer while cross-task pollution and synchronous blocking have not yet become reproducible problems; once both appear reliably and prompts and retries cannot converge them, the benefit of layering begins to exceed the cost.

    8. Summary

    The logic behind a layered architecture is not mysterious: the context window is a scarce resource that is not automatically reclaimed, and routing and execution need opposite bandwidth, so they must be physically separated; synchronous waiting amplifies long-task latency into system-level latency, so dispatch must be asynchronous; free-text communication lets pollution flow back, so contracts must hold the boundary. Once these three points are clear, architecture selection is no longer a matter of style preference but a derivable engineering conclusion.