Claude apps gateway spend limits
--- a/claude-apps-gateway-spend-limits.md
+++ b/claude-apps-gateway-spend-limits.md
@@ -48,7 +48,7 @@
3. List price for the [`models[].id`](</docs/en/claude-apps-gateway-config#models>) you mapped to that upstream ID, for upstream strings that carry no model name, such as an Amazon Bedrock application-inference-profile ARN or a Microsoft Foundry deployment name. Requires v2.1.218 or later.
4. The unknown-model tier of $5/$25 per million input/output tokens, so an ID the meter can’t place is never free. The gateway warns at boot and once per ID at runtime when it uses this tier.
-Whichever rate applies, the meter then multiplies the amount by [`pricing.multiplier`](</docs/en/claude-apps-gateway-config#pricing>), default `1`. Requires a gateway server running Claude Code v2.1.227 or later. Client aborts are billed too. When a stream ends without the upstream’s final usage frame, the meter bills a floor estimate of about four characters per output token for the text already sent to the client, so aborting requests early doesn’t evade a cap.
+Whichever rate applies, the meter then multiplies the amount by [`pricing.multiplier`](</docs/en/claude-apps-gateway-config#pricing>), default `1`. Requires a gateway server running Claude Code v2.1.227 or later. When a stream ends without the upstream’s final usage frame, the meter bills a floor estimate of about four characters per output token for text already sent to the client.
#### Long-prompt rates
Show diff (153 lines)
--- a/claude-apps-gateway-spend-limits.md
+++ b/claude-apps-gateway-spend-limits.md
@@ -1,10 +1,6 @@
Spend limits cap how much each developer can spend through your [Claude apps gateway](</docs/en/claude-apps-gateway>) in a given day, week, or month. When a developer passes their cap, the gateway returns `429` on their following requests until an admin raises the cap, or until the cap resets if it’s above $0. Use spend limits to give each developer, group, or the whole organization a ceiling on a credential everyone shares. By default, a Claude apps gateway forwards all inference through one shared upstream credential, so your provider’s bill attributes everything to that credential, not to individual developers. On Amazon Bedrock, [per-developer AWS cost attribution](</docs/en/claude-apps-gateway-config#per-developer-aws-cost-attribution>) changes this. Without per-developer limits, one runaway agent fleet can spend the organization’s entire commitment. Spend limits are the gateway’s per-developer view and circuit breaker on top of that shared bill.
-##
-
-
-
-Set a cap
+## Set a cap
With the [`admin:`](</docs/en/claude-apps-gateway-config#admin>) block configured in `gateway.yaml`, the gateway serves an admin API at `/v1/organizations/spend_limits` and enforces caps live on every inference request. Caps themselves are set through that API, not in `gateway.yaml`; each `POST /v1/organizations/spend_limits` request creates or replaces one cap from `{scope, amount, period}`. The API mirrors the wire shapes of Anthropic’s public [Admin API](<https://platform.claude.com/docs/en/manage-claude/admin-api>) spend-limits endpoints, so an HTTP client written against that contract can target the gateway by changing its base URL. This request sets an org-wide default of $500 per month for every developer:
@@ -28,22 +24,14 @@
A group or organization cap is a per-seat default that each member inherits, not a shared pool. Per period, a developer’s effective cap resolves in this order: a per-user override, then the most restrictive of their group caps, then the org default, then unlimited. [`admin.group_limit_mode: max`](</docs/en/claude-apps-gateway-config#admin>) flips the multi-group tie-break to least-restrictive instead.
-###
-
-
-
-Authenticate to the admin API
+### Authenticate to the admin API
Send one of:
* An `x-api-key` header matching a key in [`admin.write_keys`](</docs/en/claude-apps-gateway-config#admin>) for full access, or `admin.read_keys` for `GET`-only access. Each key carries an `id` that appears in the audit log as `admin-key:<id>`, so give Terraform, CI, and each automation its own.
* A gateway bearer token whose `groups` claim includes one of [`admin.admin_groups`](</docs/en/claude-apps-gateway-config#admin>). This is full access and audits as `oidc:<sub>`, so prefer it for human admins.
-##
-
-
-
-How enforcement works
+## How enforcement works
On each `/v1/messages` request, the gateway looks up the developer’s caps and period-to-date spend in one Postgres query. A developer over any cap gets a `429` with `error.type: billing_error` and header `x-should-retry: false`. For a cap above `"0"`, the message gives the UTC date that cap resets. If you set [`admin.blocked_message`](</docs/en/claude-apps-gateway-config#admin>), the gateway appends it, as in this example:
@@ -51,11 +39,7 @@
For a `"0"` cap, which a reset doesn’t lift, the message has no date. When a developer exceeds several caps at once, the message describes the cap that resets last. The response also carries a `retry-after` header with the seconds until that cap’s period ends. Before v2.1.319 on the gateway server, the message named the period and reset time, such as `spend limit reached (daily; resets 2026-08-08 00:00 UTC)`. Before v2.1.225, the message was `spend limit reached` with no period, reset time, or `retry-after` header. On v2.1.227 or later, the protocol reference at `<public_url>/protocol` also lists the exact usage-limit response headers and `429` body. Caps reset on UTC calendar boundaries: daily at 00:00 UTC, weekly on Monday, and monthly on the first. The gateway never blocks `/v1/messages/count_tokens`, because token counting is free.
-###
-
-
-
-How requests are priced
+### How requests are priced
After each response, a usage meter reads the token counts and adds the cost to the daily, weekly, and monthly counters. It never touches the bytes sent to the client, so a metering failure can’t break a response. The amounts are USD estimates, a circuit breaker rather than an invoice; for billing, reconcile against your provider’s usage reporting. The meter picks each request’s rates in this order:
@@ -66,27 +50,15 @@
Whichever rate applies, the meter then multiplies the amount by [`pricing.multiplier`](</docs/en/claude-apps-gateway-config#pricing>), default `1`. Requires a gateway server running Claude Code v2.1.227 or later. Client aborts are billed too. When a stream ends without the upstream’s final usage frame, the meter bills a floor estimate of about four characters per output token for the text already sent to the client, so aborting requests early doesn’t evade a cap.
-####
-
-
-
-Long-prompt rates
+#### Long-prompt rates
The list price for [Claude Haiku 5.5](<https://platform.claude.com/docs/en/models/haiku-5-5/overview>) has a [higher rate for prompts over a token threshold](</docs/en/model-config#haiku-5-5-context-window-and-pricing>). When Haiku 5.5 serves a request whose prompt exceeds the threshold, a gateway server running Claude Code v2.1.293 or later prices the whole request at that rate. The meter counts input tokens, cache reads, and cache writes toward that threshold. If one of your `pricing.overrides` rows matches the request, that row’s rates apply at any prompt length.
-###
-
-
-
-Postgres availability
+### Postgres availability
The pre-check queries Postgres with a two-second timeout. If the store is unreachable or times out, enforcement fails open by default: the request proceeds, the gateway logs a warning, and the response carries no `anthropic-ratelimit-unified-*` headers. Set [`enforcement.fail_closed_on_error: true`](</docs/en/claude-apps-gateway-config#enforcement>) to fail closed instead, which returns the same `429 billing_error` but with the message `spend limit unavailable` and no period, reset time, or `retry-after` header. Fail-open keeps a store outage from becoming an inference outage; fail-closed guarantees no unmetered spend. Fail-open only helps while your load balancer or orchestrator still routes traffic to the gateway. See [Outage behavior](</docs/en/claude-apps-gateway-deploy#outage-behavior>) for `store.readiness_grace_seconds`, which keeps replicas passing their readiness check through a short outage.
-###
-
-
-
-Usage warnings in Claude Code
+### Usage warnings in Claude Code
Claude Code warns a developer as they approach their cap: once utilization passes 75%, and again past 95% of their most-consumed cap. When the gateway blocks a request, Claude Code shows the gateway’s `429` message as is, including your `admin.blocked_message`. It also shows the cap in `/usage` and passes it to the developer’s [status line](</docs/en/statusline#spend-limit-fields>) script. Each display needs a minimum Claude Code version on the developer’s machine and on the gateway server:
@@ -99,11 +71,7 @@
The warnings and the percentage come from the `anthropic-ratelimit-unified-*` headers, which the gateway adds to each successful `/v1/messages` response for a developer who has a cap. The headers always describe the developer’s own cap: the gateway strips the upstream provider’s rate-limit headers, which describe your shared quota, and never forwards them. The spend a developer sees is the gateway’s own estimate, the same figure it enforces the cap with. It isn’t an amount from your provider’s bill. Claude Code reads the dollar amounts with a separate request to the gateway, which it sends even if you set `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` on developers’ machines. Before v2.1.295, Claude Code skipped that request when the variable was set, and `/usage` and the status line showed the percentage and the reset date, with no dollar amounts.
-##
-
-
-
-Admin API reference
+## Admin API reference
The endpoints below are served under `/v1/organizations/spend_limits`.
@@ -126,11 +94,7 @@
Every mutation writes a before/after row to `admin_audit` in the same transaction, attributed to `admin-key:<id>` or `oidc:<sub>`. The gateway serves the spend-limits endpoints only. Other Admin API surfaces, such as the `spend_limit_increase_requests` queue, aren’t part of the gateway’s admin API.
-###
-
-
-
-`/effective`
+### `/effective`
`GET /v1/organizations/spend_limits/effective` returns Anthropic’s `SpendSummary` schema: each row is a principal for a period, with the resolved cap, period-to-date spend, and an `actor` object. Gateway-specific differences:
@@ -151,27 +115,15 @@
`q=` and `user_ids[]=` ride GET query strings, so any fronting proxy or load balancer captures them in its access logs. If your PII log policy is strict, scrub these parameters there.
-###
-
-
-
-`/audit`
+### `/audit`
Returns the spend-limit mutation trail: who changed which cap, with before/after snapshots, newest-first. `has_more` is exact. This endpoint follows the local Admin API conventions rather than a first-party wire shape.
-###
-
-
-
-Pagination
+### Pagination
The raw list pages by `after_id` and `before_id`, which are mutually exclusive `spl_…` IDs; results are ordered by creation and `has_more` reflects the traversal direction. `/effective` pages by the opaque `next_page` token passed back as `?page=`, with principals ordered ascending so pages stay stable while spend is being recorded. `limit` is 1–1000, default 20, on both. `/audit` pages by `after_id`, the numeric `id` of the last event on the previous page, and its `limit` defaults to 100.
-##
-
-
-
-Data lifecycle
+## Data lifecycle
The gateway holds four spend-related tables; an hourly sweep enforces the retention windows:
@@ -184,11 +136,7 @@
When a developer leaves, delete any per-user cap via `DELETE /v1/organizations/spend_limits/{id}`; their spend and identity rows age out on the retention windows above. To erase one person immediately, for offboarding or a data subject access request (DSAR), run `DELETE FROM principal_emails WHERE principal = '<sub>'` directly against the gateway database. That removes the only table holding their email, name, and groups. The `spend` and `admin_audit` rows reference the pseudonymous OIDC `sub` only and age out on their own windows.
-##
-
-
-
-Related
+## Related
* [`admin` and `enforcement` configuration](</docs/en/claude-apps-gateway-config#admin>): enabling the admin API and tuning retention
* [Deployment guide](</docs/en/claude-apps-gateway-deploy#postgres>): Postgres schema and backup guidance
--- a/claude-apps-gateway-spend-limits.md
+++ b/claude-apps-gateway-spend-limits.md
@@ -64,7 +64,7 @@
3. List price for the [`models[].id`](</docs/en/claude-apps-gateway-config#models>) you mapped to that upstream ID, for upstream strings that carry no model name, such as an Amazon Bedrock application-inference-profile ARN or a Microsoft Foundry deployment name. Requires v2.1.218 or later.
4. The unknown-model tier of $5/$25 per million input/output tokens, so an ID the meter can’t place is never free. The gateway warns at boot and once per ID at runtime when it uses this tier.
-Whichever rate applies, the meter then multiplies the amount by [`pricing.multiplier`](</docs/en/claude-apps-gateway-config#pricing>), default `1`. Client aborts are billed too. When a stream ends without the upstream’s final usage frame, the meter bills a floor estimate of about four characters per output token for the text already sent to the client, so aborting requests early doesn’t evade a cap.
+Whichever rate applies, the meter then multiplies the amount by [`pricing.multiplier`](</docs/en/claude-apps-gateway-config#pricing>), default `1`. Requires a gateway server running Claude Code v2.1.227 or later. Client aborts are billed too. When a stream ends without the upstream’s final usage frame, the meter bills a floor estimate of about four characters per output token for the text already sent to the client, so aborting requests early doesn’t evade a cap.
####
--- a/claude-apps-gateway-spend-limits.md
+++ b/claude-apps-gateway-spend-limits.md
@@ -1,4 +1,4 @@
-Spend limits cap how much each developer can spend through your [Claude apps gateway](</docs/en/claude-apps-gateway>) in a given day, week, or month. When a developer passes their cap, the gateway returns `429` on their next request and blocks them until the period resets or an admin raises the cap. Use spend limits to give each developer, group, or the whole organization a ceiling on a credential everyone shares. By default, a Claude apps gateway forwards all inference through one shared upstream credential, so your provider’s bill attributes everything to that credential, not to individual developers. On Amazon Bedrock, [per-developer AWS cost attribution](</docs/en/claude-apps-gateway-config#per-developer-aws-cost-attribution>) changes this. Without per-developer limits, one runaway agent fleet can spend the organization’s entire commitment. Spend limits are the gateway’s per-developer view and circuit breaker on top of that shared bill.
+Spend limits cap how much each developer can spend through your [Claude apps gateway](</docs/en/claude-apps-gateway>) in a given day, week, or month. When a developer passes their cap, the gateway returns `429` on their following requests until an admin raises the cap, or until the cap resets if it’s above $0. Use spend limits to give each developer, group, or the whole organization a ceiling on a credential everyone shares. By default, a Claude apps gateway forwards all inference through one shared upstream credential, so your provider’s bill attributes everything to that credential, not to individual developers. On Amazon Bedrock, [per-developer AWS cost attribution](</docs/en/claude-apps-gateway-config#per-developer-aws-cost-attribution>) changes this. Without per-developer limits, one runaway agent fleet can spend the organization’s entire commitment. Spend limits are the gateway’s per-developer view and circuit breaker on top of that shared bill.
##
@@ -45,7 +45,11 @@
How enforcement works
-On each `/v1/messages` request, the gateway looks up the developer’s caps and period-to-date spend in one Postgres query. A developer over any cap gets a `429` with `error.type: billing_error` and header `x-should-retry: false`. The message names the period and reset time, such as `spend limit reached (daily; resets 2026-08-08 00:00 UTC)`, followed by your [`admin.blocked_message`](</docs/en/claude-apps-gateway-config#admin>) if set. When a developer exceeds several caps at once, the message names the cap that resets last. The response also carries a `retry-after` header with the seconds remaining until that reset. Before v2.1.225 on the gateway server, the message was `spend limit reached` with no period, reset time, or `retry-after` header. On v2.1.227 or later, the protocol reference at `<public_url>/protocol` also lists the exact usage-limit response headers and `429` body. Caps reset on UTC calendar boundaries: daily at 00:00 UTC, weekly on Monday, and monthly on the first. The gateway never blocks `/v1/messages/count_tokens`, because token counting is free.
+On each `/v1/messages` request, the gateway looks up the developer’s caps and period-to-date spend in one Postgres query. A developer over any cap gets a `429` with `error.type: billing_error` and header `x-should-retry: false`. For a cap above `"0"`, the message gives the UTC date that cap resets. If you set [`admin.blocked_message`](</docs/en/claude-apps-gateway-config#admin>), the gateway appends it, as in this example:
+
+ spend limit reached · resets Dec 1 · request an increase at https://go.example.com/claude-limits
+
+For a `"0"` cap, which a reset doesn’t lift, the message has no date. When a developer exceeds several caps at once, the message describes the cap that resets last. The response also carries a `retry-after` header with the seconds until that cap’s period ends. Before v2.1.319 on the gateway server, the message named the period and reset time, such as `spend limit reached (daily; resets 2026-08-08 00:00 UTC)`. Before v2.1.225, the message was `spend limit reached` with no period, reset time, or `retry-after` header. On v2.1.227 or later, the protocol reference at `<public_url>/protocol` also lists the exact usage-limit response headers and `429` body. Caps reset on UTC calendar boundaries: daily at 00:00 UTC, weekly on Monday, and monthly on the first. The gateway never blocks `/v1/messages/count_tokens`, because token counting is free.
###
@@ -91,6 +95,7 @@
Usage warnings at 75% and 95%| v2.1.225 or later| v2.1.225 or later
A **Spend limit** bar in `/usage` with the percentage of their cap used and when it resets, and a `rate_limits.spend_limit` object in the status line input| v2.1.251 or later| v2.1.225 or later
Their estimated spend and the cap in US dollars in the **Spend limit** bar, such as “$271.40 / $500.00 spent this month”, and the same amounts plus the cap’s period in the status line input| v2.1.284 or later| v2.1.284 or later
+On a gateway with an [`admin:`](</docs/en/claude-apps-gateway-config#admin>) block, when no cap applies to them, their estimated spend under **Spend (UTC)** in `/usage`, such as “$13.06 today · $80.76 this week · $272.06 this month”| v2.1.319 or later| v2.1.319 or later
The warnings and the percentage come from the `anthropic-ratelimit-unified-*` headers, which the gateway adds to each successful `/v1/messages` response for a developer who has a cap. The headers always describe the developer’s own cap: the gateway strips the upstream provider’s rate-limit headers, which describe your shared quota, and never forwards them. The spend a developer sees is the gateway’s own estimate, the same figure it enforces the cap with. It isn’t an amount from your provider’s bill. Claude Code reads the dollar amounts with a separate request to the gateway, which it sends even if you set `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` on developers’ machines. Before v2.1.295, Claude Code skipped that request when the variable was set, and `/usage` and the status line showed the percentage and the reset date, with no dollar amounts.
--- a/claude-apps-gateway-spend-limits.md
+++ b/claude-apps-gateway-spend-limits.md
@@ -92,7 +92,7 @@
A **Spend limit** bar in `/usage` with the percentage of their cap used and when it resets, and a `rate_limits.spend_limit` object in the status line input| v2.1.251 or later| v2.1.225 or later
Their estimated spend and the cap in US dollars in the **Spend limit** bar, such as “$271.40 / $500.00 spent this month”, and the same amounts plus the cap’s period in the status line input| v2.1.284 or later| v2.1.284 or later
-The warnings and the percentage come from the `anthropic-ratelimit-unified-*` headers, which the gateway adds to each successful `/v1/messages` response for a developer who has a cap. The headers always describe the developer’s own cap: the gateway strips the upstream provider’s rate-limit headers, which describe your shared quota, and never forwards them. The spend a developer sees is the gateway’s own estimate, the same figure it enforces the cap with, and not an amount from your provider’s bill. Claude Code reads the dollar amounts with a separate request to the gateway. If you set `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` on developers’ machines, as [Compliance posture](</docs/en/claude-apps-gateway-deploy#compliance-posture>) suggests, Claude Code skips that request. With that variable set, or with a gateway server older than v2.1.284, the bar and the status line stay percentage-only.
+The warnings and the percentage come from the `anthropic-ratelimit-unified-*` headers, which the gateway adds to each successful `/v1/messages` response for a developer who has a cap. The headers always describe the developer’s own cap: the gateway strips the upstream provider’s rate-limit headers, which describe your shared quota, and never forwards them. The spend a developer sees is the gateway’s own estimate, the same figure it enforces the cap with. It isn’t an amount from your provider’s bill. Claude Code reads the dollar amounts with a separate request to the gateway, which it sends even if you set `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` on developers’ machines. Before v2.1.295, Claude Code skipped that request when the variable was set, and `/usage` and the status line showed the percentage and the reset date, with no dollar amounts.
##
--- a/claude-apps-gateway-spend-limits.md
+++ b/claude-apps-gateway-spend-limits.md
@@ -61,6 +61,14 @@
4. The unknown-model tier of $5/$25 per million input/output tokens, so an ID the meter can’t place is never free. The gateway warns at boot and once per ID at runtime when it uses this tier.
Whichever rate applies, the meter then multiplies the amount by [`pricing.multiplier`](</docs/en/claude-apps-gateway-config#pricing>), default `1`. Client aborts are billed too. When a stream ends without the upstream’s final usage frame, the meter bills a floor estimate of about four characters per output token for the text already sent to the client, so aborting requests early doesn’t evade a cap.
+
+####
+
+
+
+Long-prompt rates
+
+The list price for [Claude Haiku 5.5](<https://platform.claude.com/docs/en/models/haiku-5-5/overview>) has a [higher rate for prompts over a token threshold](</docs/en/model-config#haiku-5-5-context-window-and-pricing>). When Haiku 5.5 serves a request whose prompt exceeds the threshold, a gateway server running Claude Code v2.1.293 or later prices the whole request at that rate. The meter counts input tokens, cache reads, and cache writes toward that threshold. If one of your `pricing.overrides` rows matches the request, that row’s rates apply at any prompt length.
###
--- a/claude-apps-gateway-spend-limits.md
+++ b/claude-apps-gateway-spend-limits.md
@@ -76,12 +76,15 @@
Usage warnings in Claude Code
-Claude Code warns a developer as they approach their cap: once utilization passes 75%, and again past 95% of their most-consumed cap. When the gateway blocks a request, Claude Code shows the gateway’s `429` message as is, including your `admin.blocked_message`. The warning works off response headers:
+Claude Code warns a developer as they approach their cap: once utilization passes 75%, and again past 95% of their most-consumed cap. When the gateway blocks a request, Claude Code shows the gateway’s `429` message as is, including your `admin.blocked_message`. It also shows the cap in `/usage` and passes it to the developer’s [status line](</docs/en/statusline#spend-limit-fields>) script. Each display needs a minimum Claude Code version on the developer’s machine and on the gateway server:
- * With v2.1.225 or later on the gateway server, each successful `/v1/messages` response for a developer who has a cap carries their own cap utilization and reset time in the `anthropic-ratelimit-unified-*` headers.
- * With v2.1.225 or later on the developer’s machine as well, Claude Code reads the headers and shows the warning.
+What the developer sees| Developer’s machine| Gateway server
+---|---|---
+Usage warnings at 75% and 95%| v2.1.225 or later| v2.1.225 or later
+A **Spend limit** bar in `/usage` with the percentage of their cap used and when it resets, and a `rate_limits.spend_limit` object in the status line input| v2.1.251 or later| v2.1.225 or later
+Their estimated spend and the cap in US dollars in the **Spend limit** bar, such as “$271.40 / $500.00 spent this month”, and the same amounts plus the cap’s period in the status line input| v2.1.284 or later| v2.1.284 or later
-The headers always describe the developer’s own cap: the gateway strips the upstream provider’s rate-limit headers, which describe your shared quota, and never forwards them. With v2.1.251 or later on the developer’s machine, Claude Code also reads the same headers to show a **Spend limit** bar in `/usage`, with the percentage of their cap used and when it resets, and to add a `rate_limits.spend_limit` object to the [status line](</docs/en/statusline#rate-limit-usage>) input. Claude Code shows both as a percentage rather than a dollar amount, and needs nothing newer than v2.1.225 on the gateway server.
+The warnings and the percentage come from the `anthropic-ratelimit-unified-*` headers, which the gateway adds to each successful `/v1/messages` response for a developer who has a cap. The headers always describe the developer’s own cap: the gateway strips the upstream provider’s rate-limit headers, which describe your shared quota, and never forwards them. The spend a developer sees is the gateway’s own estimate, the same figure it enforces the cap with, and not an amount from your provider’s bill. Claude Code reads the dollar amounts with a separate request to the gateway. If you set `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` on developers’ machines, as [Compliance posture](</docs/en/claude-apps-gateway-deploy#compliance-posture>) suggests, Claude Code skips that request. With that variable set, or with a gateway server older than v2.1.284, the bar and the status line stay percentage-only.
##
--- a/claude-apps-gateway-spend-limits.md
+++ b/claude-apps-gateway-spend-limits.md
@@ -1,4 +1,4 @@
-Spend limits cap how much each developer can spend through your [Claude apps gateway](</docs/en/claude-apps-gateway>) in a given day, week, or month. When a developer passes their cap, the gateway returns `429` on their next request and blocks them until the period resets or an admin raises the cap. Use spend limits to give each developer, group, or the whole organization a ceiling on a credential everyone shares. A Claude apps gateway forwards all inference through one shared upstream credential, so your provider’s bill attributes everything to that credential, not to individual developers. Without per-developer limits, one runaway agent fleet can spend the organization’s entire commitment. Spend limits are the gateway’s per-developer view and circuit breaker on top of that shared bill.
+Spend limits cap how much each developer can spend through your [Claude apps gateway](</docs/en/claude-apps-gateway>) in a given day, week, or month. When a developer passes their cap, the gateway returns `429` on their next request and blocks them until the period resets or an admin raises the cap. Use spend limits to give each developer, group, or the whole organization a ceiling on a credential everyone shares. By default, a Claude apps gateway forwards all inference through one shared upstream credential, so your provider’s bill attributes everything to that credential, not to individual developers. On Amazon Bedrock, [per-developer AWS cost attribution](</docs/en/claude-apps-gateway-config#per-developer-aws-cost-attribution>) changes this. Without per-developer limits, one runaway agent fleet can spend the organization’s entire commitment. Spend limits are the gateway’s per-developer view and circuit breaker on top of that shared bill.
##
--- a/claude-apps-gateway-spend-limits.md
+++ b/claude-apps-gateway-spend-limits.md
@@ -68,7 +68,7 @@
Postgres availability
-The pre-check queries Postgres with a two-second timeout. If the store is unreachable or times out, enforcement fails open by default: the request proceeds, the gateway logs a warning, and the response carries no `anthropic-ratelimit-unified-*` headers. Set [`enforcement.fail_closed_on_error: true`](</docs/en/claude-apps-gateway-config#enforcement>) to fail closed instead, which returns the same `429 billing_error` but with the message `spend limit unavailable` and no period, reset time, or `retry-after` header. Fail-open keeps a store outage from becoming an inference outage; fail-closed guarantees no unmetered spend.
+The pre-check queries Postgres with a two-second timeout. If the store is unreachable or times out, enforcement fails open by default: the request proceeds, the gateway logs a warning, and the response carries no `anthropic-ratelimit-unified-*` headers. Set [`enforcement.fail_closed_on_error: true`](</docs/en/claude-apps-gateway-config#enforcement>) to fail closed instead, which returns the same `429 billing_error` but with the message `spend limit unavailable` and no period, reset time, or `retry-after` header. Fail-open keeps a store outage from becoming an inference outage; fail-closed guarantees no unmetered spend. Fail-open only helps while your load balancer or orchestrator still routes traffic to the gateway. See [Outage behavior](</docs/en/claude-apps-gateway-deploy#outage-behavior>) for `store.readiness_grace_seconds`, which keeps replicas passing their readiness check through a short outage.
###
--- a/claude-apps-gateway-spend-limits.md
+++ b/claude-apps-gateway-spend-limits.md
@@ -76,12 +76,12 @@
Usage warnings in Claude Code
-Claude Code warns a developer as they approach their cap: once utilization passes 75%, and again past 95% of their fullest cap. When the gateway blocks a request, Claude Code shows the gateway’s `429` message as is, including your `admin.blocked_message`. The warning works off response headers:
+Claude Code warns a developer as they approach their cap: once utilization passes 75%, and again past 95% of their most-consumed cap. When the gateway blocks a request, Claude Code shows the gateway’s `429` message as is, including your `admin.blocked_message`. The warning works off response headers:
* With v2.1.225 or later on the gateway server, each successful `/v1/messages` response for a developer who has a cap carries their own cap utilization and reset time in the `anthropic-ratelimit-unified-*` headers.
* With v2.1.225 or later on the developer’s machine as well, Claude Code reads the headers and shows the warning.
-The headers always describe the developer’s own cap: the gateway strips the upstream provider’s rate-limit headers, which describe your shared quota, and never forwards them.
+The headers always describe the developer’s own cap: the gateway strips the upstream provider’s rate-limit headers, which describe your shared quota, and never forwards them. With v2.1.251 or later on the developer’s machine, Claude Code also reads the same headers to show a **Spend limit** bar in `/usage`, with the percentage of their cap used and when it resets, and to add a `rate_limits.spend_limit` object to the [status line](</docs/en/statusline#rate-limit-usage>) input. Claude Code shows both as a percentage rather than a dollar amount, and needs nothing newer than v2.1.225 on the gateway server.
##
--- a/claude-apps-gateway-spend-limits.md
+++ b/claude-apps-gateway-spend-limits.md
@@ -166,7 +166,7 @@
`admin_audit`| The mutation trail| [`admin.audit_retention_days`](</docs/en/claude-apps-gateway-config#admin>), default 365
`principal_emails`| Each principal’s last-seen email, display name, and IdP groups. Contains PII.| [`admin.identity_retention_days`](</docs/en/claude-apps-gateway-config#admin>) since last activity, default 90
-`identity_retention_days` is deliberately shorter than `spend_retention_months`: a deprovisioned identity stops refreshing and ages out, while its anonymous spend counters remain for year-over-year reporting. When a developer leaves, delete any per-user cap via `DELETE /v1/organizations/spend_limits/{id}`; their spend and identity rows age out on the retention windows above. To erase one person immediately, for offboarding or a data subject access request (DSAR), run `DELETE FROM principal_emails WHERE principal = '<sub>'` directly against the gateway database. That removes the only table holding their email, name, and groups. The `spend` and `admin_audit` rows reference the pseudonymous OIDC `sub` only and age out on their own windows.
+When a developer leaves, delete any per-user cap via `DELETE /v1/organizations/spend_limits/{id}`; their spend and identity rows age out on the retention windows above. To erase one person immediately, for offboarding or a data subject access request (DSAR), run `DELETE FROM principal_emails WHERE principal = '<sub>'` directly against the gateway database. That removes the only table holding their email, name, and groups. The `spend` and `admin_audit` rows reference the pseudonymous OIDC `sub` only and age out on their own windows.
##
--- a/claude-apps-gateway-spend-limits.md
+++ b/claude-apps-gateway-spend-limits.md
@@ -45,13 +45,22 @@
How enforcement works
-On each `/v1/messages` request, the gateway resolves the developer’s caps and period-to-date spend in one Postgres query. If they’re over any cap, the request returns `429` with `error.type: billing_error` and the header `x-should-retry: false`. The message is `spend limit reached`, followed by your [`admin.blocked_message`](</docs/en/claude-apps-gateway-config#admin>) if set. Caps reset on UTC calendar boundaries: daily at 00:00 UTC, weekly at 00:00 UTC on Monday, and monthly at 00:00 UTC on the first of the month. `/v1/messages/count_tokens` is exempt. Token counting is free, so it runs regardless of cap state. A running gateway serves a protocol description at `<public_url>/protocol` that lists the exact usage-limit response headers and the shape of the blocked `429`. Requires v2.1.227 or later. After each response, a usage meter reads token counts off the response as it streams to the client, prices them at USD list price, and increments Postgres counters for all three period buckets. The meter is a single reader on the stream, so the client’s bytes are untouched and a metering failure doesn’t break the response. Spend limits estimate spend from token counts at USD list price; they’re a circuit breaker, not an invoice. For authoritative billing, reconcile against your provider’s own usage reporting, such as the Anthropic Usage & Cost Admin API, invocation logs on Amazon Bedrock, or Cloud Monitoring on Google Cloud. Pricing uses the same table the Claude Code CLI uses for its own cost display, with the same model-ID canonicalization across Anthropic, Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry ID forms, such as Bedrock’s `us.anthropic.…-v1:0` and Agent Platform’s `claude-…@date`. The meter resolves each request’s rate tier in order:
+On each `/v1/messages` request, the gateway looks up the developer’s caps and period-to-date spend in one Postgres query. A developer over any cap gets a `429` with `error.type: billing_error` and header `x-should-retry: false`. The message names the period and reset time, such as `spend limit reached (daily; resets 2026-08-08 00:00 UTC)`, followed by your [`admin.blocked_message`](</docs/en/claude-apps-gateway-config#admin>) if set. When a developer exceeds several caps at once, the message names the cap that resets last. The response also carries a `retry-after` header with the seconds remaining until that reset. Before v2.1.225 on the gateway server, the message was `spend limit reached` with no period, reset time, or `retry-after` header. On v2.1.227 or later, the protocol reference at `<public_url>/protocol` also lists the exact usage-limit response headers and `429` body. Caps reset on UTC calendar boundaries: daily at 00:00 UTC, weekly on Monday, and monthly on the first. The gateway never blocks `/v1/messages/count_tokens`, because token counting is free.
- 1. Exact rates for the upstream model ID, the model string the gateway sends to the provider. When the table recognizes it, such as `us.anthropic.claude-…`, the meter prices the request by the model that served it.
- 2. Rates for the configured [`models[].id`](</docs/en/claude-apps-gateway-config#models>) you mapped to the upstream ID. This step covers upstream strings that carry no model name, such as an Amazon Bedrock application-inference-profile ARN or a Microsoft Foundry deployment name, and requires Claude Code v2.1.218 or later on the gateway server.
- 3. The unknown-model default tier of $5/$25 per million input/output tokens. The meter prices an ID that neither the table nor your `models` config can place, including a `models[].id` that is itself a custom alias, at this tier rather than zero, so an unrecognized ID can’t bypass a cap by going unmetered.
+###
-The gateway warns at boot and once per ID at runtime when it prices a model at the unknown-model tier. Before v2.1.218, the meter skipped step 2: it priced any upstream ID the table couldn’t place at the unknown-model tier and warned about it even when the configured ID’s rates were known. Client aborts are billed too. The upstream reports output tokens only in the stream’s terminal frame, so an aborted stream doesn’t carry them. The meter keeps a conservative floor estimate from the streamed content size, about four characters per token, and bills it when and only when the terminal usage frame is missing. A complete stream always bills the upstream-reported count. Without this, a capped developer could stream output and abort each request immediately before the end, spending without ever being counted.
+
+
+How requests are priced
+
+After each response, a usage meter reads the token counts and adds the cost to the daily, weekly, and monthly counters. It never touches the bytes sent to the client, so a metering failure can’t break a response. The amounts are USD estimates, a circuit breaker rather than an invoice; for billing, reconcile against your provider’s usage reporting. The meter picks each request’s rates in this order:
+
+ 1. A matching [`pricing.overrides`](</docs/en/claude-apps-gateway-config#pricing>) row for the upstream that served the request. Requires v2.1.227 or later.
+ 2. List price for the upstream model ID, the string the gateway sends to the provider, when the Claude Code cost table recognizes it. The table accepts Anthropic, Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry ID forms.
+ 3. List price for the [`models[].id`](</docs/en/claude-apps-gateway-config#models>) you mapped to that upstream ID, for upstream strings that carry no model name, such as an Amazon Bedrock application-inference-profile ARN or a Microsoft Foundry deployment name. Requires v2.1.218 or later.
+ 4. The unknown-model tier of $5/$25 per million input/output tokens, so an ID the meter can’t place is never free. The gateway warns at boot and once per ID at runtime when it uses this tier.
+
+Whichever rate applies, the meter then multiplies the amount by [`pricing.multiplier`](</docs/en/claude-apps-gateway-config#pricing>), default `1`. Client aborts are billed too. When a stream ends without the upstream’s final usage frame, the meter bills a floor estimate of about four characters per output token for the text already sent to the client, so aborting requests early doesn’t evade a cap.
###
@@ -59,7 +68,20 @@
Postgres availability
-The pre-check queries Postgres with a two-second timeout. If the store is unreachable or times out, enforcement fails open by default: the request proceeds and the gateway logs a warning. Set [`enforcement.fail_closed_on_error: true`](</docs/en/claude-apps-gateway-config#enforcement>) to fail closed instead, which returns the same `429 billing_error` with the message `spend limit unavailable`. Fail-open keeps a store outage from becoming an inference outage; fail-closed guarantees no unmetered spend.
+The pre-check queries Postgres with a two-second timeout. If the store is unreachable or times out, enforcement fails open by default: the request proceeds, the gateway logs a warning, and the response carries no `anthropic-ratelimit-unified-*` headers. Set [`enforcement.fail_closed_on_error: true`](</docs/en/claude-apps-gateway-config#enforcement>) to fail closed instead, which returns the same `429 billing_error` but with the message `spend limit unavailable` and no period, reset time, or `retry-after` header. Fail-open keeps a store outage from becoming an inference outage; fail-closed guarantees no unmetered spend.
+
+###
+
+
+
+Usage warnings in Claude Code
+
+Claude Code warns a developer as they approach their cap: once utilization passes 75%, and again past 95% of their fullest cap. When the gateway blocks a request, Claude Code shows the gateway’s `429` message as is, including your `admin.blocked_message`. The warning works off response headers:
+
+ * With v2.1.225 or later on the gateway server, each successful `/v1/messages` response for a developer who has a cap carries their own cap utilization and reset time in the `anthropic-ratelimit-unified-*` headers.
+ * With v2.1.225 or later on the developer’s machine as well, Claude Code reads the headers and shows the warning.
+
+The headers always describe the developer’s own cap: the gateway strips the upstream provider’s rate-limit headers, which describe your shared quota, and never forwards them.
##
--- a/claude-apps-gateway-spend-limits.md
+++ b/claude-apps-gateway-spend-limits.md
@@ -45,7 +45,7 @@
How enforcement works
-On each `/v1/messages` request, the gateway resolves the developer’s caps and period-to-date spend in one Postgres query. If they’re over any cap, the request returns `429` with `error.type: billing_error` and the header `x-should-retry: false`. The message is `spend limit reached`, followed by your [`admin.blocked_message`](</docs/en/claude-apps-gateway-config#admin>) if set. Caps reset on UTC calendar boundaries: daily at 00:00 UTC, weekly at 00:00 UTC on Monday, and monthly at 00:00 UTC on the first of the month. `/v1/messages/count_tokens` is exempt. Token counting is free, so it runs regardless of cap state. After each response, a usage meter reads token counts off the response as it streams to the client, prices them at USD list price, and increments Postgres counters for all three period buckets. The meter is a single reader on the stream, so the client’s bytes are untouched and a metering failure doesn’t break the response. Spend limits estimate spend from token counts at USD list price; they’re a circuit breaker, not an invoice. For authoritative billing, reconcile against your provider’s own usage reporting, such as the Anthropic Usage & Cost Admin API, invocation logs on Amazon Bedrock, or Cloud Monitoring on Google Cloud. Pricing uses the same table the Claude Code CLI uses for its own cost display, with the same model-ID canonicalization across Anthropic, Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry ID forms, such as Bedrock’s `us.anthropic.…-v1:0` and Agent Platform’s `claude-…@date`. The meter resolves each request’s rate tier in order:
+On each `/v1/messages` request, the gateway resolves the developer’s caps and period-to-date spend in one Postgres query. If they’re over any cap, the request returns `429` with `error.type: billing_error` and the header `x-should-retry: false`. The message is `spend limit reached`, followed by your [`admin.blocked_message`](</docs/en/claude-apps-gateway-config#admin>) if set. Caps reset on UTC calendar boundaries: daily at 00:00 UTC, weekly at 00:00 UTC on Monday, and monthly at 00:00 UTC on the first of the month. `/v1/messages/count_tokens` is exempt. Token counting is free, so it runs regardless of cap state. A running gateway serves a protocol description at `<public_url>/protocol` that lists the exact usage-limit response headers and the shape of the blocked `429`. Requires v2.1.227 or later. After each response, a usage meter reads token counts off the response as it streams to the client, prices them at USD list price, and increments Postgres counters for all three period buckets. The meter is a single reader on the stream, so the client’s bytes are untouched and a metering failure doesn’t break the response. Spend limits estimate spend from token counts at USD list price; they’re a circuit breaker, not an invoice. For authoritative billing, reconcile against your provider’s own usage reporting, such as the Anthropic Usage & Cost Admin API, invocation logs on Amazon Bedrock, or Cloud Monitoring on Google Cloud. Pricing uses the same table the Claude Code CLI uses for its own cost display, with the same model-ID canonicalization across Anthropic, Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry ID forms, such as Bedrock’s `us.anthropic.…-v1:0` and Agent Platform’s `claude-…@date`. The meter resolves each request’s rate tier in order:
1. Exact rates for the upstream model ID, the model string the gateway sends to the provider. When the table recognizes it, such as `us.anthropic.claude-…`, the meter prices the request by the model that served it.
2. Rates for the configured [`models[].id`](</docs/en/claude-apps-gateway-config#models>) you mapped to the upstream ID. This step covers upstream strings that carry no model name, such as an Amazon Bedrock application-inference-profile ARN or a Microsoft Foundry deployment name, and requires Claude Code v2.1.218 or later on the gateway server.
--- a/claude-apps-gateway-spend-limits.md
+++ b/claude-apps-gateway-spend-limits.md
@@ -45,7 +45,7 @@
How enforcement works
-On each `/v1/messages` request, the gateway resolves the developer’s caps and period-to-date spend in one Postgres query. If they’re over any cap, the request returns `429` with `error.type: billing_error` and the header `x-should-retry: false`. The message is `spend limit reached`, followed by your [`admin.blocked_message`](</docs/en/claude-apps-gateway-config#admin>) if set. `/v1/messages/count_tokens` is exempt. Token counting is free, so it runs regardless of cap state. After each response, a usage meter reads token counts off the response as it streams to the client, prices them at USD list price, and increments Postgres counters for all three period buckets. The meter is a single reader on the stream, so the client’s bytes are untouched and a metering failure doesn’t break the response. Spend limits estimate spend from token counts at USD list price; they’re a circuit breaker, not an invoice. For authoritative billing, reconcile against your provider’s own usage reporting, such as the Anthropic Usage & Cost Admin API, invocation logs on Amazon Bedrock, or Cloud Monitoring on Google Cloud. Pricing uses the same table the Claude Code CLI uses for its own cost display, with the same model-ID canonicalization across Anthropic, Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry ID forms, such as Bedrock’s `us.anthropic.…-v1:0` and Agent Platform’s `claude-…@date`. The meter resolves each request’s rate tier in order:
+On each `/v1/messages` request, the gateway resolves the developer’s caps and period-to-date spend in one Postgres query. If they’re over any cap, the request returns `429` with `error.type: billing_error` and the header `x-should-retry: false`. The message is `spend limit reached`, followed by your [`admin.blocked_message`](</docs/en/claude-apps-gateway-config#admin>) if set. Caps reset on UTC calendar boundaries: daily at 00:00 UTC, weekly at 00:00 UTC on Monday, and monthly at 00:00 UTC on the first of the month. `/v1/messages/count_tokens` is exempt. Token counting is free, so it runs regardless of cap state. After each response, a usage meter reads token counts off the response as it streams to the client, prices them at USD list price, and increments Postgres counters for all three period buckets. The meter is a single reader on the stream, so the client’s bytes are untouched and a metering failure doesn’t break the response. Spend limits estimate spend from token counts at USD list price; they’re a circuit breaker, not an invoice. For authoritative billing, reconcile against your provider’s own usage reporting, such as the Anthropic Usage & Cost Admin API, invocation logs on Amazon Bedrock, or Cloud Monitoring on Google Cloud. Pricing uses the same table the Claude Code CLI uses for its own cost display, with the same model-ID canonicalization across Anthropic, Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry ID forms, such as Bedrock’s `us.anthropic.…-v1:0` and Agent Platform’s `claude-…@date`. The meter resolves each request’s rate tier in order:
1. Exact rates for the upstream model ID, the model string the gateway sends to the provider. When the table recognizes it, such as `us.anthropic.claude-…`, the meter prices the request by the model that served it.
2. Rates for the configured [`models[].id`](</docs/en/claude-apps-gateway-config#models>) you mapped to the upstream ID. This step covers upstream strings that carry no model name, such as an Amazon Bedrock application-inference-profile ARN or a Microsoft Foundry deployment name, and requires Claude Code v2.1.218 or later on the gateway server.
@@ -71,12 +71,12 @@
Method and path| Description
---|---
-`GET /v1/organizations/spend_limits`| List configured caps. Query: `?limit=&after_id=&before_id=`.
+`GET /v1/organizations/spend_limits`| List configured caps, optionally filtered to one `scope_type` of `organization`, `rbac_group`, or `user`. Query: `?limit=&after_id=&before_id=&scope_type=`.
`POST /v1/organizations/spend_limits`| Create or replace a cap for `{scope, period}`.
`GET /v1/organizations/spend_limits/{id}`| Fetch one cap by its `spl_`-prefixed ID.
`DELETE /v1/organizations/spend_limits/{id}`| Delete one cap. Returns `{type: "spend_limit_deleted", id}`.
`GET /v1/organizations/spend_limits/effective`| Resolved cap and to-date spend per principal per period.
-`GET /v1/organizations/spend_limits/audit`| Admin mutation trail, newest-first. Query: `?limit=`.
+`GET /v1/organizations/spend_limits/audit`| Admin mutation trail, newest-first. Query: `?limit=&after_id=`.
Conventions mirror Anthropic’s Admin API:
@@ -84,7 +84,7 @@
* `spl_`-prefixed IDs
* Amounts as whole-number strings of USD cents; `POST` rejects any other `currency` with `400`
* The `{type: "error", error: {type, message}, request_id}` error envelope
- * A `request-id` response header on every admin response, success or error, matching the body’s `request_id`
+ * A `request-id` response header on every admin response, success or error; error bodies also carry it as `request_id`
Every mutation writes a before/after row to `admin_audit` in the same transaction, attributed to `admin-key:<id>` or `oidc:<sub>`. The gateway serves the spend-limits endpoints only. Other Admin API surfaces, such as the `spend_limit_increase_requests` queue, aren’t part of the gateway’s admin API.
@@ -119,7 +119,7 @@
`/audit`
-Returns the spend-limit mutation trail: who changed which cap, before/after snapshots, and the optional reason, newest-first. `has_more` is exact. This endpoint follows the local Admin API conventions rather than a first-party wire shape.
+Returns the spend-limit mutation trail: who changed which cap, with before/after snapshots, newest-first. `has_more` is exact. This endpoint follows the local Admin API conventions rather than a first-party wire shape.
###
@@ -127,7 +127,7 @@
Pagination
-The raw list pages by `after_id` and `before_id`, which are mutually exclusive `spl_…` IDs; results are ordered by creation and `has_more` reflects the traversal direction. `/effective` pages by the opaque `next_page` token passed back as `?page=`, with principals ordered ascending so pages stay stable while spend is being recorded. `limit` is 1–1000, default 20, on both.
+The raw list pages by `after_id` and `before_id`, which are mutually exclusive `spl_…` IDs; results are ordered by creation and `has_more` reflects the traversal direction. `/effective` pages by the opaque `next_page` token passed back as `?page=`, with principals ordered ascending so pages stay stable while spend is being recorded. `limit` is 1–1000, default 20, on both. `/audit` pages by `after_id`, the numeric `id` of the last event on the previous page, and its `limit` defaults to 100.
##
--- a/claude-apps-gateway-spend-limits.md
+++ b/claude-apps-gateway-spend-limits.md
@@ -45,7 +45,13 @@
How enforcement works
-On each `/v1/messages` request, the gateway resolves the developer’s caps and period-to-date spend in one Postgres query. If they’re over any cap, the request returns `429` with `error.type: billing_error` and the header `x-should-retry: false`. The message is `spend limit reached`, followed by your [`admin.blocked_message`](</docs/en/claude-apps-gateway-config#admin>) if set. `/v1/messages/count_tokens` is exempt. Token counting is free, so it runs regardless of cap state. After each response, a usage meter reads token counts off the response as it streams to the client, prices them at USD list price, and increments Postgres counters for all three period buckets. The meter is a single reader on the stream, so the client’s bytes are untouched and a metering failure doesn’t break the response. Spend limits estimate spend from token counts at USD list price; they’re a circuit breaker, not an invoice. For authoritative billing, reconcile against your provider’s own usage reporting, such as the Anthropic Usage & Cost Admin API, invocation logs on Amazon Bedrock, or Cloud Monitoring on Google Cloud. Pricing uses the same table the Claude Code CLI uses for its own cost display, with the same model-ID canonicalization across Anthropic, Amazon Bedrock (`us.anthropic.…-v1:0`), Google Cloud’s Agent Platform (`claude-…@date`), and Microsoft Foundry ID forms. A model ID the table can’t place, such as a Microsoft Foundry deployment name or an inference-profile ARN, is priced at the unknown-model default tier of $5/$25 per million input/output tokens rather than zero, so an unrecognized ID can’t bypass a cap by going unmetered. The gateway warns at boot and once per ID at runtime when a model prices through the fallback. Client aborts are billed too. The upstream reports output tokens only in the stream’s terminal frame, so an aborted stream doesn’t carry them. The meter keeps a conservative floor estimate from the streamed content size, about four characters per token, and bills it when and only when the terminal usage frame is missing. A complete stream always bills the upstream-reported count. Without this, a capped developer could stream output and abort each request immediately before the end, spending without ever being counted.
+On each `/v1/messages` request, the gateway resolves the developer’s caps and period-to-date spend in one Postgres query. If they’re over any cap, the request returns `429` with `error.type: billing_error` and the header `x-should-retry: false`. The message is `spend limit reached`, followed by your [`admin.blocked_message`](</docs/en/claude-apps-gateway-config#admin>) if set. `/v1/messages/count_tokens` is exempt. Token counting is free, so it runs regardless of cap state. After each response, a usage meter reads token counts off the response as it streams to the client, prices them at USD list price, and increments Postgres counters for all three period buckets. The meter is a single reader on the stream, so the client’s bytes are untouched and a metering failure doesn’t break the response. Spend limits estimate spend from token counts at USD list price; they’re a circuit breaker, not an invoice. For authoritative billing, reconcile against your provider’s own usage reporting, such as the Anthropic Usage & Cost Admin API, invocation logs on Amazon Bedrock, or Cloud Monitoring on Google Cloud. Pricing uses the same table the Claude Code CLI uses for its own cost display, with the same model-ID canonicalization across Anthropic, Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry ID forms, such as Bedrock’s `us.anthropic.…-v1:0` and Agent Platform’s `claude-…@date`. The meter resolves each request’s rate tier in order:
+
+ 1. Exact rates for the upstream model ID, the model string the gateway sends to the provider. When the table recognizes it, such as `us.anthropic.claude-…`, the meter prices the request by the model that served it.
+ 2. Rates for the configured [`models[].id`](</docs/en/claude-apps-gateway-config#models>) you mapped to the upstream ID. This step covers upstream strings that carry no model name, such as an Amazon Bedrock application-inference-profile ARN or a Microsoft Foundry deployment name, and requires Claude Code v2.1.218 or later on the gateway server.
+ 3. The unknown-model default tier of $5/$25 per million input/output tokens. The meter prices an ID that neither the table nor your `models` config can place, including a `models[].id` that is itself a custom alias, at this tier rather than zero, so an unrecognized ID can’t bypass a cap by going unmetered.
+
+The gateway warns at boot and once per ID at runtime when it prices a model at the unknown-model tier. Before v2.1.218, the meter skipped step 2: it priced any upstream ID the table couldn’t place at the unknown-model tier and warned about it even when the configured ID’s rates were known. Client aborts are billed too. The upstream reports output tokens only in the stream’s terminal frame, so an aborted stream doesn’t carry them. The meter keeps a conservative floor estimate from the streamed content size, about four characters per token, and bills it when and only when the terminal usage frame is missing. A complete stream always bills the upstream-reported count. Without this, a capped developer could stream output and abort each request immediately before the end, spending without ever being counted.
###
--- a/claude-apps-gateway-spend-limits.md
+++ b/claude-apps-gateway-spend-limits.md
@@ -45,7 +45,7 @@
How enforcement works
-On each `/v1/messages` request, the gateway resolves the developer’s caps and period-to-date spend in one Postgres query. If they’re over any cap, the request returns `429` with `error.type: billing_error` and the header `x-should-retry: false`. The message is `spend limit reached`, followed by your [`admin.blocked_message`](</docs/en/claude-apps-gateway-config#admin>) if set. `/v1/messages/count_tokens` is exempt. Token counting is free, so it runs regardless of cap state. After each response, a usage meter reads token counts off the response as it streams to the client, prices them at USD list price, and increments Postgres counters for all three period buckets. The meter is a single reader on the stream, so the client’s bytes are untouched and a metering failure doesn’t break the response. Spend limits estimate spend from token counts at USD list price; they’re a circuit breaker, not an invoice. For authoritative billing, reconcile against your provider’s own usage reporting, such as the Anthropic Usage & Cost Admin API, invocation logs on Bedrock, or Cloud Monitoring on Google Cloud. Pricing uses the same table the Claude Code CLI uses for its own cost display, with the same model-ID canonicalization across Anthropic, Bedrock (`us.anthropic.…-v1:0`), Agent Platform (`claude-…@date`), and Foundry ID forms. A model ID the table can’t place, such as a Foundry deployment name or an inference-profile ARN, is priced at the unknown-model default tier of $5/$25 per million input/output tokens rather than zero, so an unrecognized ID can’t bypass a cap by going unmetered. The gateway warns at boot and once per ID at runtime when a model prices through the fallback. Client aborts are billed too. The upstream reports output tokens only in the stream’s terminal frame, so an aborted stream doesn’t carry them. The meter keeps a conservative floor estimate from the streamed content size, about four characters per token, and bills it when and only when the terminal usage frame is missing. A complete stream always bills the upstream-reported count. Without this, a capped developer could stream output and abort each request immediately before the end, spending without ever being counted.
+On each `/v1/messages` request, the gateway resolves the developer’s caps and period-to-date spend in one Postgres query. If they’re over any cap, the request returns `429` with `error.type: billing_error` and the header `x-should-retry: false`. The message is `spend limit reached`, followed by your [`admin.blocked_message`](</docs/en/claude-apps-gateway-config#admin>) if set. `/v1/messages/count_tokens` is exempt. Token counting is free, so it runs regardless of cap state. After each response, a usage meter reads token counts off the response as it streams to the client, prices them at USD list price, and increments Postgres counters for all three period buckets. The meter is a single reader on the stream, so the client’s bytes are untouched and a metering failure doesn’t break the response. Spend limits estimate spend from token counts at USD list price; they’re a circuit breaker, not an invoice. For authoritative billing, reconcile against your provider’s own usage reporting, such as the Anthropic Usage & Cost Admin API, invocation logs on Amazon Bedrock, or Cloud Monitoring on Google Cloud. Pricing uses the same table the Claude Code CLI uses for its own cost display, with the same model-ID canonicalization across Anthropic, Amazon Bedrock (`us.anthropic.…-v1:0`), Google Cloud’s Agent Platform (`claude-…@date`), and Microsoft Foundry ID forms. A model ID the table can’t place, such as a Microsoft Foundry deployment name or an inference-profile ARN, is priced at the unknown-model default tier of $5/$25 per million input/output tokens rather than zero, so an unrecognized ID can’t bypass a cap by going unmetered. The gateway warns at boot and once per ID at runtime when a model prices through the fallback. Client aborts are billed too. The upstream reports output tokens only in the stream’s terminal frame, so an aborted stream doesn’t carry them. The meter keeps a conservative floor estimate from the streamed content size, about four characters per token, and bills it when and only when the terminal usage frame is missing. A complete stream always bills the upstream-reported count. Without this, a capped developer could stream output and abort each request immediately before the end, spending without ever being counted.
###
Show diff (153 lines)
--- a/claude-apps-gateway-spend-limits.md
+++ b/claude-apps-gateway-spend-limits.md
@@ -0,0 +1,150 @@
+Spend limits cap how much each developer can spend through your [Claude apps gateway](</docs/en/claude-apps-gateway>) in a given day, week, or month. When a developer passes their cap, the gateway returns `429` on their next request and blocks them until the period resets or an admin raises the cap. Use spend limits to give each developer, group, or the whole organization a ceiling on a credential everyone shares. A Claude apps gateway forwards all inference through one shared upstream credential, so your provider’s bill attributes everything to that credential, not to individual developers. Without per-developer limits, one runaway agent fleet can spend the organization’s entire commitment. Spend limits are the gateway’s per-developer view and circuit breaker on top of that shared bill.
+
+##
+
+
+
+Set a cap
+
+With the [`admin:`](</docs/en/claude-apps-gateway-config#admin>) block configured in `gateway.yaml`, the gateway serves an admin API at `/v1/organizations/spend_limits` and enforces caps live on every inference request. Caps themselves are set through that API, not in `gateway.yaml`; each `POST /v1/organizations/spend_limits` request creates or replaces one cap from `{scope, amount, period}`. The API mirrors the wire shapes of Anthropic’s public [Admin API](<https://platform.claude.com/docs/en/manage-claude/admin-api>) spend-limits endpoints, so an HTTP client written against that contract can target the gateway by changing its base URL. This request sets an org-wide default of $500 per month for every developer:
+
+ curl -sS https://claude-gateway.internal.example.com/v1/organizations/spend_limits \
+ -H "x-api-key: $GATEWAY_ADMIN_WRITE_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"scope": {"type": "organization"}, "amount": "50000", "period": "monthly"}'
+
+This request layers a tighter $100-per-day cap on each member of the `contractors` group:
+
+ curl -sS https://claude-gateway.internal.example.com/v1/organizations/spend_limits \
+ -H "x-api-key: $GATEWAY_ADMIN_WRITE_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"scope": {"type": "rbac_group", "rbac_group_id": "contractors"}, "amount": "10000", "period": "daily"}'
+
+Field| Values| Description
+---|---|---
+`scope.type`| `user`, `rbac_group`, `organization`| `user` targets one developer by their OpenID Connect (OIDC) `sub`, the stable user ID your identity provider assigns; pass it as `scope.user_id`. `rbac_group` targets an [IdP group](</docs/en/claude-apps-gateway-config#managed>) by name; pass it as `scope.rbac_group_id`. `organization` is the org-wide default. The gateway accepts all three; Anthropic’s public `POST` is user-only today.
+`amount`| Whole-number string of USD cents, or `null`| `null` is unlimited. `"0"` is a zero cap, which blocks every request.
+`period`| `daily`, `weekly`, `monthly`| A scope can hold one cap per period, and each enforces independently: a developer is blocked if over any of them.
+
+A group or organization cap is a per-seat default that each member inherits, not a shared pool. Per period, a developer’s effective cap resolves in this order: a per-user override, then the most restrictive of their group caps, then the org default, then unlimited. [`admin.group_limit_mode: max`](</docs/en/claude-apps-gateway-config#admin>) flips the multi-group tie-break to least-restrictive instead.
+
+###
+
+
+
+Authenticate to the admin API
+
+Send one of:
+
+ * An `x-api-key` header matching a key in [`admin.write_keys`](</docs/en/claude-apps-gateway-config#admin>) for full access, or `admin.read_keys` for `GET`-only access. Each key carries an `id` that appears in the audit log as `admin-key:<id>`, so give Terraform, CI, and each automation its own.
+ * A gateway bearer token whose `groups` claim includes one of [`admin.admin_groups`](</docs/en/claude-apps-gateway-config#admin>). This is full access and audits as `oidc:<sub>`, so prefer it for human admins.
+
+##
+
+
+
+How enforcement works
+
+On each `/v1/messages` request, the gateway resolves the developer’s caps and period-to-date spend in one Postgres query. If they’re over any cap, the request returns `429` with `error.type: billing_error` and the header `x-should-retry: false`. The message is `spend limit reached`, followed by your [`admin.blocked_message`](</docs/en/claude-apps-gateway-config#admin>) if set. `/v1/messages/count_tokens` is exempt. Token counting is free, so it runs regardless of cap state. After each response, a usage meter reads token counts off the response as it streams to the client, prices them at USD list price, and increments Postgres counters for all three period buckets. The meter is a single reader on the stream, so the client’s bytes are untouched and a metering failure doesn’t break the response. Spend limits estimate spend from token counts at USD list price; they’re a circuit breaker, not an invoice. For authoritative billing, reconcile against your provider’s own usage reporting, such as the Anthropic Usage & Cost Admin API, invocation logs on Bedrock, or Cloud Monitoring on Google Cloud. Pricing uses the same table the Claude Code CLI uses for its own cost display, with the same model-ID canonicalization across Anthropic, Bedrock (`us.anthropic.…-v1:0`), Agent Platform (`claude-…@date`), and Foundry ID forms. A model ID the table can’t place, such as a Foundry deployment name or an inference-profile ARN, is priced at the unknown-model default tier of $5/$25 per million input/output tokens rather than zero, so an unrecognized ID can’t bypass a cap by going unmetered. The gateway warns at boot and once per ID at runtime when a model prices through the fallback. Client aborts are billed too. The upstream reports output tokens only in the stream’s terminal frame, so an aborted stream doesn’t carry them. The meter keeps a conservative floor estimate from the streamed content size, about four characters per token, and bills it when and only when the terminal usage frame is missing. A complete stream always bills the upstream-reported count. Without this, a capped developer could stream output and abort each request immediately before the end, spending without ever being counted.
+
+###
+
+
+
+Postgres availability
+
+The pre-check queries Postgres with a two-second timeout. If the store is unreachable or times out, enforcement fails open by default: the request proceeds and the gateway logs a warning. Set [`enforcement.fail_closed_on_error: true`](</docs/en/claude-apps-gateway-config#enforcement>) to fail closed instead, which returns the same `429 billing_error` with the message `spend limit unavailable`. Fail-open keeps a store outage from becoming an inference outage; fail-closed guarantees no unmetered spend.
+
+##
+
+
+
+Admin API reference
+
+The endpoints below are served under `/v1/organizations/spend_limits`.
+
+Method and path| Description
+---|---
+`GET /v1/organizations/spend_limits`| List configured caps. Query: `?limit=&after_id=&before_id=`.
+`POST /v1/organizations/spend_limits`| Create or replace a cap for `{scope, period}`.
+`GET /v1/organizations/spend_limits/{id}`| Fetch one cap by its `spl_`-prefixed ID.
+`DELETE /v1/organizations/spend_limits/{id}`| Delete one cap. Returns `{type: "spend_limit_deleted", id}`.
+`GET /v1/organizations/spend_limits/effective`| Resolved cap and to-date spend per principal per period.
+`GET /v1/organizations/spend_limits/audit`| Admin mutation trail, newest-first. Query: `?limit=`.
+
+Conventions mirror Anthropic’s Admin API:
+
+ * A `type` on every object
+ * `spl_`-prefixed IDs
+ * Amounts as whole-number strings of USD cents; `POST` rejects any other `currency` with `400`
+ * The `{type: "error", error: {type, message}, request_id}` error envelope
+ * A `request-id` response header on every admin response, success or error, matching the body’s `request_id`
+
+Every mutation writes a before/after row to `admin_audit` in the same transaction, attributed to `admin-key:<id>` or `oidc:<sub>`. The gateway serves the spend-limits endpoints only. Other Admin API surfaces, such as the `spend_limit_increase_requests` queue, aren’t part of the gateway’s admin API.
+
+###
+
+
+
+`/effective`
+
+`GET /v1/organizations/spend_limits/effective` returns Anthropic’s `SpendSummary` schema: each row is a principal for a period, with the resolved cap, period-to-date spend, and an `actor` object. Gateway-specific differences:
+
+ * `user_id` is the OIDC `sub`.
+ * `actor.name` and `actor.email_address` are `null` until the principal’s first inference request through the gateway. The gateway has no user directory; it records last-seen values from each user’s own session JWT.
+ * Each row also carries a `groups` array, the principal’s last-seen IdP groups. This is a gateway extension so an admin UI can show every cap tier that applies; Anthropic-shaped clients ignore it.
+ * Without a `user_ids[]` filter, it lists principals with recorded spend, because the gateway can’t enumerate all org members.
+
+Group-sourced caps resolve against those last-seen groups with the same `group_limit_mode` tie-break that enforcement uses, so the viewer shows the cap that actually applies.
+
+Query parameter| Description
+---|---
+`user_ids[]`| Repeatable. Filter to specific principals by OIDC `sub`.
+`period[]`| Repeatable. Filter to `daily`, `weekly`, or `monthly` rows.
+`sort`| `spend_desc` lists top spenders first. Requires exactly one `period[]`.
+`q`| Case-insensitive substring filter over the OIDC `sub`, last-seen email, and last-seen display name.
+`limit` / `page`| Page size, 1–1000 with a default of 20, and the opaque cursor from the previous response’s `next_page`.
+
+`q=` and `user_ids[]=` ride GET query strings, so any fronting proxy or load balancer captures them in its access logs. If your PII log policy is strict, scrub these parameters there.
+
+###
+
+
+
+`/audit`
+
+Returns the spend-limit mutation trail: who changed which cap, before/after snapshots, and the optional reason, newest-first. `has_more` is exact. This endpoint follows the local Admin API conventions rather than a first-party wire shape.
+
+###
+
+
+
+Pagination
+
+The raw list pages by `after_id` and `before_id`, which are mutually exclusive `spl_…` IDs; results are ordered by creation and `has_more` reflects the traversal direction. `/effective` pages by the opaque `next_page` token passed back as `?page=`, with principals ordered ascending so pages stay stable while spend is being recorded. `limit` is 1–1000, default 20, on both.
+
+##
+
+
+
+Data lifecycle
+
+The gateway holds four spend-related tables; an hourly sweep enforces the retention windows:
+
+Table| Contents| Retention
+---|---|---
+`spend`| Per-principal period-to-date counters in cents| [`admin.spend_retention_months`](</docs/en/claude-apps-gateway-config#admin>), default 13
+`spend_limits`| The configured caps| Until deleted via the API
+`admin_audit`| The mutation trail| [`admin.audit_retention_days`](</docs/en/claude-apps-gateway-config#admin>), default 365
+`principal_emails`| Each principal’s last-seen email, display name, and IdP groups. Contains PII.| [`admin.identity_retention_days`](</docs/en/claude-apps-gateway-config#admin>) since last activity, default 90
+
+`identity_retention_days` is deliberately shorter than `spend_retention_months`: a deprovisioned identity stops refreshing and ages out, while its anonymous spend counters remain for year-over-year reporting. When a developer leaves, delete any per-user cap via `DELETE /v1/organizations/spend_limits/{id}`; their spend and identity rows age out on the retention windows above. To erase one person immediately, for offboarding or a data subject access request (DSAR), run `DELETE FROM principal_emails WHERE principal = '<sub>'` directly against the gateway database. That removes the only table holding their email, name, and groups. The `spend` and `admin_audit` rows reference the pseudonymous OIDC `sub` only and age out on their own windows.
+
+##
+
+
+
+Related
+
+ * [`admin` and `enforcement` configuration](</docs/en/claude-apps-gateway-config#admin>): enabling the admin API and tuning retention
+ * [Deployment guide](</docs/en/claude-apps-gateway-deploy#postgres>): Postgres schema and backup guidance