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

# Many agents in parallel

> Prepare one sandbox, save it as a snapshot, and fan out: one copy per task, all running at once, each isolated, results collected at the end. For agents on many issues, sharded test suites and batch jobs.

Some work splits naturally into many independent pieces: ten issues in the backlog, a hundred files to migrate, a
test suite that takes an hour on one machine. Doing them one after another is slow. **Run them side by side
instead**, with one sandbox per task. Each sandbox has its own files and processes, so whatever one task does can
never interfere with another.

It always follows the same four steps:

1. **Prepare once.** Set up one sandbox with the repository, its dependencies and the agent.
2. **Save it as a [snapshot](https://docs.fibre.dev/setup/snapshots.md).** Every sandbox created from it starts exactly where it was.
3. **Fan out.** Create one sandbox per task from the snapshot, all at the same time.
4. **Collect the results.** Read each sandbox's result, keep what is good, and delete the rest.

## Fan out

This example runs three tasks in parallel. To keep it short and free to run, each task is a simple stand-in for
what an agent would do: it makes a small change to a file and runs a check to prove it worked. The next section
shows how to put a real agent in its place.

**1. Prepare the base and save it**

```bash title="CLI" run theme={null}
BASE=$(fibre create --lifetime 30m --label batch=docs-fanout --json | jq -r .id)
printf "def greet(name):\n    return 'Hello ' + name\n" | fibre exec "$BASE" -i -- sh -c 'mkdir -p /work/repo && cat > /work/repo/greet.py'
fibre exec "$BASE" --cwd /work/repo -- 'git init -q && git add . && git -c user.name=dev -c user.email=dev@example.com commit -qm base'
# in your project: clone, install dependencies, install the agent here: done once for every task

fibre snapshot create docs-fanout-base --from "$BASE"
```

```typescript title="TypeScript" run theme={null}
import { Sandbox, Snapshot } from "@fibre-dev/sdk";

const base = await Sandbox.create({ lifetime: 1800, labels: { batch: "docs-fanout" } });
await base.files.write("/work/repo/greet.py", "def greet(name):\n    return 'Hello ' + name\n");
await base.run("cd /work/repo && git init -q && git add . && git -c user.name=dev -c user.email=dev@example.com commit -qm base");
// in your project: clone, install dependencies, install the agent here: done once for every task

await base.snapshot({ name: "docs-fanout-base" });
```

```python title="Python" run theme={null}
from fibre import Sandbox, Snapshot

base = Sandbox.create(lifetime=1800, labels={"batch": "docs-fanout"})
base.files.write("/work/repo/greet.py", "def greet(name):\n    return 'Hello ' + name\n")
base.run("cd /work/repo && git init -q && git add . && git -c user.name=dev -c user.email=dev@example.com commit -qm base")
# in your project: clone, install dependencies, install the agent here: done once for every task

base.snapshot(name="docs-fanout-base")
```

**2. One copy per task, all at once**

```bash title="CLI" run theme={null}
for task in "task-1:s/Hello/Hi/" "task-2:s/Hello/Hey/" "task-3:s/Hello/Good morning,/"; do
  (
    id=${task%%:*} change=${task#*:}
    S=$(fibre create --snapshot docs-fanout-base --lifetime 30m --label batch=docs-fanout --label task=$id --json | jq -r .id)

    # the agent's work goes here, e.g. claude -p "$TASK" (see the coding agent use case)
    fibre exec "$S" --cwd /work/repo -- sed -i "$change" greet.py
    echo "$id $S $(fibre exec "$S" --cwd /work/repo -- python3 -c "from greet import greet; print(greet('Ada'))")"
  ) &
done
wait
# task-1 sbx-… Hi Ada · task-2 sbx-… Hey Ada · task-3 sbx-… Good morning, Ada
```

```typescript title="TypeScript" run theme={null}
const tasks = [
  { id: "task-1", change: "s/Hello/Hi/" },
  { id: "task-2", change: "s/Hello/Hey/" },
  { id: "task-3", change: "s/Hello/Good morning,/" },
];

const results = await Promise.all(tasks.map(async (task) => {
  const sbx = await Sandbox.create({
    snapshot: "docs-fanout-base",
    lifetime: 1800,
    labels: { batch: "docs-fanout", task: task.id },
  });

  // the agent's work goes here, e.g. claude -p "$TASK" (see the coding agent use case)
  await sbx.run(`cd /work/repo && sed -i "${task.change}" greet.py`);
  const check = await sbx.run(`cd /work/repo && python3 -c "from greet import greet; print(greet('Ada'))"`);
  const diff = await sbx.run("cd /work/repo && git diff --stat");

  return { task: task.id, sandbox: sbx.id, output: check.stdout.trim(), diff: diff.stdout.trim() };
}));

console.table(results);
// task-1  sbx-…  Hi Ada                1 file changed, 1 insertion(+), 1 deletion(-)
// task-2  sbx-…  Hey Ada               …
// task-3  sbx-…  Good morning, Ada     …
```

```python title="Python" run theme={null}
import asyncio

from fibre import AsyncSandbox

tasks = [
    {"id": "task-1", "change": "s/Hello/Hi/"},
    {"id": "task-2", "change": "s/Hello/Hey/"},
    {"id": "task-3", "change": "s/Hello/Good morning,/"},
]


async def work(task):
    sbx = await AsyncSandbox.create(snapshot="docs-fanout-base", lifetime=1800, labels={"batch": "docs-fanout", "task": task["id"]})

    # the agent's work goes here, e.g. claude -p "$TASK" (see the coding agent use case)
    await sbx.run(f'cd /work/repo && sed -i "{task["change"]}" greet.py')
    check = await sbx.run("cd /work/repo && python3 -c \"from greet import greet; print(greet('Ada'))\"")
    diff = await sbx.run("cd /work/repo && git diff --stat")
    return {"task": task["id"], "sandbox": sbx.id, "output": check.stdout.strip(), "diff": diff.stdout.strip()}


async def main():
    return await asyncio.gather(*(work(t) for t in tasks))


for r in asyncio.run(main()):
    print(r["task"], r["sandbox"], r["output"], r["diff"], sep="  ")
# task-1  sbx-…  Hi Ada                1 file changed, 1 insertion(+), 1 deletion(-)
# task-2  sbx-…  Hey Ada               …
# task-3  sbx-…  Good morning, Ada     …
```

Each sandbox started with the repository already in place: **none of them had to clone or install anything.**

**3. Collect, then clean up**

Keep the sandboxes whose work you want to review. They sleep while you read, and cost nothing for compute. Delete
the others. This example deletes all of them, then the snapshot, then the sandbox it was made from:

```bash title="CLI" run theme={null}
for s in $(fibre list --label batch=docs-fanout --json | jq -r --arg base "$BASE" '.[] | select(.id != $base) | .id'); do
  fibre delete "$s"
done
fibre snapshot delete docs-fanout-base
fibre delete "$BASE"
```

```typescript title="TypeScript" run theme={null}
for await (const s of Sandbox.list({ labels: { batch: "docs-fanout" } })) {
  if (s.id !== base.id) await s.delete();
}
await (await Snapshot.get("docs-fanout-base")).delete();
await base.delete();
```

```python title="Python" run theme={null}
for s in Sandbox.list(labels={"batch": "docs-fanout"}):
    if s.id != base.id:
        s.delete()
Snapshot.get("docs-fanout-base").delete()
base.delete()
```

## With a real agent

To use a real agent, replace the stand-in with the agent's command. The rest of the code stays the same. Here,
Claude Code works on three issues at once, each in its own sandbox, and commits its fix to a branch:

```bash title="CLI" norun reason="needs your Anthropic API key" theme={null}
for issue in "#101 login fails on Safari" "#102 export ignores filters" "#103 typo in onboarding email"; do
  (
    S=$(fibre create --snapshot my-repo-with-agent --label batch=issues --label issue="${issue:1:3}" --json | jq -r .id)
    fibre exec "$S" --timeout 1h --env ANTHROPIC_API_KEY="$ANTHROPIC_API_KEY" --env TASK="Fix $issue. Run the tests." \
      -- 'cd /work/repo && ~/.local/bin/claude -p "$TASK" --allowedTools "Read,Edit,Bash"'
    fibre exec "$S" --cwd /work/repo -- "git checkout -b fix/${issue:1:3} && git commit -qam 'Fix $issue'"
  ) &
done
wait
```

```typescript title="TypeScript" norun reason="needs your Anthropic API key" theme={null}
const issues = ["#101 login fails on Safari", "#102 export ignores filters", "#103 typo in onboarding email"];

await Promise.all(issues.map(async (issue) => {
  const sbx = await Sandbox.create({ snapshot: "my-repo-with-agent", labels: { batch: "issues", issue } });
  await sbx.run(
    ["sh", "-c", 'cd /work/repo && ~/.local/bin/claude -p "$TASK" --allowedTools "Read,Edit,Bash"'],
    { env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY!, TASK: `Fix ${issue}. Run the tests.` }, timeout: 3600 },
  );
  await sbx.run(`cd /work/repo && git checkout -b fix/${issue.slice(1, 4)} && git commit -qam "Fix ${issue}"`);
}));
```

```python title="Python" norun reason="needs your Anthropic API key" theme={null}
import asyncio
import os

from fibre import AsyncSandbox

issues = ["#101 login fails on Safari", "#102 export ignores filters", "#103 typo in onboarding email"]


async def fix(issue):
    sbx = await AsyncSandbox.create(snapshot="my-repo-with-agent", labels={"batch": "issues", "issue": issue})
    await sbx.run(
        ["sh", "-c", 'cd /work/repo && ~/.local/bin/claude -p "$TASK" --allowedTools "Read,Edit,Bash"'],
        env={"ANTHROPIC_API_KEY": os.environ["ANTHROPIC_API_KEY"], "TASK": f"Fix {issue}. Run the tests."},
        timeout=3600,
    )
    await sbx.run(f'cd /work/repo && git checkout -b fix/{issue[1:4]} && git commit -qam "Fix {issue}"')


async def main():
    await asyncio.gather(*(fix(i) for i in issues))


asyncio.run(main())
```

## Sharding a test suite

The same approach speeds up a slow test suite. Split the tests into parts (called *shards*), and run each part in
its own sandbox at the same time. The suite then takes about as long as its slowest part:

```bash title="CLI" norun reason="needs your own repo and test runner" theme={null}
SHARDS=8
for i in $(seq 1 $SHARDS); do
  fibre run --rm --snapshot my-repo-ready --label ci=run-4711 --cwd /work/repo -- npx vitest run --shard=$i/$SHARDS &
done
FAILED=0
for job in $(jobs -p); do wait "$job" || FAILED=1; done
exit $FAILED
```

```typescript title="TypeScript" norun reason="needs your own repo and test runner" theme={null}
const shards = 8;
const runs = await Promise.all(Array.from({ length: shards }, async (_, i) => {
  const sbx = await Sandbox.create({ snapshot: "my-repo-ready", labels: { ci: "run-4711" } });
  const r = await sbx.run(`cd /work/repo && npx vitest run --shard=${i + 1}/${shards}`, { timeout: 1800 });
  await sbx.delete();
  return r.exitCode;
}));
process.exit(runs.every((code) => code === 0) ? 0 : 1);
```

```python title="Python" norun reason="needs your own repo and test runner" theme={null}
import sys
from concurrent.futures import ThreadPoolExecutor

from fibre import Sandbox

shards = 8


def shard(i):
    with Sandbox.create(snapshot="my-repo-ready", labels={"ci": "run-4711"}) as sbx:
        return sbx.run(f"cd /work/repo && npx vitest run --shard={i + 1}/{shards}", timeout=1800).exit_code


with ThreadPoolExecutor(shards) as pool:
    codes = list(pool.map(shard, range(shards)))
sys.exit(0 if all(code == 0 for code in codes) else 1)
```

## Limits to keep in mind

When you start many sandboxes at once, keep your plan's limits in mind:

| | |
| - | - |
| Sandboxes kept | By plan: 100 to 2,000, awake or asleep. Delete each copy when its task is done; above the number a create is refused |
| Starts a day | By plan: 200 to 2,400, then \$0.03 each |
| Retries | Give each create an `Idempotency-Key` per task, so a retry never starts a second copy |

[Errors, retries and limits](https://docs.fibre.dev/production/errors-and-limits.md) explains every limit in detail.

## Related

> [card] [Snapshots](https://docs.fibre.dev/setup/snapshots.md)
>
> What a new sandbox takes from its snapshot.

> [card] [A coding agent on your repo](https://docs.fibre.dev/use-cases/coding-agent.md)
>
> The single-task version of this page, step by step.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.