Router/Worker Layering for AI Agents: Why and When to Use It

    Building agents that execute multi-step tasks often starts with a single capable model, several tools, and a long system prompt. As task volume and task length grow, context window competition, cross-task contamination, and synchronous blocking begin to surface. This article explains why a Router/Worker split addresses these problems, how task contracts and engineering practices make the separation work, and when the added complexity is not justified.

    When building agents that can continuously execute multi-step tasks, many teams begin with an intuitive approach: choose a capable model, connect several tools, and write a long system prompt so that a single session handles understanding requirements, planning steps, executing operations, and reporting results. This approach is efficient at the prototype stage, but as the number of tasks increases and individual tasks become longer, problems begin to appear. The Router/Worker layered architecture is an engineering approach proposed to address these issues. This article explains the rationale for layering from three perspectives—resource competition, context contamination, and synchronous blocking—and discusses when it is not worth introducing.

    1. The Core Problem Layering Solves Is Context Resource Competition

    A common interpretation is that layering mimics organizational structure, as if a manager-and-employee division of labor were naturally more efficient. The actual reason is more technical: a model’s context window is a limited resource, and different stages use the window in very different ways.

    The Router handles global coordination. It needs to track the progress, blocking points, and next owner of multiple tasks at the same time. Such judgments do not require the full details of every task; they require task summaries, status identifiers, and key decision results. Therefore, the Router’s context demand is low-bandwidth and short-turn.

    The Worker handles the progress of a single task. It needs to read code, execute commands, analyze error stacks, and try fixes. Raw tool output is often long, and each step may affect subsequent paths. Therefore, the Worker’s demand is high-bandwidth and long-turn.

    The table below compares the typical characteristics of the two roles.

    Dimension Router Worker
    Focus Overall state across multiple tasks Specific details of a single task
    Information form Summaries, status, identifiers Raw logs, code, error stacks
    Turn rhythm Short turns, frequent switching Long turns, sustained progress
    Window usage Should remain small Grows dynamically with the task

    If the same session handles both roles at once, the window is quickly occupied by two different types of information. Global judgment becomes vague because there are too many details, and execution precision drops because global information is too noisy. The value of layering is to separate these two pressures structurally.

    2. The First Problem with Monolithic Agents: Cross-Task Context Contamination

    Suppose an agent handles Task A and Task B at the same time. In Task A, it tries several approaches, most of which prove unworkable, and it accumulates a large amount of logs. This content continues to occupy the window. When Task B begins, the model may treat a conclusion from Task A that was already overturned as a premise for Task B, producing errors that are difficult to notice.

    Many people try to solve this problem with prompts, for example by writing “forget the previous content” in the conversation. This is unreliable. Window usage is not released by a single instruction; old information still participates in the model’s attention computation and may affect output.

    A more effective approach is physical isolation. Each task executes in an independent sub-session, and sub-sessions exchange information only through agreed structured results. Discarded approaches from Task A do not enter Task B’s context. Isolation is guaranteed by the architecture, not by the model voluntarily following instructions.

    The following is an illustrative scheduling structure, used only to explain the isolation relationship:

    1. class Router:
    2. def __init__(self):
    3. self.tasks = {} # stores only task summaries and status
    4. def dispatch(self, task_id, goal):
    5. worker = Worker(task_id=task_id, goal=goal) # each task has its own context
    6. self.tasks[task_id] = {"status": "running", "goal": goal}
    7. worker.start_async()
    8. return task_id
    9. def on_worker_report(self, task_id, report):
    10. # receives only structured summaries, not the full execution process
    11. self.tasks[task_id].update(
    12. status=report["status"],
    13. conclusion=report["conclusion"],
    14. )

    The key point of this code is that the data structure held by the Router is small. It only cares about status and conclusions; the full process of the task remains inside the Worker.

    3. The Second Problem with Monolithic Agents: Synchronous Blocking

    The second problem relates to execution. Suppose the main session synchronously waits for a complete test or build. Before the command returns, the session can neither receive new user messages nor check the progress of other tasks. From the user’s perspective, the agent appears to be stuck.

    After layering, the Router can dispatch a long-running task to a Worker and then return immediately, continuing to serve new requests or process status updates from other tasks. When the Worker completes, it notifies the Router through a callback or message queue, and the Router updates the task status.

    1. def handle_user_message(msg):
    2. if is_long_running(msg):
    3. task_id = router.dispatch(new_task_id(), goal=msg.text)
    4. return f"Started processing. Task ID: {task_id}. You will be notified when it is complete."
    5. return router.answer_directly(msg)

    There are two key points here. First, dispatch is non-blocking, so the Router’s response time no longer depends on task duration. Second, the user gets a clear task identifier for later progress queries or cancellation.

    4. Contracts Are Key to Making Layering Work

    Layering only separates roles; boundaries must be enforced by contracts. Otherwise, the Worker will pass large amounts of intermediate state back to the Router, and window pressure will return to the main session.

    A practical task contract usually includes the following four parts:

    1. Input specification: goal description, constraints, available tool scope, and timeout.
    2. Output specification: status enum (success, failure, needs human intervention), conclusion summary, and artifact references.
    3. Error specification: failure reason categories, whether retryable, and suggested next actions.
    4. Resource specification: directories the Worker can read and write, accessible service scope, and maximum execution steps.

    An illustrative report message is as follows:

    1. {
    2. "task_id": "task-001",
    3. "status": "success",
    4. "conclusion": "All unit tests passed; coverage did not decrease.",
    5. "artifacts": ["report/test-summary"],
    6. "next_action": null
    7. }

    Reported content is limited to conclusions and artifact references, not full logs. Logs can be stored in storage and read on demand by the Worker or a dedicated query capability when needed. This keeps the Router’s window lean.

    5. Engineering Details to Watch During Implementation

    The stability of a layered architecture depends on several details.

    State management: Task state should be persisted, not only held in the memory of a session. After a session interruption, the Router can restore scheduling based on the state table.

    Timeouts and retries: Each Worker needs a timeout. After a timeout, it should not wait indefinitely; it should be marked as abnormal, and the Router should decide whether to retry, switch to another strategy, or request human intervention. Retry counts must have an upper limit.

    Failure isolation: The failure of one Worker should not affect other tasks. This is one direct benefit of physical isolation.

    Concurrency control: When multiple Workers operate on the same code repository or the same resource at the same time, locking or branch isolation is needed to avoid overwriting each other. Such coordination should be handled by the Router, not by Workers competing on their own.

    Observability: Record the start time, end time, status changes, and key decision points for each task to facilitate troubleshooting. Logging services and monitoring alerts can take on this responsibility.

    6. When Layering Is Not Worth It

    Layering increases system complexity. Tasks need protocols, state needs persistence, and debugging paths become longer. If a scenario has the following characteristics, a monolithic agent may be more suitable:

    • Tasks are short and can be completed within the window in a single session.
    • Tasks do not intersect and there is no parallel requirement.
    • Users are not sensitive to response latency and do not need to check progress midway.
    • The team is small, and the cost of maintaining a layered system exceeds the benefit.

    The criterion is whether layering can reduce actual resource competition and blocking; the sophistication of the architecture itself is irrelevant. At the prototype stage, directly using a monolithic structure and quickly validating requirements is usually a more pragmatic choice. When task volume, length, and concurrency demands grow to a certain level, introduce layering, and the migration cost is more controllable.

    7. Conclusion

    The essence of the Router/Worker layered architecture is to separate high-bandwidth execution details from low-bandwidth global coordination, and to constrain their interaction through contracts. It mainly addresses three types of problems: context window resource competition, cross-task contamination, and synchronous blocking. Whether to adopt layering should depend on task complexity, concurrency requirements, and maintenance cost.