Building a 24/7 Multi-Agent System: Architecture and Production Practices
This article explains why a single monolithic agent breaks down on long-running workflows and how a multi-agent architecture solves the problem. It covers a four-layer design, a seven-role division based on context boundaries and tool permissions, separation of messages from artifacts, four context-governance techniques for long tasks, permission boundaries for autonomous local coding, a full worked example (a competitor price-monitoring dashboard), observability and human handoff, and a list of common pitfalls. The core idea is replacing model memory with engineering constraints.
1. Problem Definition: Why a Single Agent Can’t Handle Long Workflows
Handing a one-line requirement to a model and expecting it to deliver a complete system in one shot may work in a demo, but it almost always fails in production. The reason isn’t how smart the model is; it’s three structural constraints:
- Limited context capacity. The combined output of requirements research, product design, architecture, coding, and testing far exceeds a single context window. Forcing it all in inevitably triggers compression, and early constraints get “forgotten.”
- Diluted attention. When the same context holds both business goals and error stack traces, the model tends to get stuck in local details and loses sight of the original objective.
- Non-attributable failures. When a monolithic run fails, you can’t tell whether the requirement was misunderstood, the design had a gap, or the code broke.
The core value of splitting into multiple agents isn’t “more hands make light work.” It’s trading process/session boundaries for context purity and failure attributability. Each role holds only the minimal context its responsibility requires, and roles pass structured artifacts to each other rather than chat logs.
2. Overall Architecture: A Four-Layer Structure
┌─────────────────────────────────────────┐│ Access: enterprise collab / webhook / cron │├─────────────────────────────────────────┤│ Orchestration: lead agent (task split + FSM) │├─────────────────────────────────────────┤│ Collaboration: message bus + shared store + board │├─────────────────────────────────────────┤│ Execution: specialist agents + local sandbox │└─────────────────────────────────────────┘
2.1 Role Division Principles
Roles are divided not by “job title” but by context boundaries and tool permissions. A practical split uses seven roles:
| Role | Input | Output Artifact | Tool Permissions |
|---|---|---|---|
| Lead | Raw requirement | Task tree, state transitions | Dispatch, aggregate, escalate to human |
| Market | Requirement points | Research report (structured) | Read-only retrieval |
| Product | Research report | Requirements doc, acceptance criteria | Read/write artifact store |
| Architecture | Requirements doc | Module breakdown, interface contracts | Read/write artifact store |
| Dev | Interface contracts | Code commits, change notes | Read/write code in sandbox, run builds |
| Test | Acceptance criteria | Test cases, defect tickets | Run tests in sandbox |
| Delivery | All artifacts | Delivery notes, deployment manifest | Package, release pipeline |
Key constraint: a downstream role may only consume the upstream structured artifacts and must not go back and read the upstream full conversation. This is the single most effective way to control context growth.
2.2 Separating Messages from Artifacts
A common beginner mistake is using the message bus as a database. The correct approach is that messages carry only “pointer + summary,” while the real artifacts land in a shared artifact store (backed by object storage or a versioned repository).
{"msg_id": "uuid","from": "product_agent","to": "orchestrator","type": "artifact_ready","task_id": "T-102","payload": {"artifact_uri": "store://prd/T-102/v3.md","summary": "Confirmed 6 core modules and 12 acceptance criteria","risks": ["Third-party data source has no stable API; a fallback strategy is needed"]},"trace_id": "req-20260826-001"}
The trace_id runs through the entire chain and serves as the anchor for later observability and fault localization.
3. Long-Task Stability: Four Context-Governance Techniques
To keep a chain of dozens of turns from breaking, you must manage context explicitly rather than hoping the model remembers on its own.
(1) Layered summarization. Each role maintains three tiers of memory: invariant constraints (never compressed, usually under 200 words), stage summaries (rolling-updated each time a subtask completes), and recent raw text (the last several turns). When compressing, discard recent raw text first.
def build_context(role, task_id):return "\n".join([load_invariant(task_id), # immutable constraintsload_stage_summary(role, task_id), # rolling summaryload_recent(role, task_id, k=6) # recent raw text])
(2) Checkpoints and recoverability. Persist each task’s state to storage so that after a process restart it resumes from the latest checkpoint instead of starting over. The state machine should be defined explicitly: todo → in progress → pending review → passed/rejected → archived.
(3) Task-chain continuity. Maintain a four-tuple of “goal—constraints—completed—todo” for each task and re-inject it on every dispatch. This is far more reliable than depending on conversation history.
(4) Enforced structured output. Require each role to emit a fixed schema; if parsing fails, reject and retry. This avoids free-form text that downstream roles can’t consume.
4. Execution Layer: Permission Boundaries for Autonomous Local Coding
Letting an agent autonomously invoke local AI coding tools and write code 24/7 is the source of efficiency and the biggest risk point. You must ensure:
- Sandbox isolation: a containerized execution environment with an independent filesystem and network egress, with no access to production credentials.
- Least privilege: mount dependency caches read-only; limit write access to the task working directory.
- Approval for dangerous operations: deletions, force pushes, deployments, and billing-related calls all go into a human approval queue.
- Resource quotas: per-task CPU/memory/time limits, with automatic termination and reclamation on timeout.
- Full audit: commands, exit codes, and change diffs are all written to a logging service and searchable by
trace_id.
5. Full Example: A Competitor Price-Monitoring Dashboard
Requirement input: Enter competitor links; periodically collect price, original price, discount, and stock status; provide trend charts and abnormal-fluctuation markers; send alerts via the enterprise collaboration platform on low price, sharp fluctuation, or out-of-stock; support table export.
Execution chain:
- The lead agent breaks down the task tree; the market role produces a research report (covering data-source availability, compliance boundaries, and field-design suggestions) and privately sends a progress summary to the requester.
- The product role produces the requirements doc and acceptance criteria based on the report; the lead agent runs a consistency review first and rejects it if it fails.
- The architecture role provides the module breakdown: collection scheduling, parsing adapters, storage, metric computation, alerting, and export.
- The dev role implements and self-tests the build in the sandbox; the test role generates cases from the acceptance criteria and runs them, with defects flowing back to dev.
- The delivery role aggregates the artifacts and the deployment manifest.
Core logic sketch:
def evaluate(item, history):alerts = []p = item.priceif item.stock == 0:alerts.append(("out_of_stock", item.url))if p <= item.floor_price:alerts.append(("low_price", item.url, p))if history:base = median(history[-7:])if base and abs(p - base) / base >= 0.15:alerts.append(("sharp_fluctuation", item.url, p, base))return alerts
The scheduling layer is driven by a cron trigger; collection results are persisted in a generic row-storage format and synced to object storage; the export module generates table files; alerts are peak-shaved through a message queue before being pushed to the collaboration platform group, avoiding instantaneous duplicate bombardment (deduplication by the same rule and a silence window are recommended).
6. Observability and Human Handoff
- Metrics: task success rate, average per-stage latency, number of rejections, and per-task token and compute consumption.
- Tracing: a full-chain
trace_id, so any artifact can be traced back to the original requirement. - Human handoff: the lead agent must escalate to a human in three cases—“rejected N times in a row,” “a high-risk operation is triggered,” and “requirement ambiguity”—rather than guessing on its own.
7. Common Pitfalls Checklist
- Splitting roles too finely, so communication overhead exceeds the benefit; start with 3–4 roles to get it working, then add more.
- Using chat logs as shared storage; context will inevitably blow up.
- Letting dev start without acceptance criteria; the rework rate is extremely high.
- Opening up sandbox permissions; one accidental deletion wipes out all the gains.
- Looking only at the final output and not the process metrics, making it impossible to locate which stage degraded.
8. Conclusion
The essence of a multi-agent system is replacing model memory with engineering constraints: structured artifacts, an explicit state machine, layered context, sandbox permissions, and full-chain tracing. Get these five things solid, and 24/7 unattended long-workflow delivery becomes reproducible; otherwise, no matter how strong the model, it only works once in a demo.
