Rana Maninder Singh
Lesson 8 of 12AI Agents & Automation

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

PrerequisiteWhy it matters
AGENT7Understands approval workflows, escalation, and audit trails

Lesson roadmap

By the end of this lesson you will be able to:

  1. Distinguish between coordinator agents and specialist agents.
  2. Design handoff protocols between agents.
  3. Implement communication patterns (direct, broadcast, shared memory).
  4. Resolve agent conflicts and prevent deadlocks.
  5. 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:

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:

Examples: "Pricing Specialist" (calculates prices with discounts), "Credit Check Specialist" (evaluates customer creditworthiness), "Contract Specialist" (generates contracts from templates).


Why separate them?

BenefitExplanation
Separation of concernsEach agent is simpler, more testable, easier to govern
ReusabilitySpecialists can be reused across multiple coordinators
Team ownershipDifferent teams can own different specialists
Risk isolationA bug in Pricing Specialist doesn't break Credit Check
ScalabilitySpecialists 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

PatternDescriptionUse case
Synchronous (request-response)Coordinator waits for specialist to completeSimple, fast tasks where coordinator needs result to proceed
Asynchronous (fire-and-forget)Coordinator sends task, continues other work, polls for resultLong-running tasks; coordinator can parallelize
CallbackSpecialist calls back when doneWhen coordinator can't poll (e.g., human-in-the-loop in between)
StreamingSpecialist streams partial resultsReal-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 quote and updates status to credit_check_pending.

Credit Check Specialist polls, sees status = credit_check_pending, runs check, writes credit_check, updates status to contract_pending.

Contract Specialist polls, sees status = contract_pending, generates contract, writes contract, updates status to approval_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

ConflictDescriptionExample
Resource conflictTwo agents try to modify the same resourcePricing Specialist and Contract Specialist both try to update the quote total
State conflictAgents have different views of the same stateCoordinator thinks case is "credit_check_pending"; Credit Check Specialist already completed but hasn't updated shared state
Goal conflictAgents pursue contradictory sub-goalsSales Agent wants max discount; Finance Agent wants min discount
DeadlockAgent A waits for Agent B, Agent B waits for Agent ACoordinator waits for Specialist A; Specialist A waits for Coordinator to provide input

Prevention strategies

StrategyHow it works
Single writer per resourceOnly one agent owns write access to each resource. Others read-only.
Optimistic lockingEvery write includes a version number. Write fails if version changed.
Explicit state machineCase state transitions are defined and enforced. No agent can skip states.
Timeouts on all waitsNo agent waits forever. Every wait has a max duration and a fallback.
Circuit breakerIf a specialist fails repeatedly, coordinator stops calling it and escalates.
Idempotent operationsRetrying 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-domainsOne team owns the entire process
Sub-tasks have very different tool sets, knowledge bases, or expertiseThe 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 done or 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 recalculate handoff. Use a version number so a stale write fails. Log actor, old value, new value. Do not let Sales and Finance both UPDATE the 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 identityResponsibilityMay writeMust not
Quote coordinatorCase state, order of steps, stop/escalatecase.status, handoff recordsPrices, certificate IDs, truck bookings
Pricing specialistLot price from the approved price listquote.priceCertificates, trucks
Quality specialistMatch lot to a valid phytosanitary / quality certquote.cert_idPrices, trucks
Haulage specialistInland truck request to the existing TMSquote.haulage_refPrices, certs

Handoff matrix (happy path)

FromToTaskSync/asyncSuccess outputTimeout
CoordinatorPricingPrice lot L-441Syncprice_inr, list version30s
CoordinatorQualityCert for L-441Synccert_id or missing30s
CoordinatorHaulageTruck after price+certAsynchaulage_ref15 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

  1. List workers and handoff_ids for the case — count Pricing instances.
  2. Diff quote.discount_pct history (who wrote, versions).
  3. Draw the wait graph: Pricing → Credit → Pricing.
  4. Check stop rules: max_iterations, terminal statuses — missing.
  5. Confirm whether timeout handler spawned instead of escalated.

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

SpecialistInputOutputSlow?
CAMGerber checklist, layer countfeasible / not_feasible + notesSync, ~1 minute
PlanningFeasible jobs onlypromise_dateAsync, up to 2 hours
LegalCustomer namenda_ok / nda_missingSync, ~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

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

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

  1. Feasible + nda_ok + Planning success → one date, one PDF.
  2. CAM not feasible → Planning never called; blocked.
  3. Planning timeout → one retry then escalate; worker count = 1.
  4. 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

Constraints

Required controls

Measurable acceptance criteria

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


Common mistakes

MistakeSymptomCauseConsequenceCorrectionPreventive control
Two writers on one fieldDiscount or date flips“Whoever finishes updates it”Conflicting customer documentsSingle writer + versionMatrix review before release
Circular handoffAgents idle then retry stormsEach waits for the other’s outputDeadlock or duplicate workersReorder: produce A then BDraw wait graph in design
Timeout spawns a twinMany workers, one caseRetry = new instance without idempotencyDuplicate bookings or quotesRetry same key or escalateWorker-count alert per case_id
No terminal stateStatus in_progress next dayCoordinator only knows “start next”Cost, confusion, double PDFForced escalated/blockedMax steps and time cap
Specialist knows the whole processTight coupling, surprise callsCopy of coordinator logic in each agentHidden extra handoffsNarrow interface onlyInterface review
Identity is a nicknameAudit says “assistant”No stable agent_idCannot assign blame or privilegeStable id per specialistAuthZ 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_id or promise_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

ControlThis lesson (multi-agent)
Accountable human ownerOperations Head (or named process owner) for the matrix and kill switch
Approved usersCoordinator and specialists as named identities; humans who may accept exceptions
Approved data sourcesPrice list, cert register, warehouse and billing systems already authorized for that plant
Least-privilege permissionsEach specialist writes only its columns; coordinator writes status and handoffs only
Prohibited actionsCross-writing another specialist’s fields; spawning unbounded workers; leaving cases non-terminal
Validation methodSingle-writer tests, wait-graph review, timeout-to-escalate test, worker-count cap
Approval gateMatrix and writer list signed before production; exception to skip a specialist needs a human
Escalation pathSpecialist timeout or conflict → named supervisor; deadlock → stop and human
Audit evidenceagent_id, handoff_id, case_id, writes, versions, terminal status, retry count
Fallback behaviourOn specialist failure, escalate or degrade as designed — do not silently start a second writer
Stop conditionMax 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.