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

# Rate limits

> Understand Foil API rate limits per organization and key type, read X-RateLimit response headers, handle 429 errors, and retry with Retry-After.

Foil applies rate limits per organization, key type, and environment, not per key. Every live publishable key in an organization shares one bucket, and every live secret key in an organization shares another, so adding keys doesn't add capacity. Test keys have separate buckets of the same size, so test traffic doesn't use up live capacity. Responses to requests that pass key verification carry headers that describe the bucket, and rate-limited requests return `429 Too Many Requests` with a `Retry-After` header.

## Default limits

Each bucket has a limit that applies to a 60-second window. Foil uses the organization defaults unless Foil support has configured an organization-level override.

| Key type | Default limit | Typical use |
| - | - | - |
| Publishable (`pk_*`) | `3000` units per 60 seconds | Browser and mobile SDK traffic - session setup, batch streaming, sealed-handoff minting |
| Secret (`sk_*`) | `600` units per 60 seconds | Server-side verification, session and fingerprint readback, management endpoints |

### How the window works

Each bucket is a token bucket. It holds up to the limit, so a secret key bucket holds 600 units and a publishable key bucket holds 3,000 units by default, and it starts full. Every request removes its cost from the bucket. The bucket refills continuously at the limit divided by 60 per second, which is 10 units per second for the default secret-key limit and 50 units per second for the default publishable-key limit.

A burst that fits within the bucket succeeds. Sustained traffic above the refill rate drains the bucket and gets throttled. When a request arrives and the bucket doesn't hold enough units, Foil rejects it and doesn't deduct its cost. Retrying before `Retry-After` elapses doesn't lengthen the wait, but those retries are rejected too. For high-volume integrations - fingerprint sweeps, scoring backfills, bulk audits - contact us to raise the limit for your organization.

### Per-source share of the publishable-key bucket

Publishable keys appear in your page source, so anyone can send requests with them. To keep one source from using up the whole bucket, Foil also limits how much of the publishable-key bucket each source can use. A source is one IPv4 address or one IPv6 `/64`. Each source can use a quarter of the bucket per 60 seconds, but never less than 60 units, and never more than the whole bucket. With the default limit of `3000` units, each source can use up to `750` units per 60 seconds.

A request over its source's share receives `429` with `rate_limit.exceeded`, a message that names your network address, and a `Retry-After` header for that source. Its `X-RateLimit-Limit` still describes the organization's bucket, which can have room left. Foil doesn't deduct it from the organization's bucket, so other sources are unaffected. Visitors who share one address, such as users behind a corporate network or carrier-grade NAT, draw from the same per-source share. Secret keys don't have a per-source share.

## Response headers

Every response to a request that passes key verification includes these headers:

| Header | Value |
| - | - |
| `X-RateLimit-Limit` | The bucket size for this organization and key type. |
| `X-RateLimit-Remaining` | Whole units left in the bucket after this request. This is `0` on a rejected request. |
| `X-RateLimit-Cost` | Units this request costs. This is normally `1`; weighted endpoints can charge more. A rejected request isn't charged. |

Rate-limited responses additionally include:

| Header | Value |
| - | - |
| `Retry-After` | Whole seconds, at least `1`, until the bucket holds enough units for the request. For a publishable key, this can be the time until the source's share holds enough units. Wait at least this long. Requests that arrive sooner are rejected but not deducted. |

Foil also limits how quickly a single source can present keys that Foil must verify against its database. A source that exceeds that budget receives `429` with `rate_limit.exceeded`, `Retry-After: 1`, and none of the `X-RateLimit-*` headers.

## 429 response shape

