architecture
Agent Swarms: Architecture Breakdown
How multi-agent swarms coordinate work in Claude Code. Roles, handoffs, locks, and the tracking layer that keeps a 6-mode pipeline coherent.
One prompt. N agents. Done in parallel.
Stop running tasks one by one. Spawn a swarm of agents, each tackling a piece of the problem simultaneously. Orchestrate, fan out, collect results. This is how you scale intelligence without scaling effort.
The Problem They Solve
Single-agent Claude Code is sequential by default: one task finishes before the next begins. That's fine for a 3-step pipeline, but catastrophic when you have 50 files to migrate, 12 client reports to write, or 8 competitors to research. The wall-clock time scales linearly with the number of tasks.
Agent swarms break that constraint. An orchestrator fans work out to N independent worker agents that run in parallel. Token cost stays the same (you pay per task either way), but wall-clock time collapses from items × duration to max(duration).
- →Reports to 1 parent agent
- →Isolated context per task
- →Sequential or parallel execution
- →Parent controls scope and prompt
- →Best for: discrete, bounded tasks
- →N workers spawned simultaneously
- →Orchestrator coordinates all
- →Fan-out pattern with result collection
- →Workers are independent, no peer comms
- →Best for: parallel bulk work
- →Full sessions per agent
- →Peer-to-peer communication
- →Shared or partitioned context
- →Experimental, harder to control
- →Best for: complex multi-step projects
The 6 Swarm Patterns
Click each pattern to expand. Every pattern includes a description, flow, example, and runnable bash code.
The /batch Skill
A custom Claude Code skill for swarm orchestration. One command decomposes, plans, spawns, and manages parallel agents for you. No bash scripting required. (This is an AY-authored skill, not a native Claude Code built-in.)
# What /batch does under the hood:
# 1. Scan and decompose
files=$(find src/ -name "*.tsx" -exec grep -l "extends React.Component" {} \;)
# 2. Present plan (you approve)
# "Found 20 class components. Migrate each to functional + hooks."
# [approve / modify / cancel]
# 3. Spawn agents in isolated worktrees
for f in $files; do
# Each agent gets its own git worktree
git worktree add "/tmp/batch-$(basename $f)" -b "batch/migrate-$(basename $f)"
claude --worktree "/tmp/batch-$(basename $f)" \
"Convert $f from class component to functional.
Replace lifecycle methods with hooks.
Run tests. Open PR when done." &
done
wait
# Result: 20 PRs ready for reviewHandoff Patterns & Locks
A multi-agent pipeline needs a coordination layer; otherwise agents stomp on each other's work. In Claude Code's 6-mode pipeline (PLAN → BUILD → REVIEW → QA → SHIP → RETRO), each mode hands off to the next via a shared tracking file and an exclusive lock.
A machine-readable file at the repo root that records the current pipeline mode, the active task ID, and the agent that holds the lock. Every mode transition writes an entry. If an agent crashes, the next agent reads the last entry and knows exactly where to resume.
Before writing to a shared output (HANDOFFS.md, a results file), an agent acquires an exclusive lock via flock -x .agent.lock. Only one agent can hold the lock at a time. After writing, the lock is released. This prevents race conditions in fan-out patterns.
Concrete Example: 12 Client Reports in 2 Minutes
You manage 12 active clients. Every Friday you need a status report per client: blockers, wins, next actions, and a health score. Sequentially that's 12 × ~2 min = 24 minutes of waiting. With a fan-out swarm it takes 2 minutes regardless of how many clients you have.
#!/bin/bash
# Weekly client reports - fan-out swarm
clients=$(ls 01_Projects/Clients/Active/)
count=0
for client in $clients; do
claude -p "Read all files in 01_Projects/Clients/Active/$client/.
Generate a Friday status report:
- Health score (1-10)
- Top 3 blockers
- Wins this week
- Next 3 actions
Return as JSON: {client, health, blockers:[], wins:[], actions:[]}" > "reports/${client}.json" &
count=$((count + 1))
done
wait # all 12 agents finish in parallel
echo "Generated $count client reports"
# Reduce: executive summary
claude "Read all reports/*.json.
Create an executive summary:
- Flag any client with health < 7
- List all blockers that need my attention
- Suggest my top 3 priorities for next week
Save to WEEKLY-SUMMARY.md"Real Use Cases
Patterns deployed in production. Real numbers, real workflows.
200 JavaScript files converted to TypeScript with full type annotations. One agent per file, all running in parallel. Types inferred from usage patterns, imports rewritten, tests updated.
One agent per competitor. Each researches pricing, features, positioning, reviews, tech stack. All results merged into a single comparison matrix with scoring and recommendations.
Marketing copy translated into 10 languages simultaneously. Each agent is prompted with language-specific cultural context and terminology. Native-quality output, not machine translation.
One agent per client reads their project folder, communication log, and progress file. Generates a formatted weekly report with blockers, wins, and next actions. 12 reports at once.
Common Pitfalls
Agents that write to the same file simultaneously will clobber each other. Either give each agent its own output path and merge in a reduce step, or serialise writes with a lock file.
Spawning 200 agents at once will hit API rate limits and exhaust memory. Always add a MAX_PARALLEL guard and wait every N jobs.
Writer + Critic loops can run forever if the critic keeps finding issues. Set MAX_ITERATIONS and break on APPROVED. Without this, your swarm becomes an infinite bill.
If your tasks are inherently sequential, each depending on the previous, fan-out adds zero speed. Use the Pipeline pattern instead.
Raw agent outputs (20 JSON files) are not useful on their own. Always include a reduce agent that merges, scores, and surfaces the insight from all parallel work.
When NOT to Use a Swarm
Swarms add orchestration overhead and complexity. They are the right tool only when tasks are genuinely parallelisable and numerous enough to justify the setup. Skip swarms when:
- ×Tasks that depend on each other's output (use Pipeline instead)
- ×Fewer than 3 items; sequential is simpler and easier to debug
- ×Tasks that require real-time peer communication between agents
- ×When you need deterministic, reproducible output on every run
- ×Tightly rate-limited APIs where parallel calls will be throttled anyway
Want to build production agent swarms for your team? See our AI agent development service or read the best multi-agent frameworks guide for a wider comparison. For how hooks coordinate agent handoffs, see Advanced Hooks.
Fan-Out: same prompt, different inputs, parallel. Best for bulk generation.
MapReduce: map agent per item, reduce into a single report. Best for analysis at scale.
Pipeline: specialist agents in sequence, output feeds next. Best for multi-stage workflows.
Competing Hypotheses: multiple agents, different assumptions, best evidence wins. Best for hard debugging.
Writer + Critic: iterative improvement loop with a fresh-eyes reviewer. Best for quality-sensitive output.
Bash Loop Swarm: brute force fan-out via & and wait. Best for mass file operations.
Want this running in your stack?
AY Automate builds agent systems, RAG pipelines, and Claude Code setups for production teams.