Multi-Agent Orchestration and Long-Running Task Execution: An Architecture Guide

    Large language models are evolving from "information containers" that merely answer questions into "execution engines" that can plan, call tools, and carry tasks through to completion. Public reports claim that new-generation models can work continuously for extended periods and support hundreds of parallel sub-agents. These figures come from vendor or media sources and have not been independently verified, so this article does not treat them as established conclusions. Instead, we focus on three things developers genuinely need to master: how to store state, how agents can reliably exchange messages, and how to keep the system under control at high load.

    1. The Prerequisite for Long-Running Execution: Keep State Outside the Context Window

    Model context windows are limited. After a long task runs for dozens of steps, early decisions and errors are easily pushed out of the window. Long-running execution therefore typically relies on external state storage.

    • Vector databases: store historical experience, document fragments, and log summaries for semantic retrieval.
    • Key-value or relational databases: store structured state such as task IDs, current steps, variables, and completed tool calls.

    The basic flow of each loop is as follows:

    1. Read the task state and record its version number.
    2. Build the context for this round based on the state.
    3. Call the model to get a plan or tool-call instructions.
    4. Execute the tools and validate the returned results.
    5. Write the state back using the version number as the write condition. If the write fails, re-read the state and retry.
    6. After each key step completes, write a checkpoint.

    Key parameters and boundaries to watch when implementing:

    • Context compression threshold: when context usage exceeds roughly 70% of the window, compress earlier history into a summary. The summary must retain unfinished items, key decisions, and failure records—not just final conclusions.
    • Concurrent write conflicts: only one writer may modify a given task’s state. If multiple writers are unavoidable, use optimistic locking—compare version numbers before writing. On conflict, retry up to 3 times; if it still fails, escalate to manual handling or a dead-letter queue.
    • Tool-call idempotency: generate an idempotency key for every tool call. When replaying from a checkpoint, successful calls read their historical results directly instead of executing again. This is especially important for side-effectful operations such as transfers, sending emails, and database writes.
    • Recovery strategy: after a task fails, load state from the most recent checkpoint. For operations that occurred after the checkpoint but before the failure, use idempotency keys to determine whether they already took effect, and re-execute only those that did not.

    Here is an example of version-checked state writes:

    1. from dataclasses import dataclass, field
    2. @dataclass
    3. class TaskState:
    4. task_id: str
    5. version: int = 0
    6. step: int = 0
    7. data: dict = field(default_factory=dict)
    8. class StateStore:
    9. def __init__(self):
    10. self._rows: dict[str, TaskState] = {} # Replace with a database or KV store in production
    11. def load(self, task_id: str) -> TaskState:
    12. return self._rows.get(task_id, TaskState(task_id=task_id))
    13. def save(self, state: TaskState, expected_version: int) -> bool:
    14. """Optimistic-lock write: rejects and returns False if the version does not match"""
    15. current = self._rows.get(state.task_id)
    16. current_version = current.version if current else 0
    17. if current_version != expected_version:
    18. return False
    19. state.version = expected_version + 1
    20. self._rows[state.task_id] = state
    21. return True

    2. Multi-Agent Collaboration: Route Messages by Role—Never Share a Single Queue

    The most common first mistake in multi-agent systems is letting all agents share one queue, with each agent pulling messages and then deciding whether the message belongs to its role. Once a mismatched message is pulled and not put back, it is permanently lost. Result messages without a target role cannot be routed correctly either.

    The correct approach:

    • Use a separate queue per role, or a topic exchange that routes by role. Agents only consume their own role’s queue.
    • Multiple consumers can compete for the same role’s queue, enabling horizontal scaling.
    • Acknowledge messages only after successful processing. Failed or timed-out messages are requeued.
    • Assign a unique task ID to each message; consumers use it for deduplication so repeated delivery does not produce duplicate side effects.
    • Messages exceeding the maximum retry count go to a dead-letter queue for manual or dedicated inspection.
    • Set a capacity limit on queues. When a queue is full, producers wait or reject new tasks, creating backpressure and preventing unbounded memory growth.

    The following example shows a minimal implementation of these mechanisms:

    1. import asyncio
    2. import uuid
    3. from dataclasses import dataclass, field
    4. from typing import Awaitable, Callable
    5. @dataclass
    6. class Message:
    7. role: str # Target role
    8. payload: dict
    9. task_id: str = field(default_factory=lambda: str(uuid.uuid4()))
    10. attempts: int = 0
    11. class Router:
    12. def __init__(self, roles: list[str], max_attempts: int = 3, capacity: int = 1000):
    13. self.queues = {r: asyncio.Queue(maxsize=capacity) for r in roles}
    14. self.dead_letter: asyncio.Queue = asyncio.Queue()
    15. self.max_attempts = max_attempts
    16. async def publish(self, msg: Message) -> None:
    17. await self.queues[msg.role].put(msg) # Blocks when the queue is full, creating backpressure
    18. async def requeue_or_dead_letter(self, msg: Message) -> None:
    19. msg.attempts += 1
    20. if msg.attempts >= self.max_attempts:
    21. await self.dead_letter.put(msg)
    22. else:
    23. await self.queues[msg.role].put(msg)
    24. class Worker:
    25. def __init__(self, role: str, router: Router,
    26. handler: Callable[[dict], Awaitable[dict]],
    27. timeout: float = 60.0):
    28. self.role = role
    29. self.router = router
    30. self.handler = handler
    31. self.timeout = timeout
    32. self.done_ids: set[str] = set() # In production, store in Redis or a database with an expiration time
    33. async def run(self) -> None:
    34. queue = self.router.queues[self.role]
    35. while True:
    36. msg = await queue.get()
    37. try:
    38. if msg.task_id in self.done_ids: # Idempotent deduplication
    39. continue
    40. result = await asyncio.wait_for(self.handler(msg.payload), self.timeout)
    41. self.done_ids.add(msg.task_id)
    42. await self.router.publish(Message(
    43. role="coordinator",
    44. payload={"source": self.role, "task_id": msg.task_id, "result": result},
    45. ))
    46. except Exception:
    47. await self.router.requeue_or_dead_letter(msg)
    48. finally:
    49. queue.task_done()

    A few notes on the example:

    • Each Worker only reads its own role’s queue and never pulls messages intended for other roles.
    • Timeouts are controlled by wait_for. Timed-out messages are requeued and retried up to max_attempts times.
    • done_ids handles deduplication. In the example it is kept in memory and lost on process restart. Production systems should use persistent storage with an expiration time.
    • The Router itself has no persistence. If the process crashes, queued messages are lost. Scenarios requiring guaranteed delivery should use message middleware with persistence and acknowledgment mechanisms.

    Routing for 300 agents usually does not depend on the total agent count. The number of roles is far smaller than the number of agent instances, and multiple instances of the same role can simply share one queue. The real scheduling bottleneck is typically the model API’s rate limits, not the queue itself. The scheduler should therefore set concurrency caps per role to prevent all tasks from hitting the same model endpoint simultaneously.

    3. Engineering Governance Under High Concurrency

    Public reports indicate that some models experienced service overload after launch. These incidents show that traffic exceeding system capacity is a common failure mode. From an engineering perspective, the application layer needs the following mechanisms.

    • Rate limiting: set token buckets per user, tenant, and model endpoint. Long-running tasks have high per-call costs, so rate limiting should count tokens, not just requests.
    • Degradation: during peak hours, defer non-critical tasks to off-peak times or switch to smaller models. Degradation strategies should be written in advance and rehearsed regularly.
    • Circuit breaking: when a model endpoint’s error rate exceeds a threshold continuously (e.g., above 50% for 30 seconds), pause calls and fail fast to prevent tasks from piling up in queues.
    • Load testing: test with realistic task distributions rather than repeatedly calling a single request. Long-task testing should cover step counts, tool-call volumes, and failure-retry scenarios.
    • Capacity estimation: peak calls per second ≈ concurrent running tasks ÷ average duration per call (seconds). Compare the estimate against your quota and reserve roughly 30% headroom.

    Choosing message middleware depends on message volume, persistence requirements, and your team’s operational capabilities—there is no universally optimal option. A comparison of common choices:

    Option Pros Caveats Best fit
    RabbitMQ Flexible routing; mature ack and dead-letter mechanisms High-throughput persistence requires tuning Task dispatch, role-based routing
    Kafka High throughput; messages replayable Routing and latency control are more complex Event streams, audit replay
    Redis Streams Simple to deploy; low latency Persistence strength depends on configuration Small-to-medium scale, existing Redis
    Managed cloud queues No ops burden; good elasticity Vendor lock-in; higher cross-region latency Teams with limited ops resources

    When deploying Workers on Kubernetes, you can autoscale based on queue depth; KEDA is a commonly used tool. Scaling takes time to become effective, so scaling thresholds should leave headroom to avoid frequent scale up/down cycles triggered by the first signs of backlog.

    For troubleshooting, monitor at least the following metrics:

    • Queue depth and the wait time of the oldest message.
    • Failure rate, timeout rate, and retry counts per role.
    • Dead-letter queue size and growth rate.
    • Per-task end-to-end latency, model call counts, and token consumption.

    When problems arise, follow these steps:

    1. Check the dead-letter queue first and group errors by type.
    2. Use the task ID to trace all of that task’s messages and state changes.
    3. Check whether recent changes were made to prompts, model versions, or tool APIs.
    4. Reproduce the problem with the same input to distinguish model output issues from tool-call failures.
    5. For stuck tasks, check for circular calls or mutual waiting (i.e., deadlock).

    4. Cost Structure: Developers Need to Do the Math Themselves

    Public information shows that some vendors pursue a strategy of open-weight releases alongside enterprise services, and have adjusted API pricing. Open weights lower the barrier to trial, while enterprise private deployments are typically priced by scale and service level. The specific reasons for price changes should be taken from the vendors’ official announcements. This article only discusses cost structure and makes no judgment about vendors’ pricing motives.

    The costs of long-running tasks and multi-agent systems come mainly from three sources:

    • Every step re-reads the context, so input tokens accumulate quickly for long tasks.
    • Multiple agents running in parallel multiply the number of model calls.
    • Failed retries are billed repeatedly. Idempotency design and checkpoints are therefore both reliability measures and cost-control measures.

    The cost of a single task can be estimated roughly as:

    Task cost ≈ Σ (input tokens per call × input price + output tokens per call × output price) + tool and storage fees

    Main cost items and control methods:

    Cost item Source Control method
    Input tokens Re-reading context each round Context compression; improve cache hit rate
    Output tokens Plans, reasoning, and code Limit output length; use structured output
    Retried calls Timeouts, failures, dead letters Idempotent deduplication; set max retry count
    Tool calls External APIs, search, etc. Cache results; avoid duplicate queries
    Storage and queues State, checkpoints, and logs Set retention periods; archive cold data

    Unit prices vary by vendor and plan. The table describes cost structure; for actual figures, refer to the current price list.

    For teams preparing to deploy, three things come first: first, externalize task state and add version numbers to it; second, route messages by role, and equip every message with timeout, retry, and dead-letter handling; third, run a load test with a realistic task distribution and record the call counts and token consumption per task. Only after these three are done should you consider increasing the number of agents.