# Quotas, Limits and Costs

URL: https://www.elchi.io/docs/ai-gateway/quotas-limits-and-costs

> Consumer quotas on requests, tokens and cost, how and when they count, the price table and how cost is computed, and the gateway and global token limits with CEL.

Three different things on this page:

| What | Set where | Does it refuse requests? |
|---|---|---|
| **Consumer quotas** — requests, tokens and cost per minute, day, month | a consumer's page, **Quota** | **Yes**: 429 `quota_exceeded` |
| **Prices** — what a model costs per million tokens | **Providers** tab, **Prices** | Indirectly: usage cost, cost quotas, and 403 `model_not_priced` |
| **Token limits** — counters (token types or a CEL expression) per request | **Providers** tab, **Global token limits**; a gateway's **Token limits** | **No**: the value is written to Envoy request metadata for your own rate limit or access log |

Consumer quotas apply only on gateways that **require a key** (a request on a keyless gateway belongs to no consumer).

## Consumer quotas

Open the consumer (**Consumers** tab → the consumer), fill the **Quota** section, **Save**.

| Field (UI) | API field | Counts |
|---|---|---|
| **Tokens per day** | `tokensPerDay` | input + output tokens since 00:00 UTC |
| **Tokens per month** | `tokensPerMonth` | input + output tokens since the 1st, 00:00 UTC |
| **Requests per minute** | `requestsPerMinute` | requests admitted in the last 60 seconds, **on each edge** |
| **Requests per day** | `requestsPerDay` | requests since 00:00 UTC |
| **Cost per day (USD)** | `costPerDay` | the day's tokens at the current prices |
| **Cost per month (USD)** | `costPerMonth` | the month's tokens at the current prices |
| **Tool calls per minute**, **Tool calls per day** | `mcpCallsPerMinute`, `mcpCallsPerDay` | MCP `tools/call` messages: [MCP grants and quotas](https://www.elchi.io/docs/ai-gateway/mcp/grants-and-quotas) |

- Empty or `0` is **no limit**. To stop a consumer, turn on **Disabled** instead.
- Days and months are UTC calendar periods. Cached and reasoning tokens are parts of the input and output counts, not extra.
- Counts go up to 2^53−1 (what a browser edits exactly); cost quotas up to 1e12.

### When a request is counted

Each request on a keyed gateway is checked twice by the edge's `elchi-ai-gateway` (Envoy's ext_authz):

1. **Key phase**, before the engine reads the body: the key, the consumer's gateways, and whether a quota is **already** used up. A consumer over a quota gets 429 here on every path but `/mcp`, `/v1/models` included. Nothing is counted.
2. **Model phase**, once the model is known: the consumer's providers and models, a price when it has a cost quota, the sensitive-data scan, and then the quotas again — **checking and counting the request in one step**, so concurrent requests at a limit cannot all pass.

A request refused before this last step (403 for its model, a model the gateway does not serve, a sensitive-data block) **uses no quota**.

Request quotas are exact. Token and cost quotas lag:

- Tokens are known when a response completes. The edge reads them from the engine every **30 seconds**, so the request that crosses a token or cost quota still completes, and requests admitted until the next read can pass it too.
- Other edges' use arrives through ClickHouse: each edge re-reads the day's totals **every minute** (`--authz-refresh-interval`) and the month's closed days every 15 minutes.

### Shared or edge-local totals

| Edge has a ClickHouse DSN | Day and month totals |
|---|---|
| **Yes** | **Shared**: every edge's use counts (from the usage table, which keeps at least 32 days). Each edge's `--instance-id` (default `<hostname>-ai-gateway`) must be unique, or two edges drop each other's use from their totals. |
| **No** | **Edge-local**: each edge counts only what it saw since it started. N edges allow N times a quota, and a restart resets the count. The service warns at start. |

`/configz` on the edge says which: `authz.quota_totals` is `shared` (with `last_refresh` and `last_refresh_error`) or `edge-local`. Failed refreshes are counted in `elchi_ai_gateway_authz_quota_refresh_failures_total`. **Requests per minute** are always counted per edge.

### The 429 answer

The first quota found used up is named, checked in this order: requests per minute, requests per day, tokens per day, tokens per month, cost per day, cost per month.

```
HTTP/1.1 429
content-type: application/json
retry-after: 37

{"error":{"message":"consumer billing used its quota of 60 requests per minute; it resets at 2026-12-05T10:31:07Z","type":"rate_limit_error","code":"quota_exceeded"}}
```

- `retry-after` is the seconds until the quota resets (at least 1): the oldest request of the minute turning 60 seconds old, the next 00:00 UTC, or the 1st of next month.
- The quota is named as `60 requests per minute`, `5000 requests per day`, `2000000 tokens per day`, `50000000 tokens per month`, `10.00 per day`, `200.00 per month`.

### model_not_priced (403)

A consumer **with a cost quota** may use a model only when **every provider that may serve it has a price** for the name it is asked for. Otherwise:

```json
{"error":{"message":"consumer billing has a cost quota and model gpt-4o has no price at provider openai (asked for gpt-4o)","type":"permission_error","code":"model_not_priced"}}
```

