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

# Errors, retries and limits

> Handle Fibre's errors well in production: the error shape, which errors to retry and how, safe retries with idempotency keys, and every limit in one place.

In production, some calls will fail. The network might drop for a moment, you might reach a limit, or a sandbox
might already have been deleted. **Handling errors well mostly comes down to one decision: should your code try
again, or should it stop and fix something?** This page gives you what you need to make that decision in code.

## Every error looks the same

Whatever goes wrong, Fibre answers with the same kind of JSON, so you can handle every error in one place:

```bash title="CLI" run expect-exit=3 theme={null}
fibre get sbx-0000000000 --json   # {"error": {"code": "sandbox_not_found", …}}, exit code 3
```

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

try {
  await Sandbox.get("sbx-0000000000");
} catch (e) {
  if (e instanceof NotFoundError) console.log("gone:", e.code, e.requestId); // gone: sandbox_not_found req_…
  else throw e;
}
```

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

try:
    Sandbox.get("sbx-0000000000")
except NotFoundError as e:
    print("gone:", e.code, e.request_id)  # gone: sandbox_not_found req_…
```

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

> [accordion] Response
>
> ```json title="response" expected theme={null}
> {
>   "error": "…",
>   "code": "sandbox_not_found",
>   "request_id": "…",
>   "docs_url": "…"
> }
> ```

| Field | Use it for |
| - | - |
| `code` | **Your logic.** Stable names like `sandbox_not_found`, safe to `switch` on. Never parse `error` |
| `error` | A sentence for a person: logs, alerts |
| `request_id` | **Support.** Include it when you ask us about a failure; it finds the exact request |
| `docs_url` | The code's entry in the [error list](https://docs.fibre.dev/api-reference/errors.md) |
| others | Some errors add fields: `details` (which body fields are wrong), `required` and `granted` (scopes), `limit` |

In the SDKs, every error is a `FibreError` with `status`, `code`, `requestId` and `docsUrl` (`request_id` and
`docs_url` in Python). Each kind of error also has its own class, so you can catch only the ones you care about:

| Class | Status |
| - | - |
| `ValidationError` | 400, 422 |
| `AuthenticationError` | 401 |
| `PaymentRequiredError` | 402 |
| `PermissionDeniedError` | 403 |
| `NotFoundError` | 404 |
| `ConflictError` | 409 |
| `RateLimitError` | 429, with `retryAfter` in seconds |
| `ServerError` | 5xx |
| `ConnectionError`, `TimeoutError` | No answer arrived |

## Retry, or not?

The HTTP status tells you which kind of problem you have, and whether trying again can help:

