Multi-Agent Orchestration Patterns: Hierarchical Supervisors, Swarms, and Peer Debates

Multi-Agent Orchestration Patterns: Hierarchical Supervisors, Swarms, and Peer Debates

An engineer asks an agent to retire a deprecated client function that is called from dozens of modules. The agent starts well, reads the first few files, makes the change, runs the tests, and fixes a failure. Forty minutes later its context is full of diffs it no longer needs, it has forgotten which modules it already migrated, and it reports the job finished while a third of the call sites still use the old function. Nothing in the model got worse. The task simply outgrew what one context window, read sequentially, can hold and track.

The obvious response is to hire more agents, and that is where most multi-agent projects go wrong. Splitting a task across agents does not add intelligence; it adds coordination, and coordination has costs that a single agent never pays: lost context at every handoff, conflicting edits, duplicated work, runaway loops, and a token bill that multiplies. Some tasks justify that cost and many do not. This article covers the three families of coordination that actually show up in practice (supervisor-worker hierarchies, swarm-style handoffs, and peer debate), the mechanisms behind each, a worked example with code, the failure modes that only appear when several agents share a job, and a way to choose between them or decide to stay with one.

1. Start with one agent and find where it breaks

A multi-agent design is a response to a specific limit, so name the limit before choosing the design. A single agent fails in a small number of recognisable ways, and each failure points at a different remedy.

  • Context exhaustion. The task needs more material than fits, or the working history grows until early facts are ignored. The remedy is to give sub-tasks their own fresh context and pass back only summaries.
  • Serial latency. The sub-tasks are independent but run one after another. The remedy is parallel workers.
  • Role interference. One prompt must be a planner, an implementer and a harsh reviewer at once, and the roles bleed. The remedy is separate agents with separate instructions, often separate tool sets.
  • Self-confirmation. The agent that wrote the answer reviews it and agrees with itself. The remedy is an independent reviewer, ideally with different information or a different model.
  • Tool sprawl. The agent has so many tools that it picks poorly. The remedy is specialists with small, relevant tool sets.

If none of these describes your failure, more agents will not help. Teams often reach for a multi-agent framework because a single-agent prompt is underspecified or its tools return too much text; fixing the prompt and trimming tool output is cheaper than orchestration. Engineering write-ups from labs that build research agents report the same trade: multi-agent setups can outperform a single agent on broad, parallelisable work, and they consume substantially more tokens to do it. Treat that as the default expectation, not an anomaly.

2. The supervisor-worker pattern

In a hierarchical design one agent, the supervisor (also called the orchestrator or lead), owns the goal. It decomposes the work into sub-tasks, dispatches each to a worker agent, collects results, and decides what happens next. Workers do not talk to each other; all information flows through the supervisor. The shape is familiar from distributed systems: it is a coordinator with stateless workers.

What makes it work

The supervisor holds the plan and the global state, so workers can be small, focused and disposable. Each worker starts with a clean context containing only its brief, which is the main defence against context exhaustion. The supervisor's own context stays manageable because it receives compact results rather than the workers' full transcripts. And because the control flow is centralised, there is one place to enforce budgets, retries, permissions and logging.

The brief is the interface

A worker knows nothing except what its brief says, so the brief must be self-contained: the goal, the exact files or resources in scope, the constraints that must hold, the definition of done, and the format of the result. The classic failure is a one-line delegation such as "fix the failing test", which forces the worker to rediscover what the supervisor already knew. A good brief also states what the worker must not touch. Delegating understanding, as in "based on your findings, implement it", is a defect, because the supervisor is the one who synthesised the findings and must write the specific instruction.

Where it breaks

The supervisor is a bottleneck and a single point of failure. If it decomposes the task badly, every worker does the wrong thing in parallel. If it accepts worker claims at face value, errors pass straight through. And because it sees only summaries, it can miss problems that the full transcript would have shown. Guard against all three by making the plan inspectable, by verifying results with code rather than with the worker's own report, and by letting workers return a structured "blocked, here is why" instead of forcing a guess.

