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

# Rate limiting with Unkey

> Unkey rate limits your API per customer, key, endpoint, or IP, and Compute limits it at the gateway.

Per customer, Unkey counts on an identity, so extra keys don't add budget.

You can also limit per key, per endpoint with a named limit or a `cost`, and per IP with `ratelimit.limit`.

Monthly quotas are separate, as credits on the key.

On Compute, a gateway policy applies these limits before the request reaches your API.

## Which one do I use

Use the row that matches what you want to count.

| You want to limit | What Unkey uses | Read more |
| - | - | - |
| Per customer | A rate limit on the identity, shared by every key with that `externalId` | [Shared rate limits](https://www.unkey.com/docs/api-management/identities/shared-rate-limits.md) |
| Per key | A named rate limit on the key, checked during `keys.verifyKey` | [Key and identity rate limits](https://www.unkey.com/docs/api-management/ratelimiting/key-and-identity-limits.md) |
| Per endpoint | A named limit the route opts into, or a `cost` on that call. With no key, one namespace per route on `ratelimit.limit` | [Per-endpoint rate limits](https://www.unkey.com/docs/api-management/cookbook/endpoint-rate-limit.md) |
| Per IP | The IP as the identifier on `ratelimit.limit`. On Compute, a gateway policy can count by remote IP | [ratelimit.limit](https://www.unkey.com/docs/api-management/ratelimiting/limit-and-multi-limit.md), [Rate limit policy](https://www.unkey.com/docs/compute/gateway/rate-limiting.md) |
| Monthly quota | Credits on the key, with `credits.refill.interval` set to `monthly` | [Credits and refill](https://www.unkey.com/docs/api-management/keys/credits-and-refill.md) |

## Limit per customer

Create the identity with the shared limit, then create each key with the same `externalId`. `keys.verifyKey` counts all of those keys together. The client is `@unkey/api` 2.5.1.

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

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

await unkey.identities.createIdentity({
  externalId: "cus_acme",
  ratelimits: [
    { name: "requests", limit: 100, duration: 60000, autoApply: true },
  ],
});

await unkey.keys.createKey({ apiId: "api_...", externalId: "cus_acme" });

export async function handler(key: string) {
  const { data } = await unkey.keys.verifyKey({ key });

  if (data.valid) {
    return new Response("ok");
  }

  if (data.code === "RATE_LIMITED") {
    return new Response("Too many requests", { status: 429 });
  }

  return new Response("Unauthorized", { status: 401 });
}
```

To override that customer's limit, call `identities.updateIdentity` with `identity` set to the same `externalId` and a new `ratelimits` array. The array replaces the whole list, so send every limit the customer should keep. See [Per-user rate limits](https://www.unkey.com/docs/api-management/cookbook/per-user-rate-limit.md).

Unkey enforces per-user and per-customer rate limits, and a monthly request quota, on an API you host yourself. You don't run Redis or any other counter store. Attach both to an API key, or call `ratelimit.limit` with a user id, a customer id, or any other stable string.

A rate limit is a sliding window, such as 100 requests per minute. A monthly quota is credits on the key: set `credits.refill.interval` to `monthly`, and each successful `keys.verifyKey` spends from that balance. Credits are an exact total. Rate limit counts are close, and they can run a little high when traffic is split across regions. See [Credits and refill](https://www.unkey.com/docs/api-management/keys/credits-and-refill.md).

## Add a per-key limit

Create the key with a per-minute limit and a monthly credit refill, then verify it on each request. This limit counts that key alone. `externalId` still ties the key to one customer.

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

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

await unkey.keys.createKey({
  apiId: "api_...",
  externalId: "cus_acme",
  credits: {
    remaining: 10000,
    refill: { interval: "monthly", amount: 10000, refillDay: 1 },
  },
  ratelimits: [
    { name: "requests", limit: 100, duration: 60000, autoApply: true },
  ],
});

export async function handler(request: Request) {
  const header = request.headers.get("authorization") ?? "";
  const key = header.startsWith("Bearer ") ? header.slice("Bearer ".length) : header;
  const { data } = await unkey.keys.verifyKey({ key });

  if (data.valid) {
    return new Response("ok");
  }

  if (data.code === "RATE_LIMITED") {
    const resetMs = data.ratelimits?.find((limit) => limit.exceeded)?.reset ?? Date.now();
    const retryAfter = Math.max(1, Math.ceil((resetMs - Date.now()) / 1000));
    return new Response("Too many requests", {
      status: 429,
      headers: { "Retry-After": String(retryAfter) },
    });
  }

  if (data.code === "USAGE_EXCEEDED") {
    return new Response("Monthly quota exceeded", { status: 429 });
  }

  return new Response("Unauthorized", { status: 401 });
}
```

`duration` is the window in milliseconds. `autoApply: true` checks that limit on every verification. The monthly refill replaces the balance on `refillDay` at 00:00 UTC. It doesn't add to what's left.

For an endpoint with no API key, call `ratelimit.limit` with your own identifier instead. The same pattern is on [ratelimit.limit and multiLimit](https://www.unkey.com/docs/api-management/ratelimiting/limit-and-multi-limit.md).

## What a limited request looks like

`keys.verifyKey` and `ratelimit.limit` return HTTP 200 when your user is over their limit. Read the body. `keys.verifyKey` sets `data.valid` to `false` and `data.code` to `RATE_LIMITED` (or `USAGE_EXCEEDED` when credits run out). Each checked limit is in `data.ratelimits`, with `limit`, `remaining`, `reset`, and `exceeded`. `ratelimit.limit` sets `data.success` to `false` and puts `limit`, `remaining`, and `reset` on `data`. `reset` is Unix milliseconds, when the current window ends.

Your server is the one that returns `429 Too Many Requests` to the caller. [RFC 6585](https://www.rfc-editor.org/rfc/rfc6585#section-4) defines that status and says the response may include `Retry-After`, a number of seconds to wait. Set it from `reset`, and use at least 1 second. Unkey doesn't send `Retry-After` or `X-RateLimit-*` on these two endpoints for your user's limit, so copy `limit`, `remaining`, and `reset` onto your own response if you want those headers. `X-RateLimit-Reset` on the Compute gateway is Unix seconds, so divide `reset` by 1000 if you want to match it.

If the API runs on Compute, the gateway returns 429 itself. The response has `Retry-After` (seconds, never under 1), `X-RateLimit-Limit`, `X-RateLimit-Remaining`, and `X-RateLimit-Reset` (Unix seconds). See [rate\_limited](https://www.unkey.com/docs/errors/frontline/client/rate_limited.md).

Your server's own calls to `api.unkey.com` have a separate workspace limit. If you exceed it, Unkey returns HTTP 429 with `RateLimit-Limit`, `RateLimit-Remaining`, `RateLimit-Reset` (seconds until the window ends), and `Retry-After`. Those headers describe your workspace's budget for the Unkey API, not your users' limits.

Rate limiting (Three Unkey features share this name: the standalone ratelimit API and key or identity limits (this section), and the Compute gateway rate limit policy. See the glossary.) in API Management has two forms. A standalone API takes any identifier you choose. Limits on a key or identity are checked when the key is verified. The Compute gateway's rate limit policy is separate. See the [glossary](https://www.unkey.com/docs/platform/glossary.md).

## Choose a rate limit

| | Standalone `ratelimit.limit` | Key and identity rate limits |
| - | - | - |
| What you limit | Any string: a user ID, an IP address, an email domain, a tenant | A key, or every key of an identity together |
| Where it runs | Its own endpoint, whenever you call it | Inside `keys.verifyKey`, as one of its checks |
| Configuration | You send the limit and duration with every call | Named limits stored on the key or identity |
| Per-caller exceptions | Overrides on an identifier or wildcard pattern | Different limits per key or identity |
| Failure signal | `success: false` in the response | `code: RATE_LIMITED` in the verification |

Use the standalone API when the endpoint has no key (sign-up, password reset) or when you want to limit something other than the key holder. Use key and identity limits when the request already carries a key, so the check happens during the verification you already make.

Both count requests the same way. See [How rate limiting works](https://www.unkey.com/docs/api-management/ratelimiting/how-it-works.md).

## A first rate limit

> [!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`, plus `ratelimit.*.create_namespace` the first time a namespace name is used.

```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": "email.send",
    "identifier": "user_123",
    "limit": 10,
    "duration": 60000
  }'
```

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

The namespace `email.send` names what you're limiting. The identifier `user_123` is who's being counted. Each user gets ten calls per minute, and the eleventh returns `success: false` until the window moves on. In the TypeScript SDK, the same call is `unkey.ratelimit.limit({ namespace, identifier, limit, duration })`.

## Next steps

> [card] [How rate limiting works](https://www.unkey.com/docs/api-management/ratelimiting/how-it-works.md)
>
> Sliding windows, regional counters, cross-region convergence, and what `remaining` and `reset` mean.

> [card] [ratelimit.limit and multiLimit](https://www.unkey.com/docs/api-management/ratelimiting/limit-and-multi-limit.md)
>
> Request and response fields, bounds, namespaces, cost, and atomic multi-limit checks.

> [card] [Rate limit overrides](https://www.unkey.com/docs/api-management/ratelimiting/overrides.md)
>
> Give one identifier or a wildcard pattern a different limit without changing code.

> [card] [Key and identity rate limits](https://www.unkey.com/docs/api-management/ratelimiting/key-and-identity-limits.md)
>
> Named limits on keys and identities, auto-apply, cost, and inline limits at verification.


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