This also applies when the price table is empty: a consumer with a cost quota is then refused every model. When the table has prices, the configuration notes list each unpriced model with the consumers it is refused to (`model "x" (provider "y") of gateway "g" has no price: N consumer(s) with a cost quota (…) are refused it (403)`).

## Prices

Open **Providers** and scroll to **Prices** (USD per million tokens). **Add price**, fill the row, **Save prices**.

| Column | API field | Meaning |
|---|---|---|
| **Provider** | `provider` | One provider, or **Any provider** (empty). |
| **Model** | `model` | The model name **as the provider is asked for it** (see below). |
| **Input / M** | `inputPerMTok` | Required; 0 for free. |
| **Output / M** | `outputPerMTok` | Required; 0 for free. |
| **Cached input / M** | `cachedInputPerMTok` | Optional; empty charges cached input at the input rate. |

Rules:

- A provider's own price wins over the model's **Any provider** price.
- One price per provider and model; prices up to 1e6 per million tokens; no negative values.
- The name to price is the one usage is recorded under: the multi-provider entry's **Model at the provider** when it has one, else the provider's **Model override**, else the client's model name. For a model served by several providers, price each entry as `{provider, model: <its model at the provider>}`.

### How cost is computed

```
cost = ( (input − cached_input) × inputPerMTok
         + cached_input × (cachedInputPerMTok, or inputPerMTok when unset)
         + output × outputPerMTok ) / 1 000 000
```

- Cached input tokens are part of the input count.
- A cache **write** (Anthropic's cache creation) is input to the engine and costs the input rate; the provider's own write premium is not modelled.
- Cost is never stored: it is always the tokens at the **current** prices. A price change reprices the whole period, both in quotas and in usage.
- Tokens of models without a price are reported separately as **unpriced tokens** (the consumer's page: `N tokens this month are of models without a price: they are not in the cost.`; the Usage tab); the cost is then a lower bound.

### REST

Prices and global limits are part of the providers document: `PUT /api/v3/ai-gateway/providers` with the whole document ([Providers](https://www.elchi.io/docs/ai-gateway/providers#rest-api)).

```json
"pricing": [
  {"model": "gpt-4o-mini", "inputPerMTok": 0.15, "outputPerMTok": 0.6, "cachedInputPerMTok": 0.075},
  {"provider": "azure", "model": "gpt-4o", "inputPerMTok": 2.5, "outputPerMTok": 10}
]
```

## Token limits (CEL) {#token-limits-cel}

A token limit is a **counter**, not a quota: for each request, at the end of the response, the engine computes a number and writes it into Envoy's dynamic metadata (namespace `io.envoy.ai_gateway`, key = the limit's **metadata key**). Use it in an Envoy rate limit or access log you configure. elchi does not refuse requests on these values; consumer quotas are what refuse.

- **Global token limits** (**Providers** tab, **Save limits**) are computed for every gateway's requests.
- A gateway's **Token limits** are computed only for that gateway's requests. A gateway key equal to a global key overrides it for that gateway.

| Field | Meaning |
|---|---|
| **Metadata key** | Required; unique within its list. |
| **Type** | `InputToken`, `OutputToken`, `TotalToken`, `CachedInputToken`, `CacheCreationInputToken`, `ReasoningToken`, or `CEL`. |
| **CEL** | Required exactly when the type is `CEL`. |

### CEL expressions

Variables:

| Variable | Type |
|---|---|
| `model`, `backend`, `route_name` | string |
| `input_tokens`, `cached_input_tokens`, `cache_creation_input_tokens`, `output_tokens`, `total_tokens`, `reasoning_tokens` | **uint** |

The result must be an integer that is not negative. The token variables are unsigned, and CEL does not mix signed and unsigned numbers, so **integer literals need the `u` suffix**:

| Expression | Result |
|---|---|
| `input_tokens + output_tokens * 4u` | accepted |
| `output_tokens * 4` | refused: `cannot compile CEL expression …` (int and uint mixed) |
| `model == "gpt-4o" ? total_tokens * 2u : total_tokens` | accepted |

The save compiles and evaluates every expression the way the engine does when it loads its configuration (the engine rejects the **whole** configuration on one bad expression), so a bad one is refused at save with **400**, never on the edge.

```json
"limits": [
  {"metadataKey": "total", "type": "TotalToken"},
  {"metadataKey": "weighted", "type": "CEL", "cel": "input_tokens + output_tokens * 4u"}
]
```

## Verify

- A consumer's page, **Use**: today's and this month's requests, tokens and cost against each limit; the **Consumers** list's **Quota used** bar.
- Send requests past **Requests per minute** and expect 429 with `retry-after`.
- Unexpected 403 `model_not_priced`: add a price for that model on every provider that serves it (under the name it is asked for).
- Token quota passed by more than expected: tokens are counted up to 30 s after a response, and other edges' up to a minute later; edges without ClickHouse count separately.
- Error reference: [Error codes](https://www.elchi.io/docs/ai-gateway/reference/error-codes).
