> ## Documentation Index
> Fetch the complete documentation index at: https://docs.agents-squads.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Agent Parallelization

> Run multiple agents concurrently for faster execution

## Why Parallelize?

Sequential execution wastes time when tasks are independent:

| Approach   | Execution                                  | Time    |
| ---------- | ------------------------------------------ | ------- |
| Sequential | Task1 → Task2 → Task3 → Task4              | 4 hours |
| Parallel   | Task1 + Task2 + Task3 + Task4 (concurrent) | 1 hour  |

## When to Parallelize

### Good Candidates

<Check>
  * Independent research tasks
  * Multiple file analyses
  * Different codebase sections
  * Separate feature implementations
  * Parallel test suites
</Check>

### Poor Candidates

<Warning>
  * Tasks with dependencies
  * Shared resource modifications
  * Sequential workflows
  * Tasks requiring prior results
</Warning>

## Parallelization Patterns

### 1. Git Worktrees (Recommended)

Use separate worktrees to avoid branch conflicts:

```bash theme={null}
# Create isolated worktree per agent
git worktree add ../.worktrees/issue-1 -b solve/issue-1 origin/main
git worktree add ../.worktrees/issue-2 -b solve/issue-2 origin/main

# Agents work in parallel
cd ../.worktrees/issue-1 && claude "Fix issue 1"
cd ../.worktrees/issue-2 && claude "Fix issue 2"

# Cleanup after PRs created
git worktree remove ../.worktrees/issue-1 --force
git worktree remove ../.worktrees/issue-2 --force
```

### 2. Task Tool Parallelization

Spawn multiple agents in a single message:

```javascript theme={null}
// Bad: Sequential
await Task({ prompt: "Research A" });
await Task({ prompt: "Research B" });

// Good: Parallel (multiple tool calls in one message)
Task({ prompt: "Research A" })
Task({ prompt: "Research B" })
```

### 3. Domain Separation

Assign agents to non-overlapping domains:

<Frame caption="Domain Separation Pattern">
  **Orchestrator** delegates to:

  <CardGroup cols={3}>
    <Card title="Auth Agent" icon="lock">
      `src/auth/`
    </Card>

    <Card title="API Agent" icon="server">
      `src/api/`
    </Card>

    <Card title="UI Agent" icon="desktop">
      `src/ui/`
    </Card>
  </CardGroup>
</Frame>

### 4. Map-Reduce

Parallel processing with aggregation:

<Steps>
  <Step title="Input">
    Files: \[file1, file2, file3, file4]
  </Step>

  <Step title="Map (parallel)">
    Haiku processes \[f1, f2] | Haiku processes \[f3, f4]
  </Step>

  <Step title="Reduce">
    Sonnet synthesizes all results into final output
  </Step>
</Steps>

## Implementation

### Worktree Script

```bash theme={null}
#!/bin/bash
# parallel-solve.sh

issues=("$@")
pids=()

for issue in "${issues[@]}"; do
  (
    worktree="../.worktrees/issue-${issue}"
    git worktree add "$worktree" -b "solve/issue-${issue}" origin/main
    cd "$worktree"
    claude --print "Solve issue #${issue}"
    gh pr create --title "Fix #${issue}" --body "Automated fix"
    cd -
    git worktree remove "$worktree" --force
  ) &
  pids+=($!)
done

# Wait for all
for pid in "${pids[@]}"; do
  wait $pid
done
```

### Squad Parallel Execution

```yaml theme={null}
# SQUAD.md
## Parallel Agents

### researcher-1
Investigates competitor A

### researcher-2
Investigates competitor B

### researcher-3
Investigates competitor C

## Orchestration
Run all researchers in parallel, then synthesize results.
```

### Claude Code Parallel Tasks

```javascript theme={null}
// Launch multiple agents concurrently
const results = await Promise.all([
  Task({ prompt: "Analyze frontend performance" }),
  Task({ prompt: "Analyze backend performance" }),
  Task({ prompt: "Analyze database queries" })
]);

// Synthesize results
const synthesis = await Task({
  prompt: `Synthesize these findings: ${JSON.stringify(results)}`
});
```

## Coordination Strategies

### Shared Context File

```markdown theme={null}
# .agents/parallel-context.md

## Task Status
- [ ] Auth module - Agent 1
- [ ] API module - Agent 2
- [x] UI module - Agent 3 (complete)

## Findings
### UI Module (Agent 3)
- Found 3 accessibility issues
- Performance bottleneck in table component
```

### Lock Files for Shared Resources

```bash theme={null}
# Before modifying shared file
while [ -f .lock ]; do sleep 1; done
touch .lock

# Do work...

# Release lock
rm .lock
```

### Dependency Declaration

```yaml theme={null}
# task-manifest.yaml
tasks:
  - id: setup-db
    parallel: false

  - id: backend
    depends_on: [setup-db]
    parallel: true

  - id: frontend
    depends_on: [setup-db]
    parallel: true

  - id: integration-tests
    depends_on: [backend, frontend]
    parallel: false
```

## Resource Management

### Limit Concurrent Agents

```bash theme={null}
# Max 3 parallel agents
MAX_PARALLEL=3

for task in "${tasks[@]}"; do
  while [ $(jobs -r | wc -l) -ge $MAX_PARALLEL ]; do
    sleep 1
  done
  run_agent "$task" &
done

wait
```

### Token Budget Distribution

```javascript theme={null}
const TOTAL_BUDGET = 100000;  // tokens
const agents = 4;
const perAgentBudget = TOTAL_BUDGET / agents;

agents.forEach(agent => {
  agent.maxTokens = perAgentBudget;
});
```

## Monitoring Parallel Execution

### Status Dashboard

```bash theme={null}
# Watch worktree status
watch -n 5 'for w in ../.worktrees/*; do
  echo "=== $(basename $w) ==="
  git -C $w status --short
done'
```

### Aggregate Logs

```bash theme={null}
# Tail all agent logs
tail -f ../.worktrees/*/agent.log
```

## Best Practices

<Check>
  * Use git worktrees for code-modifying agents
  * Limit parallelism to available resources
  * Declare dependencies explicitly
  * Monitor all parallel processes
  * Use locks for shared resources
  * Aggregate results after completion
</Check>

<Warning>
  **Common issues:**

  * Branch conflicts (solve with worktrees)
  * Resource contention (use locks)
  * Orphaned processes (track PIDs)
  * Memory exhaustion (limit concurrency)
  * Inconsistent state (use transactions)
</Warning>

## Related

<CardGroup cols={2}>
  <Card title="Multi-LLM Usage" icon="layer-group" href="/guides/multi-llm">
    Assign different models to parallel tasks
  </Card>

  <Card title="Token Economics" icon="coins" href="/guides/token-economics">
    Budget tokens across parallel agents
  </Card>
</CardGroup>