| Status | Retry? | What to do |
| - | - | - |
| 400, 422 | **No** | Your request is wrong. Read `code` and `details`, fix it |
| 401, 403 | **No** | Wrong, expired or too narrow key. See [API keys](https://docs.fibre.dev/get-started/api-keys.md#errors) |
| 402 | **No** | Billing: add funds, turn on auto top-up, or choose a plan |
| 404 | **No** | It does not exist (deleted, expired, or never yours). Treat as final |
| 409 | **Sometimes** | A state conflict. `idempotency_key_in_progress`: wait and retry. Others: fix the state first |
| 429 | **Yes, later** | A limit. Wait (`Retry-After` when given) or free capacity, then retry |
| 500, 502, 503, 504 | **Yes** | Temporary. Retry with backoff: 1 s, 2 s, 4 s, up to about a minute |
| No answer | **Yes**, if the call is safe to repeat | See below |

**The SDKs already retry for you.** When a connection drops, or Fibre answers `429`, `502`, `503` or
`504`, the SDK tries again twice, waiting a little longer each time, as long as the call is safe to repeat. To
change how many times, use `new Fibre({ maxRetries })`, or `Fibre(max_retries=…)` in Python.

## Retrying a create safely

One case needs special care: **a request to create a sandbox that times out**. You cannot tell whether the sandbox
was created or not, and simply trying again could create a second one that you pay for. To avoid that, send an
`Idempotency-Key` header. **If you retry with the same key, Fibre returns the first sandbox instead of creating
another:**

```bash title="curl" norun reason="shows the header; the create page runs the same call" theme={null}
curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes" \
  -H "Idempotency-Key: user-42-task-7" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \
  -d '{"labels": {"user": "42", "task": "7"}}'
```

* **Base the key on what you are creating**, for example `user-42-task-7`, or a random ID that you store with the
  job.
* **A key is remembered for 24 hours.** Using the same key with a different request is refused
  (`422 idempotency_key_reused`).
* **In the SDKs, `Sandbox.create()` sends a key for you**, so the SDK's own retries never create a second
  sandbox.

There is more about this in [retry without making two](https://docs.fibre.dev/sandboxes/overview.md#retry-without-making-two).

## A retry helper

If you make calls outside the SDK, or want to wait longer than its built-in retries do, a small helper like this
one retries temporary errors and gives up on everything else:

```typescript title="TypeScript" norun reason="a helper for your own code" theme={null}
import { FibreError, ConnectionError, TimeoutError } from "@fibre-dev/sdk";

const RETRY = new Set([429, 500, 502, 503, 504]);

export async function withRetry<T>(call: () => Promise<T>, attempts = 5): Promise<T> {
  for (let i = 0; ; i++) {
    try {
      return await call();
    } catch (e) {
      const temporary = e instanceof ConnectionError || e instanceof TimeoutError ||
        (e instanceof FibreError && RETRY.has(e.status));
      if (!temporary || i === attempts - 1) throw e;
      const wait = (e as any).retryAfter ?? Math.min(2 ** i, 30) + Math.random();
      await new Promise((r) => setTimeout(r, wait * 1000));
    }
  }
}
```

```python title="Python" norun reason="a helper for your own code" theme={null}
import random
import time

from fibre import FibreConnectionError, FibreError, FibreTimeoutError

RETRY = {429, 500, 502, 503, 504}


def with_retry(call, attempts=5):
    for i in range(attempts):
        try:
            return call()
        except FibreError as e:
            temporary = isinstance(e, (FibreConnectionError, FibreTimeoutError)) or e.status in RETRY
            if not temporary or i == attempts - 1:
                raise
            wait = getattr(e, "retry_after", None) or min(2**i, 30) + random.random()
            time.sleep(wait)
```

## Limits

Here is every limit in one place:

| | Limit |
| - | - |
| **Sandboxes kept** | By plan: 100, 300, 1,000 or 2,000, awake or asleep. Above it a create is refused (`429 sandbox_limit`) |
| **Starts and wakes a day** | By plan: 200, 840, 1,680 or 2,400. Above it, \$0.03 each |
| **API requests** | Per account, each minute: 1,200 reads (`GET`) and 600 other requests on the \$20 plan; 3×, 10× and 20× that on the larger plans. Above it `429 rate_limited`, with `retry_after_ms` |
| Lifetime | None unless you set one: kept until you delete it. 60 seconds to 10 years; change or remove it at any time |
| Idle timeout | 0 (never sleep) to a day; 300 seconds unless set |
| Sizes | Up to 16 vCPU, 32 GB memory, 80 GB disk |
| Labels | 16 per sandbox; keys up to 63 characters, values up to 128 |
| List page | 50 sandboxes, up to 200 with `limit` |
| HTTP exec | 30 seconds; 4 MB of output per stream |
| Background command | No time limit, or `timeout_sec` |
| Write to a command's input | 8 MB per call |
| Files | Up to the sandbox's free disk |
| Network allow list | 200 entries |
| Browser | One per sandbox |
| Shells | 5 open at once per user |
| Secrets | 50 named per sandbox or command |
| API keys | Expire after up to 365 days, or never |
| Idempotency keys | 1 to 255 characters, kept 24 hours |
| Webhook endpoints | 10 per account; 10 seconds to answer; 7 attempts |
| Build context | 2 GB |
| Free trial | 2 sandboxes kept, `xsmall`, `small` and `medium` sizes, 100 starts a day |

## Related

> [card] [All error codes](https://docs.fibre.dev/api-reference/errors.md)
>
> Every error code, its HTTP status and what it means.

> [card] [Usage and billing](https://docs.fibre.dev/production/usage.md)
>
> See how close you are to your plan's limits today.


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