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

# Sleep, wake and lifetime

> An idle sandbox sleeps with its memory and wakes on the next call, with its programs, data and open files where they were. What is kept, what wakes it, how to tune it, and what it costs.

Most of a sandbox's life is spent waiting: for the user's next message, the next pull request, the next test run.
**Fibre does not charge you for that waiting.** When nothing has happened in a sandbox for a while, it goes to
sleep. When the next call comes, it wakes up **exactly where it was**, with the same running programs, the same
data in memory and the same open files.

This is different from most machines you may have used. Stopping a server normally throws away everything in
memory, and starting it again means booting from scratch. A Fibre sandbox keeps its memory while it sleeps, so
waking it is more like opening a laptop lid than switching on a computer.

Keeping memory across a sleep changes how you can build:

* **There is no slow start to design around.** A dev server that took a long time to start is already running
  after a wake. An agent's process still holds its conversation. A dataset loaded into memory is still loaded.
* **You do not write code to save and restore state.** Nothing needs to be written to disk before a sleep, and
  nothing needs to be rebuilt after a wake.
* **One sandbox per user becomes affordable.** If a thousand users each work ten minutes an hour, you pay for ten
  minutes an hour each, not for a thousand machines running all the time.

## See it: memory survives a sleep

The best way to understand this is to see it. In this example, a small server loads two million rows into memory
and counts the requests it receives. We call it, let the sandbox fall asleep, and then call it again. **If memory
really survives the sleep, the count carries on from where it was, and the data is not loaded a second time.**

**1. Start a sandbox that sleeps after one quiet minute**

```bash title="CLI" run theme={null}
SBX=$(fibre create --idle-timeout 1m --lifetime 15m --label docs=sleep --json | jq -r .id)
```

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

const sbx = await Sandbox.create({ idleTimeout: 60, lifetime: 900, labels: { docs: "sleep" } });
```

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

sbx = Sandbox.create(idle_timeout=60, lifetime=900, labels={"docs": "sleep"})
```

```bash title="curl" run capture=SBX=.id theme={null}
curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \
  -d '{"idle_timeout_sec": 60, "lifetime_sec": 900, "labels": {"docs": "sleep"}}'
```

**2. Run a server that holds data in memory**

```bash title="CLI" run theme={null}
fibre exec "$SBX" -i -- sh -c 'mkdir -p /work && cat > /work/server.py' <<'PY'
import http.server, json, os, time
DATA = list(range(2_000_000))            # loaded once, lives in memory
LOADED_AT = time.strftime('%H:%M:%S')
hits = 0
class Handler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        global hits
        hits += 1
        body = json.dumps({'pid': os.getpid(), 'loaded_at': LOADED_AT, 'rows_in_memory': len(DATA), 'hits': hits})
        self.send_response(200); self.end_headers(); self.wfile.write(body.encode())
    def log_message(self, *args): pass
http.server.HTTPServer(('127.0.0.1', 8000), Handler).serve_forever()
PY
fibre exec "$SBX" --detach --keep -- python3 /work/server.py

# wait until it has loaded its data and answers (this is request 1)
fibre exec "$SBX" --timeout 60 -- 'until curl -sf -o /dev/null localhost:8000; do sleep 1; done'

BEFORE=$(fibre exec "$SBX" -- curl -sf localhost:8000)
echo "$BEFORE"   # {"pid": 21, "loaded_at": "14:02:11", "rows_in_memory": 2000000, "hits": 2}
```

