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

# Fork

> Copy a running sandbox into children that start from its memory and disk and then run on their own.

A fork of a running sandbox answers `201`.

A fork pauses a sandbox, takes a copy-on-write snapshot of its memory and disk, and restores the children on pre-spawned blank VMs. The parent keeps running after the fork; the children see the parent's memory at the moment of
the fork and then diverge.

## Fork a sandbox

```bash theme={"theme":"css-variables"}
curl -sS https://api.styne.ai/sandboxes/$SANDBOX_ID/fork \
  -H "Authorization: Bearer $STYNE_API_KEY" \
  -H "content-type: application/json" \
  -d '{"count": 1, "timeout": 300}'
```

`count` is the number of children, default 1. `timeout` (seconds) and `metadata` apply to the children. The answer is
`201` and a list with one entry per child, each holding the child's sandbox as a create answer:

```text theme={"theme":"css-variables"}
[{"sandbox": {"templateID": "code", "sandboxID": "vm...", "domain": "styne.ai", ...}}]
```

Each child is a normal sandbox: use its `sandboxID` for exec, files and kill. Children count against your concurrent
sandbox limit, so a fork that would exceed it answers `429` (see [limits](https://docs.styne.ai/limits.md)).

## Forks under heavy load

A fork is admitted behind creates. While the node is busy it answers `503` (`capacity`, `admission_deadline_exceeded`) or takes
several seconds, and a burst of forks from many sandboxes at once is refused more often than a single one (measured on the
test region on 2026-11-13: a storm of forks at 8 times the normal create rate completed fewer than a third of its forks on
the first try). Retry a refused fork with a growing wait, as [parallel fan-out](https://docs.styne.ai/guide-fan-out.md) does, and keep the number of
simultaneous forks small.

## Best of N

Set a sandbox up once, fork it into N children, try one attempt in each at the same time, keep the best child and
kill the rest. Each child is a sandbox of its own: it is billed from the fork that made it until it is killed, so the
attempts you discard cost only the seconds they ran. The children of one fork restore from one snapshot of the
parent, so N children cost one snapshot, not N.

```python theme={"theme":"css-variables"}
import json
import os
import urllib.request
from concurrent.futures import ThreadPoolExecutor

from e2b import Sandbox

os.environ.setdefault("E2B_API_URL", "https://api.styne.ai")
os.environ["E2B_API_KEY"] = os.environ["STYNE_API_KEY"]
API = os.environ["E2B_API_URL"]
N = 5

def fork(sandbox_id: str, count: int, timeout: int = 600) -> list[str]:
    """POST /sandboxes/{id}/fork: the children's sandbox ids."""
    req = urllib.request.Request(
        f"{API}/sandboxes/{sandbox_id}/fork",
        data=json.dumps({"count": count, "timeout": timeout}).encode(),
        headers={"Authorization": f"Bearer {os.environ['STYNE_API_KEY']}", "content-type": "application/json"},
        method="POST",
    )
    with urllib.request.urlopen(req, timeout=60) as answer:
        return [(child.get("sandbox") or child)["sandboxID"] for child in json.load(answer)]

def attempt(sandbox_id: str) -> tuple[int, Sandbox]:
    """One attempt in one child; here a random score stands in for the agent's next step and its grade."""
    child = Sandbox.connect(sandbox_id)
    run = child.commands.run("test -s /home/user/setup.txt && od -An -N2 -tu2 /dev/urandom")
    return int(run.stdout.split()[0]), child

parent = Sandbox.create(template="base", timeout=900)
parent.commands.run("echo 'cloned, installed, warmed up' > /home/user/setup.txt")
children = fork(parent.sandbox_id, N)
with ThreadPoolExecutor(max_workers=N) as pool:
    results = list(pool.map(attempt, children))
score, best = max(results, key=lambda r: r[0])
for _, child in results:
    if child is not best:
        child.kill()
parent.kill()
print(f"kept {best.sandbox_id} with score {score} of {len(results)} attempts")
best.kill()
```

The example uses the unmodified `e2b` package for create, exec, connect and kill (see [Switch from E2B](https://docs.styne.ai/e2b-drop-in.md))
and one HTTP call for the fork. For the next round, fork the kept child the same way: a child forks like any sandbox.

## What a fork is not

* It is not a re-run of the parent's commands: the child starts from the parent's memory, not from its template.
* It is not free of the parent: a running parent is paused for the snapshot and resumes when the fork returns. A paused
  parent can be forked too and stays paused (one parked on disk is woken for the snapshot and paused again in memory).
  A snapshot of a paused sandbox works the same way.

A snapshot of a sandbox is a separate call; see [snapshots](https://docs.styne.ai/snapshots.md).

## Operations

| Method | Path | What it does |
| - | - | - |
| `POST` | `/sandboxes/{id}/fork` | Fork a running sandbox into copies |


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