Engineering Practices for Long-Term Tasks and Multi-Agent Collaboration
As LLM applications transition from simple single-turn Q&A to complex long-term tasks, engineers face new challenges such as limited context windows, state loss, and error amplification. This article explores engineering practices for building robust multi-agent systems. It covers common collaboration patterns, layered architecture design, and key implementation details including state machines, dependency scheduling, and cost control. Furthermore, it provides guidance on observability, phased deployment strategies, and scenarios where multi-agent architectures might not be the optimal choice.
1. From Single-Turn Q&A to Long-Term Execution
Early LLM applications were primarily single-turn Q&A systems. Tasks had clear boundaries, outputs could be directly reviewed by humans, and the cost of errors was low.
Current requirements are evolving. A development task might require continuous operation for hours, spanning code retrieval, modification, testing, and documentation generation. A data processing pipeline might involve multiple systems, requiring continuous monitoring and automatic recovery upon exceptions. These are known as long-term tasks, characterized by numerous steps, extended durations, multiple intermediate states, and dependencies between steps.
Long-term tasks introduce three direct engineering challenges:
- Limited context: The model’s context window cannot accommodate the entire history, causing early critical information to be pushed out.
- State loss: Process interruptions, timeouts, or rate limits can erase in-progress execution. Restarting from scratch wastes resources and may produce duplicate side effects.
- Error amplification: If an error in a sub-step is not isolated, it can propagate along the dependency chain, ultimately corrupting the entire task’s output.
Solving these issues depends not on choosing the right model, but on the surrounding orchestration and governance design.
2. Three Common Patterns of Multi-Agent Collaboration
When a single execution unit cannot complete a task within a reasonable timeframe, the task can be divided among multiple agents for parallel or serial processing. There are three common organizational patterns.
Master-Worker Pattern: A master node is responsible for decomposing tasks, assigning sub-tasks, and aggregating results. Workers focus only on their assigned sub-tasks and do not communicate directly with each other. This pattern offers a clear structure, making it easy to uniformly manage budgets and permissions, and is the default choice for most scenarios. The trade-off is that the master node can easily become a bottleneck, and the quality of decomposition directly determines the overall outcome.
Pipeline Pattern: Tasks pass sequentially through multiple agents in fixed stages, such as requirements analysis, solution design, coding, and review. The output of each stage is the input for the next. The process is predictable and easy to debug, but a delay in one stage slows down the entire chain.
Shared Blackboard Pattern: Multiple agents collaborate around a shared state store, reading and updating its contents independently. It is suitable for exploratory tasks, such as multi-directional information research. However, concurrent writes require strict version control to prevent mutual overwriting.
The trade-offs among the three patterns are summarized below:
| Dimension | Master-Worker | Pipeline | Shared Blackboard |
|---|---|---|---|
| Predictability | Medium | High | Low |
| Parallelism | High | Low | High |
| Debugging Difficulty | Medium | Low | High |
| Permission & Budget Control | Easy | Easy | Hard |
| Applicable Scenarios | General decomposition tasks | Fixed-stage processes | Exploration & research |
Most production systems use a hybrid of these three patterns. For example, the outer layer uses the master-worker pattern for scheduling, while a specific sub-task internally adopts a pipeline.
3. Layered Architecture Design
It is recommended to split the system into five layers, each with a single responsibility, facilitating independent evolution and testing.
- Orchestration Layer: Maintains the task dependency graph and determines which tasks are eligible for execution.
- Execution Layer: Actually invokes models and runs sub-agents, responsible for isolating the context of individual executions.
- State Layer: Writes task status, intermediate artifacts, and checkpoints to persistent storage to support breakpoint recovery.
- Tool Layer: Encapsulates calls to external capabilities, such as object storage, message queues, container platforms, logging services, and code repositories. The tool layer uniformly handles authentication, timeouts, and retries.
- Governance Layer: Responsible for budget, permissions, auditing, and human confirmation. It spans all other layers and holds veto power over high-risk operations.
The value of layering lies in clear boundaries. For instance, when changing the model implementation in the execution layer, the orchestration logic requires no modification; when adjusting retry policies, only the tool layer needs to be updated.
4. Key Implementation Details
4.1 Explicit Task State Machine
Every task should have a clear state: Pending, Running, Done, or Failed. State transitions should only occur through the orchestration layer to prevent arbitrary modifications elsewhere. This ensures that the task state is traceable at any given moment.
4.2 Dependency Scheduling and Concurrency Limits
A task can only execute after all its dependencies are completed. Concurrency must have an upper limit; otherwise, multiple sub-tasks simultaneously requesting the same service can easily trigger rate limits and cause costs to spiral out of control. The following code provides a simplified orchestrator where concurrency is controlled via a semaphore, and retries use exponential backoff.
import asynciofrom dataclasses import dataclass, fieldfrom enum import Enumclass Status(Enum):PENDING = "pending"RUNNING = "running"DONE = "done"FAILED = "failed"@dataclassclass Task:task_id: strdeps: list[str] = field(default_factory=list)status: Status = Status.PENDINGretries: int = 0max_retries: int = 3result: object = Noneclass Orchestrator:def __init__(self, tasks, executor, max_concurrency=8):self.tasks = {t.task_id: t for t in tasks}self.executor = executor # async execution function injected by the callerself.sem = asyncio.Semaphore(max_concurrency)def ready_tasks(self):return [t for t in self.tasks.values()if t.status is Status.PENDINGand all(self.tasks[d].status is Status.DONE for d in t.deps)]async def _run_one(self, task: Task):async with self.sem:task.status = Status.RUNNINGtry:task.result = await self.executor(task)task.status = Status.DONEexcept Exception:task.retries += 1if task.retries > task.max_retries:task.status = Status.FAILEDelse:task.status = Status.PENDINGawait asyncio.sleep(2 ** task.retries)async def run(self):while True:batch = self.ready_tasks()if not batch:breakawait asyncio.gather(*(self._run_one(t) for t in batch))return {tid: t.status for tid, t in self.tasks.items()}
Two points require attention in this code. First, if an upstream dependency fails, the downstream task will never enter a ready state, and the loop will end. Therefore, after execution concludes, you should check for any unfinished tasks and report them upward, rather than assuming everything succeeded. Second, the execution function must be idempotent. When a task is executed multiple times due to retries, it should not produce duplicate side effects, such as creating duplicate resources or sending duplicate messages.
4.3 Checkpoints and Breakpoint Recovery
After each task is completed, its result and status should be immediately written to persistent storage. Upon process restart, the orchestrator first reads the completed records, skips those tasks, and only executes the remaining parts. Checkpoint granularity requires balancing: too fine increases storage and write overhead, while too coarse loses too much progress during a failure. Typically, “one model call or one tool call” is a suitable unit.
4.4 Structured Handoff for Sub-Agents
The content returned by sub-agents should not be a large block of free text. The master node requires information that can be directly consumed. It is recommended to agree on a unified output structure, such as:
{"task_id": "analyze-module-a","conclusion": "Module A's cache invalidation logic has a race condition","evidence": ["cache/store.py line 88", "Concurrent test case 3 failed to reproduce"],"open_items": ["Confirm production environment concurrency level"],"risk_level": "medium","confidence": 0.7}
Structured output offers three benefits. The master node can mechanically verify whether all fields are present; aggregation requires no re-reading of the full text; and the content passed to the next agent is more compact, effectively mitigating context bloat.
4.5 Budget and Cost Control
The cost of long-term tasks is easily overlooked. Each task should have a token budget, a call limit, and a time limit. Upon exceeding these limits, execution should automatically pause and preserve the current state. Budgets can be tiered: a global budget constrains the entire task, while individual sub-task budgets are allocated by the master node based on importance. An example configuration is as follows (values are for structural illustration only and should be adjusted based on actual load):
budget:global_max_tokens: 2000000global_max_wall_time_minutes: 240per_task_max_tokens: 150000per_task_max_calls: 40max_concurrency: 8on_exceed: checkpoint_and_pause
Setting on_exceed to pause rather than terminate outright allows humans to decide whether to add budget or discard the results.
4.6 Least Privilege and Human-in-the-Loop
The tool layer should declare required permissions per task, granting only the necessary scope of access. High-risk operations—such as deleting data, modifying production configurations, sending external messages, or changing permissions—must undergo human confirmation. The confirmation node should display the operation target, impact scope, and rollback method, rather than just providing a simple “OK” button.
5. Observability
The execution path of a multi-agent system is not linear. If you only look at the final output when troubleshooting, it is nearly impossible to pinpoint the cause. It is recommended to establish observability capabilities in the following areas:
- Assign a unique trace ID to each user request, threading it through all logs across orchestration, execution, and tool calls.
- Log the input size, output size, latency, and status of every model call to analyze cost and latency distributions.
- Provide a task progress view showing the status of each node, dependencies, and current bottlenecks.
- Categorize and statistically analyze failures, distinguishing between timeouts, rate limits, validation failures, and business logic errors, as their handling methods are completely different.
Logs should not contain keys, credentials, or sensitive user data. This information should be masked before being written, or only reference identifiers should be logged.
6. Deployment Path and Evaluation Metrics
It is not recommended to launch a complete multi-agent system all at once. A more prudent approach is a three-step rollout.
Step 1: Select a repetitive, easily verifiable task type and run the process with a single agent plus checkpoints. The goal here is to verify the reliability of state persistence and recovery mechanisms.
Step 2: Introduce the master-worker pattern, breaking the task into several parallel sub-tasks, and set concurrency limits and budgets. The focus here is to observe decomposition quality and cost changes.
Step 3: Gradually expand the scope of tasks and establish long-term tracking metrics. It is recommended to monitor at least the following four:
- End-to-end task success rate, distinguishing between complete success, partial success, and failure.
- Average and tail latency, especially the 95th percentile latency, which reflects user experience better than the average.
- Cost per successful task, meaning the resources consumed per successful result.
- Human intervention rate, the proportion of tasks requiring manual intervention. A consistently rising intervention rate usually indicates that orchestration or permission design still has flaws.
7. When Not to Use Multi-Agent Systems
Multi-agent systems are not a universally optimal solution. In the following scenarios, a single agent or a traditional deterministic process is often more appropriate:
- Task steps are tightly coupled; splitting them requires frequent synchronization, making coordination costs higher than parallel benefits.
- Results require strict reproducibility, but model outputs have inherent randomness.
- Highly sensitive to costs, and the task itself can be reliably accomplished using rules or scripts.
- The team lacks experience with distributed execution, state consistency, and fault recovery; the system complexity will exceed maintenance capabilities.
Technology selection should start with task characteristics. First, break down the problem clearly, then decide how many agents are needed and how they should collaborate—rather than fitting the task into a predetermined architecture.