Rate-limited responses use the standard [error envelope](https://usefoil.com/docs/api-reference/errors.md):

```json theme={"dark"}
{
  "error": {
    "code": "rate_limit.exceeded",
    "message": "Rate limit exceeded for this API key. Wait for the Retry-After window to expire before retrying.",
    "status": 429,
    "retryable": true,
    "request_id": "req_..."
  }
}
```

`error.retryable` is `true` on every `rate_limit.exceeded` response. The envelope doesn't tell you when to retry. The `Retry-After` header does.

## Retry strategy

A correct retry for a 429 does three things: honor `Retry-After`, add jitter, and cap attempts. The server SDKs don't retry requests for you, so you implement the loop. The SDK error types also expose the response body but not the response headers. To read `Retry-After`, call the REST API with your own HTTP client, as the following examples do. If you use an SDK, back off exponentially instead, starting at one second, as described in [Errors](https://usefoil.com/docs/api-reference/errors.md#retry-strategy).

```javascript Node.js theme={"dark"}
async function requestWithRetry(url, options, maxAttempts = 4) {
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    const response = await fetch(url, options);
    if (response.status !== 429) return response;

    const retryAfter = Number(response.headers.get("retry-after")) || 1;
    const jitterMs = Math.floor(Math.random() * 500);
    await new Promise((r) => setTimeout(r, retryAfter * 1000 + jitterMs));
  }
  throw new Error("Rate-limited after retries");
}
```

```python Python theme={"dark"}
import time, random, requests

def request_with_retry(method, url, max_attempts=4, **kwargs):
    for attempt in range(max_attempts):
        response = requests.request(method, url, **kwargs)
        if response.status_code != 429:
            return response
        retry_after = int(response.headers.get("retry-after", "1"))
        time.sleep(retry_after + random.uniform(0, 0.5))
    raise RuntimeError("Rate-limited after retries")
```

```go Go theme={"dark"}
func requestWithRetry(client *http.Client, req *http.Request, maxAttempts int) (*http.Response, error) {
    for attempt := 0; attempt < maxAttempts; attempt++ {
        resp, err := client.Do(req)
        if err != nil {
            return nil, err
        }
        if resp.StatusCode != 429 {
            return resp, nil
        }
        retryAfter, _ := strconv.Atoi(resp.Header.Get("Retry-After"))
        if retryAfter < 1 {
            retryAfter = 1
        }
        jitter := time.Duration(rand.Intn(500)) * time.Millisecond
        time.Sleep(time.Duration(retryAfter)*time.Second + jitter)
    }
    return nil, fmt.Errorf("rate-limited after retries")
}
```

None of the server SDKs retry a rate-limited request or read `Retry-After`. Write a retry loop around every SDK or HTTP call that can receive a 429.

## What counts against the limit

Every request that passes key verification and the rate limit consumes units, including requests that go on to fail:

* Successful 2xx responses count.
* 4xx client errors from the endpoint, such as a validation failure or a missing resource, count.
* 5xx server errors count.

Some requests never consume units:

* Requests that the rate limit rejects with `429` don't count, as described in [How the window works](#how-the-window-works).
* Requests that Foil rejects while verifying the key don't count. These include a missing, malformed, or unrecognized key, a key type or mobile client that isn't allowed on the path, an origin that isn't allowed, and an inactive organization.
* Preflight `OPTIONS` requests don't count.
* The unauthenticated `GET /v2/collect/pings/:pingId` endpoint doesn't count.

Most requests cost one unit. `POST /v1/agents/ip-rotation` costs one unit per item in `items`, up to 10, so a 10-item batch costs 10 units. Foil reads the item count from the request body before it validates the body. If IP rotation isn't enabled for your organization, the request costs one unit. Read `X-RateLimit-Cost` rather than assuming every HTTP request costs one unit.

In particular, a burst of 422 validation errors during development can eat into your bucket the same way as a burst of successful calls. If your integration is hammering the API in a loop because of a bug, fix the bug rather than raising the limit.

## Reducing your request rate

If you're brushing up against the ceiling, the usual culprits and their fixes:

* **Per-request session verification.** If you're calling `GET /v1/sessions/:sessionId` on every authenticated API hit, you're doing too much work. Cache the verified sealed token locally (the token already carries the verdict), and only fall back to the sessions API for audits, escalations, or stale sessions. See [API abuse → Session reuse](https://usefoil.com/docs/use-cases/api-abuse.md).
* **Small pages.** List endpoints return 50 items per page by default and accept up to 200 with `limit`. Requesting the largest page your code can process reduces the number of requests by up to a factor of four. The SDK [iterators](https://usefoil.com/docs/api-reference/pagination.md#auto-pagination-in-the-sdks) make one request per page, so they don't reduce request count on their own.
* **Unbatched management calls.** If you're provisioning many API keys or organizations, space the calls out with backoff rather than firing them concurrently.
* **Polling that could be webhooks.** If you poll `GET /v1/sessions` to find new results, subscribe an endpoint to the `session.result.persisted` [webhook event](https://usefoil.com/docs/webhooks.md) instead.

## Raising a limit

Production integrations with sustained, legitimate load can have organization-level limits raised above the defaults. Contact support with:

* The organization you want raised
* Whether the increase is for publishable keys, secret keys, or both
* Your expected steady-state and peak RPS
* The endpoints you need headroom on

Publishable-key limits can generally go significantly higher than secret-key limits, since `pk_*` serves browser and mobile traffic.

## What's next

> [card] [Errors](https://usefoil.com/docs/api-reference/errors.md)
>
> The full error envelope, including 429 details.

> [card] [Pagination](https://usefoil.com/docs/api-reference/pagination.md)
>
> Page size, cursors, and filters.

> [card] [API abuse](https://usefoil.com/docs/use-cases/api-abuse.md)
>
> Session reuse patterns that reduce server-side verification rate.

> [card] [Authentication](https://usefoil.com/docs/api-reference/authentication.md)
>
> Key types, scopes, and lifecycle.


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