Multi-Agent Collaboration in Production: From Long-Horizon Coding to Task Orchestration
This article explains how LLM applications evolve from Q&A tools into execution engines that plan work, call tools, coordinate agents, and track state. It covers context lifecycle management for long-horizon coding, multi-agent scheduling with dependency graphs and concurrency control, heterogeneous roles and routing, reliability mechanisms such as checkpoints and backpressure, and token-based cost estimation. The focus is on engineering practices for long-running, stable agent systems, including key trade-offs and common failure modes.
1. From Q&A Tools to Execution Engines
LLM usage has roughly gone through three stages. In the first stage, the model acts as an information container and mainly answers questions; typical use cases are Q&A systems and knowledge base assistants. In the second stage, the model becomes a generation engine that can write articles, generate images, and complete code. In the third stage, the model becomes an execution engine: it needs to decompose goals on its own, call tools, collaborate with other agents, and record execution state.
Once applications enter the third stage, the engineering focus shifts from “answering correctly” to “running for longer and running reliably.” Developers need to handle three issues: how to manage context during long runs, how to synchronize state across multiple agents, and how to recover after errors. The following sections address these three issues.
2. Long-Horizon Coding: Managing the Context Lifecycle
When a task lasts for hours or even days, the model cannot keep all historical content in the active context. A common approach is to divide context into three layers:
- Working memory: stores the real-time state of the current subtask. It is the shortest layer and is updated most frequently.
- Task memory: records conclusions from completed steps, such as “the API has been changed to v2 and tests passed.”
- Long-term memory: stores knowledge that can be reused across tasks, such as project coding conventions and dependency versions.
Each layer can have an independent token budget, and older content can be periodically compressed into summaries. Detailed processes for completed subtasks move to archival storage, and later steps read the relevant summaries when needed. Summaries may lose details, so sample checks are needed to verify summary accuracy.
For large codebases or knowledge bases, files can first be chunked and indexed with vectors. Each time, only the most relevant chunks are loaded into context instead of reading everything at once.
Regarding runnable duration, teams should not directly trust a single number. Actual duration depends on model version, task type, and resource configuration. The most reliable approach is to test with your own real tasks and record when context overflow, summary distortion, and duplicated work appear.
3. Multi-Agent Scheduling: Task Decomposition and State Consistency
When a single agent has limited capability, tasks can be split across multiple agents for parallel processing. The scheduler needs to do three things: decompose tasks, dispatch subtasks, and collect results.
Decomposition can use static rules or be dynamically generated by a main agent. Either way, subtasks often have dependencies. The scheduler should maintain a dependency graph and dispatch downstream tasks only after their prerequisites are complete.
When multiple agents write to shared resources at the same time, concurrency control is required. There are three common patterns:
- Primary-backup model: the main agent holds global state, and subagents submit results transactionally.
- Shared blackboard: all agents read and write the same data structure, and each write carries a version number. On a version conflict, the agent re-reads and then writes again.
- Message queue: agents collaborate through asynchronous messages and do not call each other directly. This structure makes scaling and troubleshooting easier.
For resources, each agent should have independent CPU, memory, and timeout limits. Concurrency depends on available resources and downstream API quotas; there is no universal recommendation.
The following code sample illustrates the basic flow of dependency ordering, bounded retries, and escalation handling:
from collections import defaultdict, dequeMAX_RETRIES = 2 # Maximum retries for a single subtask; adjust based on failure ratedef run_task(task, pool, decompose, build_context):subtasks = decompose(task) # Returns {id: Subtask(deps, role, timeout)}indegree = {sid: len(s.deps) for sid, s in subtasks.items()}children = defaultdict(list)for s in subtasks.values():for d in s.deps:children[d].append(s.id)ready = deque(sid for sid, n in indegree.items() if n == 0)attempts = defaultdict(int)results = {}while ready:sid = ready.popleft()sub = subtasks[sid]attempts[sid] += 1agent = pool.acquire(role=sub.role)try:res = agent.execute(sub, context=build_context(sub, results),timeout=sub.timeout)results[sid] = resfor child in children[sid]:indegree[child] -= 1if indegree[child] == 0:ready.append(child)except TimeoutError:if attempts[sid] <= MAX_RETRIES:ready.append(sid)else:raise RuntimeError(f"Subtask {sid} exceeded retry limit; escalating to manual handling")finally:pool.release(agent)return results
This code is illustrative only. It does not implement pool, decompose, or build_context, nor does it handle concurrency locks, permission checks, or subtasks added during execution. These parts need to be completed before direct production use.
4. Heterogeneous Roles and Task Routing
Different agents can take on different roles:
- Planner: decomposes goals, analyzes dependencies, and sets priorities.
- Executor: writes code, runs tests, and processes data.
- Reviewer/QA: runs unit tests and static scans and checks edge cases.
- External interactor: confirms requirements with users or third-party systems.
Routing decisions are usually based on task type labels, input size, required capabilities, priority, and timeout.
Routing can be implemented in two ways. One is to write rules into the main controller agent’s prompt. This approach is flexible, but its output is hard to reproduce and audit. The other is to use deterministic matching in code. This approach is testable and auditable, but new scenarios require manual rule additions. In practice, a hybrid approach is often used: high-frequency scenarios are covered by code rules, while low-frequency exceptions are handled by the main agent, with its decision rationale logged.
Common routing mistakes include:
- Routing rules are out of sync with the role capability table, so tasks are assigned to agents that lack the required capability.
- The reviewer and executor use the same prompt, so review results lose independence.
- Routing decisions are not logged, making it impossible to trace the cause after an issue occurs.
A “role cluster” combines several roles into a reusable collaboration template. It reduces the work of redesigning the process for every new task and makes human review of system behavior easier.
5. Stability: Checkpoints, Backpressure, and Capacity
For unattended operation, checkpoints are essential. At fixed intervals, the system writes agent runtime state, context summaries, and task progress to persistent storage. When an exception occurs, the system recovers from the latest checkpoint without starting over.
In addition to checkpoints, the following mechanisms should be configured:
- Health checks: periodically confirm that agents are still producing results. If there is no response beyond a threshold, restart automatically.
- Transaction log: record every state change so that data can be verified after recovery.
- Backpressure and queuing: limit the number of concurrent requests at the application layer. When the queue is full, return a clear message to avoid burst traffic directly hitting the model service.
- Degradation path: after the same subtask fails repeatedly, move it to manual review or a simplified flow.
Capacity planning should be based on real traffic estimates. When a new model is first launched, traffic fluctuations are often large, so it is advisable to reserve headroom and set rate-limiting thresholds.
6. Cost Estimation: From Tokens to Tasks
In multi-agent scenarios, the cost of a single task no longer grows linearly with a single request. It can be estimated with the following formula:
Single-task cost ≈ Σ(input tokens per subagent × input unit price) + Σ(output tokens per subagent × output unit price) + scheduling and storage overhead
Assume a task is split into 40 subagents, each with an average of 20,000 input tokens and 2,000 output tokens. Total input is 800,000 tokens, and total output is 80,000 tokens. If the input price is 2 yuan per million tokens and the output price is 8 yuan per million tokens, the model invocation cost is approximately 1.6 yuan plus 0.64 yuan, for a total of about 2.24 yuan. Unit prices should be based on vendor-published pricing.
This result only includes model invocation fees, not scheduling, storage, or retry overhead. Retries can multiply token consumption, so estimates should add a coefficient based on historical average retry counts.