```typescript title="TypeScript" run theme={null}
await sbx.files.write("/work/server.py", [
  "import http.server, json, os, time",
  "DATA = list(range(2_000_000))            # loaded once, lives in memory",
  "LOADED_AT = time.strftime('%H:%M:%S')",
  "hits = 0",
  "class Handler(http.server.BaseHTTPRequestHandler):",
  "    def do_GET(self):",
  "        global hits",
  "        hits += 1",
  "        body = json.dumps({'pid': os.getpid(), 'loaded_at': LOADED_AT, 'rows_in_memory': len(DATA), 'hits': hits})",
  "        self.send_response(200); self.end_headers(); self.wfile.write(body.encode())",
  "    def log_message(self, *args): pass",
  "http.server.HTTPServer(('127.0.0.1', 8000), Handler).serve_forever()",
].join("\n") + "\n");

await sbx.spawn(["python3", "/work/server.py"], { keep: true });

// wait until it has loaded its data and answers (this is request 1)
await sbx.run("until curl -sf -o /dev/null localhost:8000; do sleep 1; done", { timeout: 60 });

const ask = () => sbx.run("curl -sf localhost:8000").then((r) => JSON.parse(r.stdout));
const before = await ask();
console.log(before); // { pid: 21, loaded_at: '14:02:11', rows_in_memory: 2000000, hits: 2 }
```

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

sbx.files.write("/work/server.py", "\n".join([
    "import http.server, json, os, time",
    "DATA = list(range(2_000_000))            # loaded once, lives in memory",
    "LOADED_AT = time.strftime('%H:%M:%S')",
    "hits = 0",
    "class Handler(http.server.BaseHTTPRequestHandler):",
    "    def do_GET(self):",
    "        global hits",
    "        hits += 1",
    "        body = json.dumps({'pid': os.getpid(), 'loaded_at': LOADED_AT, 'rows_in_memory': len(DATA), 'hits': hits})",
    "        self.send_response(200); self.end_headers(); self.wfile.write(body.encode())",
    "    def log_message(self, *args): pass",
    "http.server.HTTPServer(('127.0.0.1', 8000), Handler).serve_forever()",
]) + "\n")

sbx.spawn(["python3", "/work/server.py"], keep=True)

# wait until it has loaded its data and answers (this is request 1)
sbx.run("until curl -sf -o /dev/null localhost:8000; do sleep 1; done", timeout=60)


def ask():
    return json.loads(sbx.run("curl -sf localhost:8000").stdout)


before = ask()
print(before)  # {'pid': 21, 'loaded_at': '14:02:11', 'rows_in_memory': 2000000, 'hits': 2}
```

```bash title="curl" run theme={null}
cat <<'EOF' | curl -sS -o /dev/null -X PUT "$FIBRE_API_URL/v1/sandboxes/$SBX/files/content?path=/work/server.py" \
  -H "Authorization: Bearer $FIBRE_API_KEY" --data-binary @-
import http.server, json, os, time
DATA = list(range(2_000_000))            # loaded once, lives in memory
LOADED_AT = time.strftime('%H:%M:%S')
hits = 0
class Handler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        global hits
        hits += 1
        body = json.dumps({'pid': os.getpid(), 'loaded_at': LOADED_AT, 'rows_in_memory': len(DATA), 'hits': hits})
        self.send_response(200); self.end_headers(); self.wfile.write(body.encode())
    def log_message(self, *args): pass
http.server.HTTPServer(('127.0.0.1', 8000), Handler).serve_forever()
EOF

curl -sS -o /dev/null -X POST "$FIBRE_API_URL/v1/sandboxes/$SBX/commands" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \
  -d '{"command": ["python3", "/work/server.py"], "keep": true}'

# wait until it has loaded its data and answers (this is request 1)
curl -sS -o /dev/null -X POST "$FIBRE_API_URL/v1/sandboxes/$SBX/exec" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \
  -d '{"command": ["sh", "-c", "until curl -sf -o /dev/null localhost:8000; do sleep 1; done"]}'

curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes/$SBX/exec" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \
  -d '{"command": ["curl", "-sf", "localhost:8000"]}' | jq -r .stdout