3. Pipelines, fan-out and fan-in

Not every multi-agent system needs an intelligent coordinator. Two simpler topologies cover a large share of real needs and are easier to reason about.

A pipeline chains agents in a fixed order: extract, then transform, then review, then format. Control flow is ordinary code, each stage has a typed input and output, and failures are easy to localise because you can see which stage produced the bad artifact. Pipelines suit work whose stages are known in advance. Their weakness is rigidity: if stage three discovers that stage one misunderstood the request, the system has no path back unless you build one.

Fan-out and fan-in runs the same kind of task over many independent items in parallel, then merges. Searching ten sources, reviewing forty files, or trying three solution strategies are all fan-out. The fan-in step is where the intelligence goes: deduplicating, resolving contradictions, ranking, or picking a winner. Two rules prevent most trouble. First, the items must really be independent, meaning no shared files and no ordering dependency. Second, the merge must be deterministic where possible. Sorting, deduplicating by key and taking a union are code, not model calls.

Many successful systems are simply a supervisor that plans once and then runs a fan-out of workers behind a verification gate. That is the shape of the worked example in section 6.

4. Swarms and handoffs

In a swarm or handoff design there is no central planner. Each agent has a role and a set of tools, and any agent can hand the conversation to another by calling a transfer function. A triage agent hands a billing question to the billing agent, which may hand an account-closure request to a retention agent. Several agent SDKs expose this as a first-class concept, where handing off is just another tool call that changes which agent speaks next.

The strengths are flexibility and low overhead for conversational systems. Each agent keeps a short prompt and small tool set, and the route emerges from the conversation. The weaknesses are the same properties seen from the other side. With no owner of the global goal, loops are possible: A hands to B, who hands back to A. The shared conversation history grows as it passes along, so context can balloon or, if you trim it, lose the facts the next agent needs. And debugging is harder, because the path taken is data rather than code.

Swarms earn their place where the set of specialists is stable and the routing signal is clear from the conversation itself: customer support, intake desks, assistants that cross a few product areas. They are a poor fit for long-running work with a shared artifact such as a codebase, where concurrent agents with no coordinator will overwrite each other. If you use handoffs, add explicit guards: a maximum hop count, a rule that a handoff must carry a written summary of what is known, and a terminal state that a human or a supervisor owns.

5. Peer debate and critic loops

The third family is about correctness rather than throughput. In a critic loop one agent produces and another reviews, and the producer revises against the critique until the reviewer is satisfied or a round limit is hit. In a debate several agents answer independently, see each other's answers, argue, and converge on a result, or a judge picks. Published research on multi-agent debate, including work by Du and colleagues in 2023, reported gains in factuality and reasoning on several benchmarks compared with a single model answering once. That is evidence the idea can work, not a promise that it will on your task.

Why independence matters more than headcount

