Multi-Agent Systems
Lesson opener
In one line: Complex business problems often require multiple specialized agents working together — a coordinator orchestrates, specialists execute, and handoffs pass context cleanly.
Why it matters: A single agent trying to do everything becomes bloated, fragile, and hard to govern. Multi-agent systems divide work by expertise, but they introduce new challenges: coordination, communication, conflict resolution, and shared state. This lesson teaches you how to design multi-agent systems that work reliably in business contexts.
Before this lesson: Workflow orchestration and human approval.
Prerequisites
| Prerequisite | Why it matters |
|---|---|
| AGENT7 | Understands approval workflows, escalation, and audit trails |
Lesson roadmap
By the end of this lesson you will be able to:
- Distinguish between coordinator agents and specialist agents.
- Design handoff protocols between agents.
- Implement communication patterns (direct, broadcast, shared memory).
- Resolve agent conflicts and prevent deadlocks.
- Evaluate when a multi-agent system is needed vs. a single agent with tools.
Coordinator vs. specialist agents
Coordinator agent
Role: Owns the overall goal. Plans the high-level workflow. Decides which specialist to invoke. Aggregates results. Handles exceptions.
Responsibilities:
- Understands the end-to-end business process
- Maintains the master case state
- Routes tasks to specialists
- Handles timeouts, failures, and escalations
- Presents final outcome to the user
Example: A "Quote-to-Cash Coordinator" that manages the entire process from quote generation to payment collection.
Specialist agent
Role: Executes a specific sub-task with deep expertise. Has its own tools, knowledge, and control loop.
Responsibilities:
- Owns a narrow domain (e.g., pricing, credit check, contract generation)
- Exposes a clear interface (inputs, outputs, success/failure)
- Does not know about the overall process — only its task
- Reports results back to the coordinator
Examples: "Pricing Specialist" (calculates prices with discounts), "Credit Check Specialist" (evaluates customer creditworthiness), "Contract Specialist" (generates contracts from templates).
Why separate them?
| Benefit | Explanation |
|---|---|
| Separation of concerns | Each agent is simpler, more testable, easier to govern |
| Reusability | Specialists can be reused across multiple coordinators |
| Team ownership | Different teams can own different specialists |
| Risk isolation | A bug in Pricing Specialist doesn't break Credit Check |
| Scalability | Specialists can be scaled independently (more pricing requests vs. credit checks) |
Why it matters: Don't create multiple agents just for the sake of it. Only split when the complexity, reuse, or governance benefits outweigh the coordination overhead.
Handoff protocols
What is a handoff?
A handoff is the transfer of a task (with context) from one agent to another. The sending agent packages the task; the receiving agent executes it and returns a result.
Handoff payload structure
{
"handoff_id": "hf_abc123",
"from_agent": "quote_to_cash_coordinator",
"to_agent": "pricing_specialist",
"task": "calculate_quote",
"priority": "normal",
"context": {
"case_id": "QTC-2024-0892",
"customer_id": "C00123",
"items": [
{"sku": "SRV-PREM", "qty": 12, "list_price": 499},
{"sku": "SRV-BASIC", "qty": 50, "list_price": 199}
],
"discount_tier": "Gold",
"validity_days": 30
},
"expected_output": {
"quote_id": "string",
"line_items": "array",
"subtotal": "number",
"discount": "number",
"total": "number",
"valid_until": "date"
},
"timeout_seconds": 30,
"retry_policy": {"max_attempts": 2, "backoff_seconds": 5}
}Handoff patterns
| Pattern | Description | Use case |
|---|---|---|
| Synchronous (request-response) | Coordinator waits for specialist to complete | Simple, fast tasks where coordinator needs result to proceed |
| Asynchronous (fire-and-forget) | Coordinator sends task, continues other work, polls for result | Long-running tasks; coordinator can parallelize |
| Callback | Specialist calls back when done | When coordinator can't poll (e.g., human-in-the-loop in between) |
| Streaming | Specialist streams partial results | Real-time progress updates for UI |
Business example — Quote-to-Cash handoffs:
Coordinator: "Quote-to-Cash Coordinator" manages case QTC-2024-0892.
Step 1: Coordinator → Pricing Specialist (sync): "Calculate quote for these items with Gold discount."
→ Returns: quote with line items, subtotal, discount, total.
Step 2: Coordinator → Credit Check Specialist (async): "Check credit for customer C00123, amount $45,000."
→ Returns (later): { approved: true, credit_limit: 100000, recommended_terms: "Net 30" }
Step 3: Coordinator → Contract Specialist (sync): "Generate contract from quote Q-4455, terms Net 30."
→ Returns: contract PDF, contract_id.
Step 4: Coordinator → Approval Specialist (async + human): "Route contract for e-signature."
→ Returns (later): { signed: true, signed_by: "Customer VP", timestamp: "..." }
Step 5: Coordinator → Fulfillment Specialist (sync): "Create fulfillment order for signed contract CT-7788."
→ Returns: order_id, expected_ship_date.
Communication patterns
1. Direct agent-to-agent (point-to-point)
How it works: Agent A calls Agent B directly via a defined interface.
Pros: Simple, low latency, clear ownership.
Cons: Tight coupling. Agent A must know Agent B's interface.
Best for: Synchronous handoffs where the coordinator owns the flow.
2. Shared memory / blackboard
How it works: Agents read/write to a shared state store (database, Redis, message queue). No direct calls.
Pros: Loose coupling. Agents can be added/removed without changing others. Natural for human-in-the-loop.
Cons: Higher latency. Need conflict resolution for concurrent writes. Harder to trace.
Best for: Asynchronous workflows, human-in-the-loop, long-running processes.
3. Message bus / event-driven
How it works: Agents publish events to a message bus (Kafka, RabbitMQ, Azure Service Bus). Other agents subscribe.
Pros: Highly decoupled. Scalable. Natural for audit trails.
Cons: Operational complexity. Eventual consistency. Harder to debug.
Best for: High-volume, multi-team systems where agents are independently deployed.
Business example — Shared memory for Quote-to-Cash:
Shared state (Redis key:
qtc_case:QTC-2024-0892):```json
{
"case_id": "QTC-2024-0892",
"status": "credit_check_pending",
"quote": { "quote_id": "Q-4455", "total": 45000, ... },
"credit_check": null,
"contract": null,
"approval": null,
"fulfillment": null,
"updated_by": "pricing_specialist",
"updated_at": "2024-10-15T10:30:00Z"
}
```
Pricing Specialist writes
quoteand updatesstatustocredit_check_pending.Credit Check Specialist polls, sees
status = credit_check_pending, runs check, writescredit_check, updatesstatustocontract_pending.Contract Specialist polls, sees
status = contract_pending, generates contract, writescontract, updatesstatustoapproval_pending.Why this works: No agent calls another directly. Each owns its step. The coordinator just initializes the case and monitors the shared state.
Agent conflicts and deadlocks
Conflict types
| Conflict | Description | Example |
|---|---|---|
| Resource conflict | Two agents try to modify the same resource | Pricing Specialist and Contract Specialist both try to update the quote total |
| State conflict | Agents have different views of the same state | Coordinator thinks case is "credit_check_pending"; Credit Check Specialist already completed but hasn't updated shared state |
| Goal conflict | Agents pursue contradictory sub-goals | Sales Agent wants max discount; Finance Agent wants min discount |
| Deadlock | Agent A waits for Agent B, Agent B waits for Agent A | Coordinator waits for Specialist A; Specialist A waits for Coordinator to provide input |
Prevention strategies
| Strategy | How it works |
|---|---|
| Single writer per resource | Only one agent owns write access to each resource. Others read-only. |
| Optimistic locking | Every write includes a version number. Write fails if version changed. |
| Explicit state machine | Case state transitions are defined and enforced. No agent can skip states. |
| Timeouts on all waits | No agent waits forever. Every wait has a max duration and a fallback. |
| Circuit breaker | If a specialist fails repeatedly, coordinator stops calling it and escalates. |
| Idempotent operations | Retrying an operation doesn't change the outcome (e.g., "create quote if not exists"). |
Business example — Deadlock prevention:
Scenario: Coordinator sends task to Pricing Specialist. Pricing Specialist needs a discount approval from Finance Specialist. But Finance Specialist needs the final quote from Pricing Specialist to evaluate the discount. Deadlock!
Fix: Redesign the flow. Pricing Specialist calculates quote WITHOUT discount (base price). Coordinator sends base quote to Finance Specialist for discount approval. Finance Specialist returns approved discount %. Coordinator sends discount % back to Pricing Specialist for final quote. No circular dependency.
When to use multi-agent vs. single agent with tools
| Use multi-agent when: | Use single agent with tools when: |
|---|---|
| The process has distinct, reusable sub-domains (pricing, credit, legal) | The process is a single coherent workflow |
| Different teams own different sub-domains | One team owns the entire process |
| Sub-tasks have very different tool sets, knowledge bases, or expertise | The agent's tools are all in the same domain |
| You need independent scaling (pricing volume ≠ credit volume) | Volume is uniform across steps |
| Governance requires isolation (finance logic separate from sales logic) | Governance can be handled at the tool level |
Why it matters: Multi-agent systems add significant complexity (coordination, communication, debugging, deployment). Only use them when the benefits clearly outweigh the costs.
Pause-and-think questions
These questions stay in the lesson. Answers sit under each one so you can check yourself without a hidden accordion.
1. Design a multi-agent system for employee onboarding. Name the coordinator, at least three specialists, one sync handoff, and one async handoff.
Coordinator owns the join date and case status. IT Provisioning (sync): account and laptop request must exist before day-one access is promised. HR Systems (async): HRIS and payroll can finish while IT continues. Compliance (sync after HR identity exists): policy ack and training assignment. Flow: start → IT sync → HR async in parallel with later Compliance sync → coordinator closes only when required specialists report
doneor a human accepts a documented exception. Each specialist has a timeout and a single writer for its records.
2. Two specialists both want to update “customer risk score.” How do you prevent conflict?
One writer: only the Risk Scoring specialist writes the score. Others send a
recalculatehandoff. Use a version number so a stale write fails. Log actor, old value, new value. Do not let Sales and Finance bothUPDATEthe same column.
3. The coordinator’s specialist times out. What next?
Retry a small, fixed number of times with backoff. Then mark the step failed, alert the human ops queue if the step is on the critical path, or continue degraded if the design allows it. Open the circuit if the specialist fails repeatedly. Never wait forever and never start a second specialist on the same write without an idempotency key.
Worked walkthrough: Responsibility and handoff matrix at Malabar Spice Exports
Malabar Spice Exports (Kochi) quotes container lots of black pepper and cardamom. A single bloated agent used to price, check quality certificates, and book inland haulage. The team splits the work. This walkthrough builds a responsibility and handoff matrix you can test with a tiny state machine. No paid API.
Agents
| Agent identity | Responsibility | May write | Must not |
|---|---|---|---|
| Quote coordinator | Case state, order of steps, stop/escalate | case.status, handoff records | Prices, certificate IDs, truck bookings |
| Pricing specialist | Lot price from the approved price list | quote.price | Certificates, trucks |
| Quality specialist | Match lot to a valid phytosanitary / quality cert | quote.cert_id | Prices, trucks |
| Haulage specialist | Inland truck request to the existing TMS | quote.haulage_ref | Prices, certs |
Handoff matrix (happy path)
| From | To | Task | Sync/async | Success output | Timeout |
|---|---|---|---|---|---|
| Coordinator | Pricing | Price lot L-441 | Sync | price_inr, list version | 30s |
| Coordinator | Quality | Cert for L-441 | Sync | cert_id or missing | 30s |
| Coordinator | Haulage | Truck after price+cert | Async | haulage_ref | 15 min |
Coordinator does not call Haulage until Pricing and Quality both returned. That removes the circular wait “price needs truck cost / truck needs final price” unless you add an explicit extra step for estimated freight.
Reproduce conflict and termination rules
TERMINAL = {"quoted", "blocked", "escalated"}
def next_status(status, event):
transitions = {
("new", "price_ok"): "priced",
("priced", "cert_ok"): "ready_to_haul",
("priced", "cert_missing"): "blocked",
("ready_to_haul", "haulage_ok"): "quoted",
("ready_to_haul", "haulage_timeout"): "escalated",
}
return transitions.get((status, event), status)
status = "new"
status = next_status(status, "price_ok")
status = next_status(status, "cert_ok")
status = next_status(status, "haulage_ok")
assert status == "quoted"
assert status in TERMINAL
# Duplicate pricing write is refused by single-writer + version
price_doc = {"version": 1, "writer": "pricing"}
def write_price(writer, version):
if writer != "pricing" or version != price_doc["version"]:
return False
price_doc["version"] += 1
return True
assert write_price("quality", 1) is False
assert write_price("pricing", 1) is True
assert write_price("pricing", 1) is False # stale version
print("Malabar handoff and single-writer checks passed")Stop condition: after quoted, blocked, or escalated, the coordinator must not start another Pricing loop on the same case_id without a new human-approved revision.
Failure example: Navya Pharma Distribution specialists conflict and never terminate
Business context
Navya Pharma Distribution (Hyderabad) quotes hospital tenders. A coordinator calls a Pricing specialist and a Credit specialist. Pricing needs an approved credit limit to apply a tender discount. Credit wants a final net price to decide the limit. Both specialists were also given write access to quote.discount_pct “so either can finish.”
Intended outcome
Coordinator sends list price to Credit first (async). Credit returns limit_ok or limit_hold. Coordinator then sends a single price task to Pricing with the credit outcome. One writer updates discount_pct. When both required outputs exist — or a specialist fails twice — the coordinator enters a terminal state and stops.
Actual failure
Each specialist waited for the other (deadlock). After 20 seconds they both timed out, retried, and started additional instances because the coordinator used “fire another worker” on timeout. Two Pricing instances wrote discount_pct (12 percent and 18 percent). The case status stayed in_progress overnight. A hospital portal showed two different quote PDFs for the same tender id.
Observable symptom
Ops dashboard: 14 active workers on one case_id, status never done. Quote table: last-write-wins discount flips every few minutes. Tender desk sends the wrong PDF. Nobody owns stop.
Root cause
Circular dependency in the handoff design. Two writers on one field. Timeout created new work instead of escalating. No maximum loop count and no terminal states. Agent identity was only a display name, not an enforced writer role.
Business or security impact
Conflicting commercial terms go to a hospital buyer. Duplicate effort burns model and staff time. The tender may be legally awkward if two quotes exist. Finance cannot tell which discount was authorized.
Diagnostic steps
- List workers and handoff_ids for the case — count Pricing instances.
- Diff
quote.discount_pcthistory (who wrote, versions). - Draw the wait graph: Pricing → Credit → Pricing.
- Check stop rules:
max_iterations, terminal statuses — missing. - Confirm whether timeout handler
spawnedinstead ofescalated.
Correction
Break the cycle: Credit on list price first, then Pricing once. Single writer for discount_pct (Pricing only). Idempotency key case_id + task + attempt. Timeout: retry once, then escalated and no new worker. Coordinator stop: max_handoffs=6 or 10 minutes, whichever first.
Validation after correction
Replay the tender: exactly one Credit result, one Pricing write, terminal status in under the time cap. Forced double Pricing write fails the version check. Chaos test: kill Credit — case goes escalated, not infinite retry.
Preventive control
Responsibility and handoff matrix reviewed before go-live. Conflict test (two writers) and termination test (timeout) in CI. Circuit breaker on specialist error rate.
Guided practice: Responsibility and handoff matrix for Bharat Circuit Boards
Realistic scenario
Bharat Circuit Boards (Peenya, Bengaluru) takes prototype orders. A coordinator must gather: fabrication feasibility (CAM specialist), promised date (Planning specialist), and NDA status (Legal specialist). CAM and Planning both used to edit order.promise_date, which caused two dates on the same order acknowledgement.
Input information
| Specialist | Input | Output | Slow? |
|---|---|---|---|
| CAM | Gerber checklist, layer count | feasible / not_feasible + notes | Sync, ~1 minute |
| Planning | Feasible jobs only | promise_date | Async, up to 2 hours |
| Legal | Customer name | nda_ok / nda_missing | Sync, ~30 seconds |
Sales wants the acknowledgement PDF as soon as all three exist. If CAM says not feasible, Planning must not run.
Required outcome
A multi-agent responsibility and handoff matrix: identity, sole writes, sequence, sync vs async, conflict rule, termination, and human escalate.
Constraints
- Only Planning writes
promise_date. - Legal does not start CAM.
- If CAM is
not_feasible, coordinator terminates asblockedand notifies sales. - If Planning exceeds two hours, escalate to the Planning supervisor — do not start a second Planning agent on the same order.
Staged hints
Hint 1 — Sequence. Legal can run in parallel with CAM. Planning waits for feasible.
Hint 2 — Identity. Write the service name that appears in audit logs, not “the bot.”
Hint 3 — Conflict. If Sales types a date in email, that is not a write to order.promise_date unless Planning accepts a handoff.
Hint 4 — Stop. Terminal states: acknowledged, blocked, escalated. Define max CAM retries (for example 1).
Learner checkpoints
- [ ] Three specialists plus coordinator named
- [ ] Single writer per contested field
- [ ] Handoff table includes timeout and success payload
- [ ] Planning cannot run on
not_feasible - [ ] No second Planning worker on timeout
- [ ] Human escalate target named
Complete model solution
Responsibility: Coordinator owns status and PDF trigger. CAM writes feasibility only. Planning writes promise date only. Legal writes NDA flag only.
Handoffs: Coordinator → Legal (sync) and Coordinator → CAM (sync) in parallel. If nda_missing, status blocked (commercial hold) even if CAM is feasible — or you may allow CAM to finish but you still do not acknowledge. Coordinator → Planning (async) only if feasible and nda_ok. On Planning timeout: one retry, then Planning supervisor.
Conflict: Version on promise_date. CAM and Legal have no update right.
Termination: acknowledged after PDF; blocked on CAM fail or NDA missing; escalated on Planning timeout. Coordinator max_steps=8.
Why it works
Work is split by expertise, but writes and stops are exclusive. Parallel Legal + CAM saves time without letting Planning invent a date for an infeasible board.
Validation procedure
- Feasible + nda_ok + Planning success → one date, one PDF.
- CAM not feasible → Planning never called;
blocked. - Planning timeout → one retry then escalate; worker count = 1.
- CAM attempts to write
promise_date→ denied.
Governance / human-review check
Operations Head owns the matrix. Planning supervisor owns late dates. Legal owns NDA blocks. A change to who may write promise_date needs the same review as a price-write change.
Independent practice: Dispatch matrix for Godavari Rice Mills
Workplace scenario
Godavari Rice Mills (East Godavari) dispatches 20 kg bags to distributors. A coordinator currently over-calls three specialists: Inventory (bag count in the warehouse system), Transport (lorry from the existing transport desk), and Invoice (GST invoice in the billing system). Last week Inventory and Transport both created a lorry request, and Invoice kept regenerating PDFs because the coordinator never marked the case terminal.
Deliverable
A multi-agent responsibility and handoff matrix for one dispatch case, plus a half-page termination and conflict addendum.
Scope
- One plant, one distributor order, one lorry request, one invoice.
- Systems of record already exist; you are assigning which agent may write which record.
Constraints
- Single writer per record type (lorry request, invoice, stock reservation).
- Transport runs only after stock is reserved.
- Invoice runs only after lorry request exists (or after a documented exception from Dispatch Supervisor).
- Failure to terminate is out of policy: every case must reach a terminal state.
Required controls
- Agent identity in logs.
- Handoff payloads with timeout and idempotency key.
- Conflict rule for double lorry requests.
- Stop condition (max handoffs or clock).
- Escalation to Dispatch Supervisor.
Measurable acceptance criteria
- [ ] Coordinator + at least three specialists with sole writes
- [ ] Handoff matrix has sequence, sync/async, timeout
- [ ] Duplicate lorry request is impossible under your rules
- [ ] Terminal states listed and one of them is forced on timeout
- [ ] Idempotency key defined
- [ ] Supervisor escalate named
- [ ] You did not invent a new transport vendor API — you assign writes to the existing desk/system
Model approach or rubric
Full marks: identity, responsibility, handoff, conflict, termination all specific to rice dispatch. Partial: generic “use a coordinator.” Fail: two specialists may insert a lorry row.
Self-review checklist
- [ ] A new reader knows who writes stock reservation
- [ ] Invoice cannot loop forever
- [ ] Timeout does not spawn a twin specialist
- [ ] You can draw the wait graph with no cycle
- [ ] Kill switch / stop condition is testable
Common mistakes
| Mistake | Symptom | Cause | Consequence | Correction | Preventive control |
|---|---|---|---|---|---|
| Two writers on one field | Discount or date flips | “Whoever finishes updates it” | Conflicting customer documents | Single writer + version | Matrix review before release |
| Circular handoff | Agents idle then retry storms | Each waits for the other’s output | Deadlock or duplicate workers | Reorder: produce A then B | Draw wait graph in design |
| Timeout spawns a twin | Many workers, one case | Retry = new instance without idempotency | Duplicate bookings or quotes | Retry same key or escalate | Worker-count alert per case_id |
| No terminal state | Status in_progress next day | Coordinator only knows “start next” | Cost, confusion, double PDF | Forced escalated/blocked | Max steps and time cap |
| Specialist knows the whole process | Tight coupling, surprise calls | Copy of coordinator logic in each agent | Hidden extra handoffs | Narrow interface only | Interface review |
| Identity is a nickname | Audit says “assistant” | No stable agent_id | Cannot assign blame or privilege | Stable id per specialist | AuthZ on write by agent_id |
Quick checks
1. Explain. Why does a handoff payload need an expected output schema, not only a chat instruction?
The coordinator must validate success or failure. A paragraph cannot be checked for
cert_idorpromise_date, so the next step starts on guesswork.
2. Predict. Pricing and Credit each wait for the other’s result, and timeout starts a new worker. What do you observe after an hour?
A growing set of workers, conflicting writes, and a case that never terminates — the Navya pattern.
3. Diagnose. Two lorry requests for one rice order. Inventory and Transport both called “create lorry.” What was missing?
Single writer for the lorry record and a sequence that allows only Transport (or only a booking desk) to insert after stock reserve.
4. Compare approaches. Direct coordinator-to-specialist calls versus a shared case record with one writer per field. When is the shared record safer?
When steps are async, humans join mid-flow, or you must prevent two specialists from calling each other. Direct calls are fine for short sync steps if the coordinator still owns stop.
5. Validation method. How do you prove specialists terminate?
Staging: force a specialist timeout and a CAM-not-feasible path. Pass only if status is terminal, worker count is bounded, and no extra writes occur after stop.
Responsible AI controls
| Control | This lesson (multi-agent) |
|---|---|
| Accountable human owner | Operations Head (or named process owner) for the matrix and kill switch |
| Approved users | Coordinator and specialists as named identities; humans who may accept exceptions |
| Approved data sources | Price list, cert register, warehouse and billing systems already authorized for that plant |
| Least-privilege permissions | Each specialist writes only its columns; coordinator writes status and handoffs only |
| Prohibited actions | Cross-writing another specialist’s fields; spawning unbounded workers; leaving cases non-terminal |
| Validation method | Single-writer tests, wait-graph review, timeout-to-escalate test, worker-count cap |
| Approval gate | Matrix and writer list signed before production; exception to skip a specialist needs a human |
| Escalation path | Specialist timeout or conflict → named supervisor; deadlock → stop and human |
| Audit evidence | agent_id, handoff_id, case_id, writes, versions, terminal status, retry count |
| Fallback behaviour | On specialist failure, escalate or degrade as designed — do not silently start a second writer |
| Stop condition | Max handoffs / max minutes; circuit breaker; kill switch on the coordinator |
Agent identity, responsibility, handoff, conflict handling, and termination are the multi-agent controls. Without them, extra agents add risk rather than skill.
Complete the lesson quiz to test whether you can apply these decisions to a new scenario.
Key takeaways
- Coordinator agent owns the end-to-end goal and routes to specialists. Specialist agents execute narrow, deep tasks.
- Handoffs transfer tasks with structured payloads (context, expected output, timeout, retry policy). Patterns: sync, async, callback, streaming.
- Communication patterns: direct (tight coupling), shared memory (loose coupling, good for human-in-the-loop), message bus (high scale, decoupled).
- Conflicts (resource, state, goal, deadlock) prevented by: single writer, optimistic locking, explicit state machine, timeouts, circuit breakers, idempotency.
- Use multi-agent when sub-domains are distinct, reusable, independently governed, or scaled. Use single agent when the process is coherent and unified.
Bridge to next lesson
What's next: Security, Guardrails & Governance — learn how to protect agents from prompt injection, data leakage, unauthorized access, and ensure auditability.