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

> ## Agent Instructions
> Unkey is two separate products. Compute builds, deploys, and runs apps behind a gateway. API Management issues API keys, enforces rate limits, manages identities and permissions, and reports usage. Say which product a page belongs to; a reader can use either without the other.
> Every Unkey API endpoint is an HTTP POST to https://api.unkey.com/v2/{service}.{procedure} with a root key in the Authorization: Bearer header. Root keys are workspace scoped.
> Error codes have the form err:{system}:{category}:{specific} and each has a page at /errors/{system}/{category}/{specific}.
> The word environment means production or preview in Compute. Rate limiting has four meanings on this site; the glossary lists them.

# ratelimit.limit and multiLimit

> Rate limit any identifier with one call, or several limits at once.

Call `ratelimit.limit` to rate limit a public API by user id, customer id, or IP address. Unkey keeps the counters, so you don't run Redis. You send the limit and the window on each call, and you return HTTP 429 when `data.success` is `false`.

`ratelimit.multiLimit` runs up to 100 checks in one call, and counts them only if they all pass. The rules live in your code. To change the rule for particular identifiers without a deploy, use [overrides](https://www.unkey.com/docs/api-management/ratelimiting/overrides.md). A monthly total on an API key is credits, not this window. See [Key and identity rate limits](https://www.unkey.com/docs/api-management/ratelimiting/key-and-identity-limits.md).

```typescript theme={"system"}
import { Unkey } from "@unkey/api";

const unkey = new Unkey({ rootKey: process.env.UNKEY_ROOT_KEY });

export async function handler(request: Request) {
  const userId = request.headers.get("x-user-id") ?? "anonymous";
  const { data } = await unkey.ratelimit.limit({
    namespace: "api.requests",
    identifier: userId,
    limit: 100,
    duration: 60_000,
  });

  if (!data.success) {
    const retryAfter = Math.max(1, Math.ceil((data.reset - Date.now()) / 1000));
    return new Response("Too many requests", {
      status: 429,
      headers: { "Retry-After": String(retryAfter) },
    });
  }

  return new Response("ok");
}
```

The endpoint returns HTTP 200 either way. `data.reset` is Unix milliseconds. `Retry-After` is in seconds, which is what [RFC 6585](https://www.rfc-editor.org/rfc/rfc6585#section-4) allows on a 429. Unkey doesn't set `Retry-After` or `X-RateLimit-*` on this endpoint. The full header list, including what the Compute gateway sends, is on [Rate limiting](https://www.unkey.com/docs/api-management/ratelimiting/overview.md#what-a-limited-request-looks-like).

> [!NOTE]
>
> Create a root key with the permissions listed on this page under **Root Keys** in the dashboard sidebar. CLI commands can instead use a session from [unkey login](https://www.unkey.com/docs/platform/cli/login.md) with the required permissions. See [Permission reference](https://www.unkey.com/docs/platform/root-keys/permissions-legacy.md) for every permission.

The root key needs `ratelimit.*.limit` or `ratelimit.<namespace_id>.limit` for every namespace checked. The first call with a new namespace name creates it, which also needs `ratelimit.*.create_namespace`.

## Namespaces

A namespace names what you're limiting, such as `email.send` or `api.requests`. Identifiers are counted separately in each namespace. Refer to a namespace by name (1 to 512 characters, case-sensitive) or ID (`rlns_...`). A new name is created on first use. Rename or delete namespaces in the dashboard under **Ratelimit**. A check against a deleted namespace fails with HTTP 410 `err:unkey:data:ratelimit_namespace_gone`.

## ratelimit.limit

**namespace** `string` *required*

Namespace name or ID, 1 to 512 characters.

**identifier** `string` *required*

Who or what you're counting, 1 to 512 characters: a user ID, IP address, tenant, or any stable string.

**limit** `integer` *required*

Maximum tokens per window, 1 or more. A matching override replaces it.

**duration** `integer` *required*

Window length in milliseconds, 1000 (one second) to 2592000000 (30 days). A matching override replaces it.

**cost** `integer` (default: 1)

Tokens this request spends, 0 or more. 0 checks without counting.

```bash theme={"system"}
curl -X POST https://api.unkey.com/v2/ratelimit.limit \
  -H "Authorization: Bearer $UNKEY_ROOT_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "namespace": "api.requests",
    "identifier": "user_123",
    "limit": 100,
    "duration": 60000,
    "cost": 5
  }'
```

### Response

**success** `boolean` *required*

Whether the request fit within the limit. The endpoint returns HTTP 200 either way, so read this field.

**limit** `integer` *required*

The limit that applied, from the request or from a matching override.

**remaining** `integer` *required*

Tokens left in the current window, as a close estimate. 0 on denial.

**reset** `integer` *required*

Unix milliseconds when the current window ends.

**overrideId** `string`

The override that was applied, when one matched.

```json theme={"system"}
{
  "meta": { "requestId": "req_..." },
  "data": { "success": true, "limit": 100, "remaining": 95, "reset": 1704067260000 }
}
```

Every check is recorded in rate limit analytics and writes a `ratelimit.limit` audit event. To keep a `ratelimit.limit` call out of analytics and your API request logs, send the header `X-Unkey-Metrics: disabled`. `ratelimit.multiLimit` ignores this header.

## ratelimit.multiLimit

Send an array of 1 to 100 objects with the same fields as `ratelimit.limit`. Use it when one action must pass several limits, for example a per-user and a per-organization limit, or a request count and a token budget.

Each check must have a different combination of namespace, identifier and duration. A repeated combination returns a 400 error with `invalid_input` before any namespace is created.

```bash theme={"system"}
curl -X POST https://api.unkey.com/v2/ratelimit.multiLimit \
  -H "Authorization: Bearer $UNKEY_ROOT_KEY" \
  -H "Content-Type: application/json" \
  -d '[
    { "namespace": "api.requests", "identifier": "user_123", "limit": 100, "duration": 60000 },
    { "namespace": "api.requests", "identifier": "org_acme", "limit": 1000, "duration": 60000 },
    { "namespace": "llm.tokens", "identifier": "user_123", "limit": 50000, "duration": 3600000, "cost": 1200 }
  ]'
```

If any check fails, none of them count. A request that passes counts against every limit. Overrides apply per check. A deleted namespace in any check fails the whole call with `err:unkey:data:ratelimit_namespace_gone`.

### Response

**passed** `boolean` *required*

`true` only when every check passed.

**limits** `object[]` *required*

One result per check, in request order, each with `namespace`, `identifier`, `passed`, `limit`, `remaining`, `reset`, and `overrideId`.

```json theme={"system"}
{
  "meta": { "requestId": "req_..." },
  "data": {
    "passed": false,
    "limits": [
      { "namespace": "api.requests", "identifier": "user_123", "passed": true, "limit": 100, "remaining": 99, "reset": 1704067260000 },
      { "namespace": "api.requests", "identifier": "org_acme", "passed": true, "limit": 1000, "remaining": 999, "reset": 1704067260000 },
      { "namespace": "llm.tokens", "identifier": "user_123", "passed": false, "limit": 50000, "remaining": 0, "reset": 1704070800000 }
    ]
  }
}
```

Nothing was counted, so `remaining` on the passing checks doesn't include this request.

## Choosing limits

* **Pick the window for the job.** Short windows, such as 20 per 10 seconds, stop bursts. Longer windows, such as 1,000 per hour, work as quotas. Windows of a minute or more are more accurate across regions.
* **Use `cost` for expensive operations** instead of a second namespace.
* **Keep identifiers stable.** An identifier with a timestamp or request ID in it is never seen twice, so it limits nothing.
* **Send plan limits per call.** To raise limits when a user upgrades, send the new `limit` with the same identifier and `duration`. Usage already counted in the window carries over. See [Change a limit mid-window](https://www.unkey.com/docs/api-management/ratelimiting/how-it-works.md#change-a-limit-mid-window).
* **Use an [override](https://www.unkey.com/docs/api-management/ratelimiting/overrides.md)** when one customer needs a different number, instead of a code path.


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