```

> [accordion] Response
>
> ```json title="response" expected theme={null}
> {
>   "pid": "…",
>   "loaded_at": "…",
>   "rows_in_memory": 2000000,
>   "hits": 2
> }
> ```

`keep: true` starts the server as a program that keeps running on its own, independently of the call that started
it. See [keep a program running](https://docs.fibre.dev/sandboxes/running-commands.md#keep-a-program-running).

**3. Leave it alone until it sleeps**

There is nothing to call here. Because this sandbox was created with a one-minute idle timeout, it goes to sleep
on its own after a quiet minute, and its `status` changes from `running` to `standby`. The code below simply
watches for that:

```bash title="CLI" run theme={null}
until [ "$(fibre get "$SBX" --json | jq -r .status)" = standby ]; do sleep 5; done
fibre get "$SBX" --json | jq -r .status   # standby
```

```typescript title="TypeScript" run theme={null}
while ((await sbx.refresh()).status !== "standby") await new Promise((resolve) => setTimeout(resolve, 5000));
console.log(sbx.status); // standby
```

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

while sbx.refresh().status != "standby":
    time.sleep(5)
print(sbx.status)  # standby
```

```bash title="curl" run theme={null}
for i in $(seq 1 40); do
  status=$(curl -sS "$FIBRE_API_URL/v1/sandboxes/$SBX" -H "Authorization: Bearer $FIBRE_API_KEY" | jq -r .status)
  [ "$status" = standby ] && break
  sleep 5
done
echo "$status"
```

> [accordion] Output
>
> ```text title="output" expected theme={null}
> standby
> ```

**From this moment on, you are not paying for compute.**

**4. Call it again**

There is no separate "wake" call. You simply use the sandbox again, and Fibre wakes it before answering:

```bash title="CLI" run theme={null}
AFTER=$(fibre exec "$SBX" -- curl -sf localhost:8000)
echo "$AFTER"    # {"pid": 21, "loaded_at": "14:02:11", "rows_in_memory": 2000000, "hits": 3}
[ "$(echo "$AFTER" | jq .pid)" = "$(echo "$BEFORE" | jq .pid)" ] && echo "the same process, with its memory"
```

```typescript title="TypeScript" run theme={null}
const after = await ask();
console.log(after); // { pid: 21, loaded_at: '14:02:11', rows_in_memory: 2000000, hits: 3 }
console.log(after.pid === before.pid, after.loaded_at === before.loaded_at); // true true
```

```python title="Python" run theme={null}
after = ask()
print(after)  # {'pid': 21, 'loaded_at': '14:02:11', 'rows_in_memory': 2000000, 'hits': 3}
print(after["pid"] == before["pid"], after["loaded_at"] == before["loaded_at"])  # True True
```

```bash title="curl" run theme={null}
curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes/$SBX/exec" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \
  -d '{"command": ["curl", "-sf", "localhost:8000"]}' | jq -r .stdout
```

> [accordion] Response
>
> ```json title="response" expected theme={null}
> {
>   "pid": "…",
>   "loaded_at": "…",
>   "rows_in_memory": 2000000,
>   "hits": 3
> }
> ```

**Look at `hits`: it is 3, not 1.** The answer came from the same process (the same `pid`) that loaded its data at
the same time (the same `loaded_at`). The server was not restarted: it was resumed, and the two million rows were
never loaded again.

## What is kept

Here is what a sandbox keeps while it sleeps:

| | Across a sleep |
| - | - |
| **Memory** | Kept: variables, caches, loaded models and datasets |
| **Processes** | Kept on `vm`. On `standard`: the sandbox's main program and everything started with `keep` |
| **Files** | Kept, including open files and their positions |
| **Browser** | Kept: tabs, logins, cookies, the page you were on |
| **Its address** | The same `url` and the same `id` |
| **Environment** | The same image, variables and labels |
| **Connections to other machines** | Not always: see below |