Five copies of the same model with the same prompt and the same context are not five independent opinions; their errors are correlated, and they tend to agree with each other for the same wrong reason. Debate and review help in proportion to how different the participants are: different models, different information (one reviewer sees only the diff and the requirements, not the author's reasoning), different instructions (one hunts for bugs, one hunts for missing tests), or different tools (one can execute code). A reviewer who can run the tests is worth more than three who can only read.

Failure modes

Agents in a debate can be talked into the wrong answer by a confident peer, so a debate without ground truth sometimes converges on something fluent and false. Critic loops can oscillate, where the producer fixes what the critic named and breaks something else. And both cost multiples of a single call. Put a hard round limit on every loop, ask the critic for specific, checkable objections instead of general impressions, and prefer executable checks over argument whenever the claim can be tested. Use debate for judgement calls such as design trade-offs or ambiguous requirements, where there is no test to run.

6. Worked example: retiring a deprecated function across a codebase

Return to the opening scenario and design it properly. The goal is to replace calls to fetch_user_v1 with fetch_user across a repository, keeping behaviour identical.

  1. Plan once, with code doing the discovery. A search finds every call site. The supervisor groups call sites into tasks by module so that no two tasks share a file. This grouping is the one place the supervisor needs judgement, and it must also reject any plan in which two tasks overlap.
  2. Isolate each worker. Every worker gets its own checkout on its own branch, so a half-finished edit in one cannot break another's tests.
  3. Brief precisely. Each brief lists its files, the mapping from old to new signature, the behaviours that must not change, the test command, and the output format.
  4. Verify outside the worker. After a worker reports success, the supervisor runs the tests in that worker's checkout. A worker's statement that tests pass is a claim, not evidence.
  5. Merge sequentially. Verified branches merge one at a time, with the full suite run after each, because two individually correct changes can still conflict semantically.
  6. Review independently. A reviewer agent that sees only the final diff and the requirement looks for call sites that were silently skipped and for behaviour changes.

The supervisor core can be small. The sketch below shows the parts that matter: disjointness enforcement, bounded parallelism, a shared budget, retries, and verification by exit code. The worker call is deliberately left as a stub for whichever agent runtime you use.

import asyncio
import subprocess
from dataclasses import dataclass

MAX_PARALLEL = 4
MAX_ATTEMPTS = 2
WORKER_TOKEN_CAP = 200_000
TOTAL_TOKEN_BUDGET = 2_000_000


@dataclass(frozen=True)
class Task:
    id: str
    files: tuple[str, ...]
    goal: str


@dataclass
class Result:
    task_id: str
    ok: bool
    notes: str
    tokens: int = 0


def assert_disjoint(tasks: list[Task]) -> None:
    owner: dict[str, str] = {}
    for t in tasks:
        for f in t.files:
            if f in owner:
                raise ValueError(f"{f} is assigned to both {owner[f]} and {t.id}")
            owner[f] = t.id


async def run_worker(task: Task, workspace: str, token_cap: int) -> Result:
    """Call your agent runtime here. It must write only inside `workspace`."""
    raise NotImplementedError


def tests_pass(workspace: str) -> bool:
    return subprocess.run(["make", "test"], cwd=workspace).returncode == 0


async def supervise(tasks: list[Task], workspace_for) -> list[Result]:
    assert_disjoint(tasks)
    gate = asyncio.Semaphore(MAX_PARALLEL)
    spent = 0

    async def attempt(task: Task) -> Result:
        nonlocal spent
        for _ in range(MAX_ATTEMPTS):
            async with gate:
                if spent >= TOTAL_TOKEN_BUDGET:
                    return Result(task.id, False, "budget exhausted")
                ws = workspace_for(task)
                res = await run_worker(task, ws, WORKER_TOKEN_CAP)
                spent += res.tokens
            # Evidence comes from running the tests, not from the worker's report.
            if res.ok and await asyncio.to_thread(tests_pass, ws):
                return res
        return Result(task.id, False, "failed verification after retries")

    outcomes = await asyncio.gather(*(attempt(t) for t in tasks), return_exceptions=True)
    return [
        o if isinstance(o, Result) else Result(t.id, False, f"crashed: {o!r}")
        for t, o in zip(tasks, outcomes)
    ]

Three choices in that code are worth defending. The semaphore keeps parallelism at a number your rate limits and machine can sustain, instead of whatever the plan happens to contain. The budget is checked before every attempt, so a loop that burns tokens stops itself. And return_exceptions=True means one crashed worker produces a failed result for its task instead of cancelling the rest. The merge and review steps follow the same pattern and are omitted for length.

Verification by exit code beats verification by narrative. A worker saying "all tests pass" is the cheapest claim in the system to produce and the most expensive to be wrong about. Make the supervisor run the check itself, in the worker's isolated workspace, before any result is accepted.

7. Failure modes that only appear with many agents

  • Error compounding. If each step in a chain is correct with some probability below one, the end-to-end success rate falls with chain length. Longer chains need checkpoints that catch errors early, not just a review at the end.
  • Context loss at handoffs. Whatever the receiving agent is not told, it does not know. Summaries drop caveats first. Pass structured fields (decisions made, files touched, open questions) rather than free-form recaps.
  • Write conflicts. Agents editing the same files, database rows or external tickets produce lost updates and merge conflicts. Assign ownership of every mutable resource to exactly one agent, or give each its own isolated copy and merge deliberately.
  • Runaway loops and cost. Agents that can spawn agents, or hand off indefinitely, can multiply without bound. Cap depth, fan-out, rounds and total tokens, and make the caps part of the runtime rather than a request in a prompt.
  • Correlated blind spots. A producer and reviewer built on the same model with the same context share failures. Differ the information, the model or the tools.
  • Silent partial success. Fan-out returns thirty of forty results and the merge step reports success on thirty. Count what was expected, compare with what arrived, and fail loudly on the difference.
  • Unobservable decisions. When something goes wrong in a swarm, you need the path. Log every dispatch, handoff, tool call and verification result with a task identifier.

8. Choosing a topology

The table compares the families on qualitative properties. The cost column describes how the cost scales, not a measured amount; treat any real figures as something to measure on your own workload.

Topology Who controls the flow Parallelism Typical failure Cost shape Best fit
Single agent The one agent None Context exhaustion, self-confirmation Lowest; grows with context length Bounded tasks that fit in one context
Supervisor-worker Supervisor plans and aggregates High, if sub-tasks are independent Bad decomposition, unverified worker claims Multiplies with workers plus briefs Large tasks that split cleanly
Pipeline Fixed code-defined stages Per stage or per item No path back from early misunderstanding Predictable, one call per stage Known sequence of transformations
Swarm with handoffs Agents route among themselves Usually sequential Handoff loops, history bloat Low per turn, hard to bound overall Conversational routing among stable specialists
Peer debate or critic loop Rounds with a judge or stop rule Within a round Confident agreement on a wrong answer Multiple calls per round, per participant Judgement calls and review where tests cannot decide

A decision checklist

  1. Can a single agent do it with a better prompt and trimmed tool output? If yes, stop.
  2. Are the sub-tasks independent? If yes, fan-out or supervisor-worker. If they are ordered, use a pipeline.
  3. Is the route unknown until the conversation unfolds, among a stable set of specialists? Consider handoffs, with hop limits.
  4. Is correctness the problem, and can the claim be tested? Run the test. If it cannot be tested, use an independent reviewer or a debate.
  5. Who owns each mutable resource? If two agents could write the same thing, redesign.
  6. What are the caps on depth, fan-out, rounds and tokens, and where are they enforced?

The principles of a typed agent stack follow the same logic: work is split into typed, narrow decisions, parallel workers get isolated workspaces, and nothing counts as done until a verification step has actually run. The topology is secondary to those three properties.

9. What to do on Monday

If you are starting from a single agent that struggles, resist adopting a framework first. Take your worst recent failure and classify it using the list in section 1. Then make the smallest change that addresses that class.

Common mistakes

  • Adding agents to compensate for an unclear task description.
  • Letting workers share a working directory.
  • Accepting worker self-reports as evidence.
  • Passing full transcripts between agents instead of structured summaries.
  • Using identical models and identical context for producer and reviewer, then trusting the agreement.
  • Giving agents the ability to spawn agents without a depth limit.

Frequently asked questions

How many workers should run in parallel? As many as your rate limits, machine resources and merge capacity can absorb, and no more than there are independent sub-tasks. Start low, observe the failure rate and the wait on rate limits, and raise it with evidence.

Should the supervisor be the strongest model? Often the planning and verification steps benefit most from a capable model, while narrow, well-briefed worker tasks can run on a cheaper one. Test that on your tasks rather than assuming it.

Do I need a framework? Not to begin. The sketch in section 6 is a few dozen lines of ordinary code. Adopt a framework when you need its persistence, tracing or human-in-the-loop features, and keep the verification and budget logic in code you own.

What is the first experiment to run? Take a task that currently fails because of context size, split it into two or three independent parts with written briefs, run them in isolated workspaces, verify each with executable checks, and compare success and total tokens against the single-agent attempt. If the multi-agent version is not clearly better on both reliability and cost-adjusted effort, you have learned that this task does not need it.