> ## 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.

# A sandbox per user

> Give every user of your product their own sandbox: a workspace for their agent, their files and their running app. Three patterns with their monthly costs, the code to find or create a user's sandbox, and what to do when users come and go.

Many products give **each user a machine of their own**: an AI app builder, a coding assistant, a notebook, or an
agent that works on the user's files. Products like these have three needs in common:

* **Each user's code must be kept apart** from everyone else's.
* **A user's work must still be there** when they come back tomorrow.
* **The bill must not grow because of users who are not active** right now.

This page shows how to meet all three with Fibre, and what it costs.

## Three patterns

There are three common ways to give users sandboxes. The first one suits almost every product:

| Pattern | How it works | A user costs, per month | Use it when |
| - | - | - | - |
| **Sleep between turns** (Fibre's default) | One sandbox per user. It sleeps a few minutes after the last action and wakes on the next | **Only their active minutes**: 20 hours of use on `default` is **\$0.60** | Almost always |
| Always on | `idle_timeout_sec: 0`. Never sleeps | 730 hours on `medium`: **\$21.90** | Bots, workers, apps that must answer in milliseconds |
| One sandbox per task | A fresh copy of a snapshot per request, deleted after | Each task's seconds | Stateless jobs: code execution, file conversion |

**With sleep, inactive users cost nothing for compute.** You do not need to write any code to stop and start
sandboxes: a request to a sleeping sandbox wakes it, with the user's programs and memory exactly as they left
them.

## Find or create a user's sandbox

Each time a user does something, your app needs their sandbox. You do not need to store sandbox IDs in your own
database for this: **label each sandbox with the user's ID**, and look it up by that label. If the user does not
have a sandbox yet, create one. It is kept until you delete it, so it is there whenever the user comes back:

```bash title="CLI" run theme={null}
sandbox_for_user() {
  local id
  id=$(fibre list --label app=builder --label user="$1" --json | jq -r '.[0].id // empty')
  if [ -n "$id" ]; then
    echo "$id"
  else
    fibre create --label app=builder --label user="$1" --idle-timeout 5m --port 3000 --json | jq -r .id
  fi
}

FIRST=$(sandbox_for_user user-42)
AGAIN=$(sandbox_for_user user-42)
[ "$FIRST" = "$AGAIN" ] && echo "the same sandbox on every visit"
```

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

async function sandboxForUser(userId: string): Promise<Sandbox> {
  for await (const existing of Sandbox.list({ labels: { app: "builder", user: userId } })) {
    return existing;
  }
  return Sandbox.create({
    labels: { app: "builder", user: userId },
    idleTimeout: 300,                                  // sleep 5 minutes after the last action
    exposedPort: 3000,                                 // the user's app, at the sandbox's URL
  });
}

const first = await sandboxForUser("user-42");
const again = await sandboxForUser("user-42");
console.log(first.id === again.id); // true: the same sandbox on every visit
```

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


def sandbox_for_user(user_id: str) -> Sandbox:
    for existing in Sandbox.list(labels={"app": "builder", "user": user_id}):
        return existing
    return Sandbox.create(
        labels={"app": "builder", "user": user_id},
        idle_timeout=300,  # sleep 5 minutes after the last action
        exposed_port=3000,  # the user's app, at the sandbox's URL
    )


first = sandbox_for_user("user-42")
again = sandbox_for_user("user-42")
print(first.id == again.id)  # True: the same sandbox on every visit
```

There is one subtle case. If two requests for a brand-new user arrive at the same moment, both might find no
sandbox and both might create one. To prevent that, send an **idempotency key based on the user's ID**. Both
requests then get the same sandbox:

```typescript title="TypeScript" norun reason="shows the header option on a raw call" theme={null}
await fibre.json("POST", "/v1/sandboxes", {
  body: { labels: { app: "builder", user: userId }, idle_timeout_sec: 300 },
  headers: { "Idempotency-Key": `builder-user-${userId}` },
});
```

```python title="Python" norun reason="shows the header option on a raw call" theme={null}
fibre.json(
    "POST", "/v1/sandboxes",
    json={"labels": {"app": "builder", "user": user_id}, "idle_timeout_sec": 300},
    headers={"Idempotency-Key": f"builder-user-{user_id}"},
)
```

## Start every user ready

A new user should not have to wait for `npm install` to finish before they can start. Prepare one sandbox with your
stack, save it as a [snapshot](https://docs.fibre.dev/setup/snapshots.md), and create every user's sandbox from it. **Each one then starts
with the dependencies installed and your development server already running:**

```bash title="CLI" norun reason="needs your own snapshot" theme={null}
fibre create --snapshot builder-stack-v3 --label app=builder --label user="$1" --json | jq -r .id
```

```typescript title="TypeScript" norun reason="needs your own snapshot" theme={null}
return Sandbox.create({ snapshot: "builder-stack-v3", labels: { app: "builder", user: userId } });
```

```python title="Python" norun reason="needs your own snapshot" theme={null}
return Sandbox.create(snapshot="builder-stack-v3", labels={"app": "builder", "user": user_id})
```

## Show the user their app

If you create the sandbox with `exposedPort`, whatever the user's app serves on that port is available at the
sandbox's `url`. You can show it in a frame next to your chat, or simply give the user the link. **A visit wakes
a sleeping sandbox**, so the preview still works after the user has been away. See
[public URLs](https://docs.fibre.dev/connect/public-urls.md).

## When users come and go

Here is what to do, or not do, as users come and go:

| Event | Do |
| - | - |
| User returns after an hour | Nothing: the next call wakes their sandbox as they left it |
| User returns after a week | Nothing: their sandbox is kept until you delete it |
| User inactive for good | It sleeps, and only its storage is billed. Delete it when your product decides the user has gone, such as when they close their account |
| User deletes their project | Delete the sandbox. **Only on an explicit action**, never on a timer |
| You ship a new stack | New users start from the new snapshot; offer existing users a "rebuild" that creates a fresh sandbox |

> [!TIP]
>
> **Keep a copy of the user's important work outside the sandbox as well.** Push their code to a repository, or copy
> important files out with the [files API](https://docs.fibre.dev/sandboxes/files.md) when a session ends. A sandbox is a workspace, not a
> backup.

## Clean up

```bash title="CLI" run theme={null}
fibre delete "$FIRST"
```

```typescript title="TypeScript" run theme={null}
await first.delete();
```

```python title="Python" run theme={null}
first.delete()
```

## What it costs, worked through

Here is an example with real numbers: 1,000 users on the `medium` size, each active for 30 minutes a day, on 20
days a month.

| | |
| - | - |
| Awake hours | 1,000 × 0.5 × 20 = 10,000 |
| Compute | 10,000 × $0.030 = **$300 a month\*\* |
| The same users, always on | 1,000 × 730 × $0.030 = $21,900 a month |

The only difference between those two lines is sleep. See [pricing](https://docs.fibre.dev/get-started/pricing.md) for all the prices.

## Related

> [card] [Sleep and wake](https://docs.fibre.dev/sandboxes/sleep-and-wake.md)
>
> What a sleeping sandbox keeps, and what wakes it.

> [card] [A key for one sandbox](https://docs.fibre.dev/get-started/api-keys.md#a-key-for-one-sandbox)
>
> Let the user's agent manage its own sandbox, and nothing else.


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