> [!NOTE]
>
> There is one difference between the two [runtimes](https://docs.fibre.dev/sandboxes/runtimes.md). On `standard`, a program you started
> with a plain exec or command, and which is still running when the sandbox goes to sleep, is **not** there after
> the wake. So start anything that should keep running with `keep: true`. On `vm`, every process is kept, and you
> do not need to think about it.

### Connections to other services

Programs inside the sandbox keep their state across a sleep, but **the services they were talking to do not wait
for them**. A database connection, a message queue, or a pool of HTTP connections that was open when the sandbox
fell asleep may have been closed by the other side by the time it wakes. The first query on such a connection then
fails with an error such as "connection reset" or "server closed the connection".

Most client libraries can handle this for you. Turn on the option that checks or retries a connection before using
it, for example `pool_pre_ping=True` in SQLAlchemy, a keep-alive or retry option in your HTTP client, or simply
reconnect when a call fails with a connection error. Connections that arrive at the sandbox, such as visitors to
its `url`, are not affected: each new visitor wakes it and is served.

## When it sleeps

A sandbox goes to sleep when nothing has happened in it for its **idle timeout**, which is 300 seconds (5 minutes)
unless you choose another value. Fibre counts any of these as "something happening":

* **A command or exec is running**, or a shell or terminal is open.
* **Its programs are using the CPU.**
* **Network traffic is flowing, in either direction.** This matters for agents: an agent waiting for a model's
  answer has a connection open, so **it is never put to sleep in the middle of a thought**.

Only when all of these have been quiet for the whole idle timeout does the sandbox go to sleep.

## What wakes it

Any call that needs the sandbox wakes it, with no extra step on your side:

| Call | Wakes it |
| - | - |
| An exec or a new command | Yes |
| A files call | Yes |
| An HTTP request to its `url` | Yes: the first visitor waits a moment, then gets the page |
| Opening its browser or desktop link | Yes |
| `GET /v1/sandboxes/{id}` (reading its status) | **No**: you can watch a sleeping sandbox without waking it |

The call that wakes a sandbox simply takes a moment longer than usual. If several calls arrive while it is waking,
they all wait for that same wake, and nothing is started twice.

## Tune it

You decide how quickly a sandbox goes to sleep. Set the idle timeout when you create the sandbox, or change it at
any time. Here, setting it to `0` means the sandbox never sleeps:

```bash title="CLI" run theme={null}
fibre update "$SBX" --idle-timeout 0   # never sleep
```

```typescript title="TypeScript" run theme={null}
await sbx.update({ idleTimeout: 0 }); // never sleep
```

```python title="Python" run theme={null}
sbx.update(idle_timeout=0)  # never sleep
```

```bash title="curl" run theme={null}
curl -sS -X PATCH "$FIBRE_API_URL/v1/sandboxes/$SBX" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \
  -d '{"idle_timeout_sec": 0}'
```

> [accordion] Response
>
> ```json title="response" expected theme={null}
> {
>   "id": "…",
>   "idle_timeout_sec": 0
> }
> ```

Which value to choose depends on how the sandbox is used:

| `idle_timeout_sec` | Good for |
| - | - |
| `30` to `120` | Chat and agent turns: sleep quickly between messages, save the most |
| `300` (default) | Interactive work: survives a coffee, sleeps over lunch |
| `1800` and up | Sessions where even a short wake would be noticed |
| `0` | **Always on**: a bot, a queue worker, a server that must answer instantly. Billed for every second |

## Lifetime

Sleeping is not the same as being deleted, and neither is time passing: **a sandbox is kept until you delete it**,
asleep or awake. Fibre never deletes one on its own. While it exists, its saved state counts towards your
[storage](https://docs.fibre.dev/get-started/pricing.md#storage).

If you want a sandbox to delete itself, give it a **lifetime**: from 60 seconds up to 10 years, when you create it
or later. It is deleted when the lifetime ends, whether it is asleep or awake at that moment. Each new lifetime
counts from the moment you set it:

```bash title="CLI" run theme={null}
fibre update "$SBX" --lifetime 30m   # deleted 30 minutes from now
```

```typescript title="TypeScript" run theme={null}
await sbx.update({ lifetime: 1800 });
console.log(sbx.expiresAt); // 30 minutes from now
```

```python title="Python" run theme={null}
sbx.update(lifetime=1800)
print(sbx.expires_at)  # 30 minutes from now
```

```bash title="curl" run theme={null}
curl -sS -X PATCH "$FIBRE_API_URL/v1/sandboxes/$SBX" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \
  -d '{"lifetime_sec": 1800}'
```

> [accordion] Response
>
> ```json title="response" expected theme={null}
> {
>   "id": "…",
>   "expires_at": "…"
> }
> ```

To remove the lifetime, so the sandbox is kept until you delete it, send `null`:

```bash title="CLI" run theme={null}
fibre update "$SBX" --no-lifetime   # kept until you delete it
```

```typescript title="TypeScript" run theme={null}
await sbx.update({ lifetime: null });
console.log(sbx.expiresAt); // null
```

```python title="Python" run theme={null}
sbx.update(lifetime=None)
print(sbx.expires_at)  # None
```

```bash title="curl" run theme={null}
curl -sS -X PATCH "$FIBRE_API_URL/v1/sandboxes/$SBX" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \
  -d '{"lifetime_sec": null}'
```

> [accordion] Response
>
> ```json title="response" expected theme={null}
> {
>   "id": "…",
>   "expires_at": null
> }
> ```

> [!TIP]
>
> A workspace per user needs no lifetime: it sleeps while they are away and is there when they come back. If you
> would rather have Fibre delete the workspaces of users who never return, give each one a lifetime and **extend it
> each time the user shows up**.

### When it is deleted

When you delete it, or when a lifetime you set ends, a sandbox is gone for good: its running programs are stopped, and
its files, its memory and its address are deleted. This cannot be undone, and nothing is kept for you to restore.

### Keep work after deleting it

A sandbox keeps its work for as long as you keep the sandbox. To keep what it produced after you delete it:

* **Copy the results out** before it ends: read the files you need, or pack a folder and download it (see
  [files](https://docs.fibre.dev/sandboxes/files.md)), or push code to its repository from inside the sandbox.
* **Save it as a [snapshot](https://docs.fibre.dev/setup/snapshots.md)** to start new sandboxes exactly as it is now, memory included. A
  snapshot outlives the sandbox it came from.

## What it costs

| State | Compute | Storage |
| - | - | - |
| Awake (`running`) | The size's price, **per second** | Not charged separately |
| Asleep (`standby`) | **Nothing** | Its saved state counts towards your included 20 GB |
| Deleted or expired | Nothing | Nothing |

Here is an example. A support agent's sandbox on the `medium` size works for 4 minutes in each hour of an 8-hour
day. It is awake for 32 minutes in total, which costs \*\*about $0.016 a day**. If the same sandbox were left awake
all day, it would cost $0.72 a day. See [pricing](https://docs.fibre.dev/get-started/pricing.md).

## Clean up

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

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

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

```bash title="curl" run theme={null}
curl -sS -X DELETE "$FIBRE_API_URL/v1/sandboxes/$SBX" -H "Authorization: Bearer $FIBRE_API_KEY"
```

## Related

> [card] [Run commands](https://docs.fibre.dev/sandboxes/running-commands.md)
>
> Start programs that carry on across sleep with `keep`.

> [card] [Runtimes](https://docs.fibre.dev/sandboxes/runtimes.md)
>
> On `vm`, every process survives a sleep, not only the kept ones.

> [card] [Serve an app](https://docs.fibre.dev/connect/public-urls.md)
>
> A site that sleeps when nobody visits and wakes on the next request.

> [card] [Pricing and limits](https://docs.fibre.dev/get-started/pricing.md)
>
> What awake time costs at each size.


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