# Budgets and TPM

**Last updated:** 2026-11-27T12:02:53-03:00 (UTC-3)

Reserve capacity **before** a call reaches the provider, then settle against the usage it reports:

- **Budget:** dollars per UTC day or month, with optional calendar week, quarter, year and nonresetting lifetime.
- **TPM:** tokens per minute (UTC). **TPD**, tokens per day, is covered in [attribution and alerts](/docs/features/quota-governance/#tokens-per-day-tpd).

The limits apply per key, team, model alias, user, project, organization or your app's end user, and they add up: a request only goes through if it fits within **every** limit that applies to it. Enforcement happens in PostgreSQL, so it covers all replicas together. No limit grants access to a model or route.

Each limit has its own counter, charged when a request is admitted. That is what happens when a team moves to another [organization](/docs/features/organizations/#when-a-team-moves): the team's budget keeps running (a team at 90% stays at 90%), the former organization's [tenant ceiling](/docs/features/quota-governance/#tenant-ceiling) keeps what the team spent there, and the new organization's starts counting the team at the move.

## How to turn it on

```yaml
features:
  usage_analytics: true
  durable_usage: true
  tpm_limits: true           # boot: token limit
  budget_limits: true        # boot: USD limit
  quota_management: true     # edit from the console and the API
quotas:
  settings:
    max_input_tokens: 2000000
    max_items: 1024
    max_tools: 128
    max_content_parts: 128
    overrun_alert_tolerance_percent: 0
    overrun_alert_dedupe_seconds: 0
  policies:
    - id: time-acme
      subject: team
      subject_id: acme
      tpm: 200000
      budget_usd: "500"
      budget_period: month
      alert_thresholds: [80, 100]
  rates:
    - provider_id: openai
      model: gpt-4.1-mini
      connection: "<hash shown in the console>"
      input_usd_per_million: "0.40"
      output_usd_per_million: "1.60"
      cache_read_usd_per_million: "0.10"   # optional: prompt-cache reads
      revision: rev-1
```

`tpm_limits` and `budget_limits` are boot flags: they change on restart. They require PostgreSQL and durable usage. All flags start off.

| Flag | What it adds |
| --- | --- |
| `quota_management` | Edit policies and rates in the console and the API, with versioning and audit |
| `calendar_budget_periods` | Enable calendar week, quarter and year USD budgets; off by default and requires `budget_limits` |
| `lifetime_budget_limits` | Enable a permanent USD budget with no automatic reset; off by default and requires `budget_limits` |
| `temporary_budget_increases` | Apply an optional time-limited addition to a policy ceiling; off by default and requires `budget_limits` |
| `hierarchical_quotas` | [Per-child templates](#per-child-templates): one ceiling applied independently to every key, user or team of a parent; off by default and requires `budget_limits` or `tpm_limits` |
| `quota_streaming` | Streams (SSE); requires `stream_usage` |
| `quota_native_protocols` | Native Anthropic Messages and Gemini; translated routes use the chat profile and do not require this native-profile flag |
| `quota_embeddings` | Embeddings |
| `quota_media` | Image, transcription and rerank, per unit |
| `quota_video` | Runway asynchronous video ([details](/docs/features/quota-video/)) |
| `quota_finance` | Reconciliation, invoice imports and archiving ([details](/docs/features/quota-finance/)) |
| `quota_manual_release` | An administrator with `quota_reservations:release` gives back the holds of an unknown reservation, with a written reason and an audit record; nothing is released automatically ([details](/docs/features/quota-finance/#releasing-an-unknown-reservation-by-hand)); off by default and requires `quota_finance` |

What each profile requires is in [protected profiles](/docs/features/quota-protocols/).

## Policies

| Field | Values |
| --- | --- |
| `quotas.policies[].subject` | `key`, `team`, `model`, `user`, `project`, `organization`, `end_user`; `group` with `attribution_groups` ([attribution groups](/docs/features/attribution-groups/)) |
| `quotas.policies[].subject_id` | The subject's ID; for `model`, the exact public alias; for `end_user`, the team; for `group`, the attribution group ID |
| `quotas.policies[].tpd` | Tokens per UTC day; requires the `tpd_limits` flag |
| `quotas.policies[].tpm` | Positive integer |
| `quotas.policies[].budget_usd` | Positive decimal as a string, up to six decimal places |
| `quotas.policies[].budget_period` | `day`, `month`; `week`, `quarter`, `year` additionally require `calendar_budget_periods`; `lifetime` requires `lifetime_budget_limits` |
| `quotas.policies[].soft_budget` | `true` alerts without denying on USD; TPM stays hard |
| `quotas.policies[].alert_thresholds` | Up to five unique percentages from 1 to 100 |
| `quotas.policies[].disabled` | Keeps the policy without applying it |
| `quotas.policies[].child` | Optional [per-child template](#per-child-templates); requires `hierarchical_quotas` |

A policy needs at least one of `tpm`, `tpd`, `budget_usd` and `child`. User, project and organization depend on an explicit binding on the managed key, explained in [attribution and alerts](/docs/features/quota-governance/). Up to 128 policies and 256 rates fit.

**Per end user.** With `end_user_budgets` (which requires `end_user_tracking` and `budget_limits` or `tpm_limits`), a `subject: end_user` policy whose `subject_id` equals a team applies the limit to **each** end user of that team, identified by the `X-Gateway-End-User` header. The header is declared by the key, not authenticated: it serves to split the quota among your app's users, not as an identity control.

### Amounts in the console

**Budget & TPM** prints every amount with the console's one money format: `US$` and the exact decimal the gateway stores, without trailing zeros and with thousands separators, for example `US$0.000008 / UTC calendar day` and `US$0 / US$0.000008` for committed and remaining. Nothing is rounded: `US$0.125000000001` keeps every digit. An amount the gateway cannot read is shown as **Unavailable**, never as `US$0`. The same format is used on the Evals, request log and usage screens, so an amount reads the same everywhere.

## Per-child templates

A **per-child template** gives every child of a parent its own ceiling, without one policy per child: every key of team `acme` gets 20,000 TPM and $5 a day, while the team keeps its cumulative $50 a day. New keys are covered the moment they exist. It needs the `hierarchical_quotas` flag (operator control, off by default, requires `budget_limits` or `tpm_limits`) and is available only with the PostgreSQL quota store.

```yaml
features:
  hierarchical_quotas: true
quotas:
  policies:
    - id: acme-tree
      subject: team
      subject_id: acme
      tpm: 100000          # cumulative parent ceilings (optional)
      budget_usd: "50"
      budget_period: day
      child:
        selector: key      # each key of the team
        tpm: 20000
        budget_usd: "5"    # each key, per UTC day (the parent's period)
```

| Field | Default | Values |
| --- | --- | --- |
| `child.selector` | required | `key` or `user` under a `team`; `team`, `key` or `user` under a `project` or `organization` |
| `child.tpm` | none | 1–100,000,000; not above the parent's `tpm` when both are set |
| `child.tpd` | none | 1–100,000,000,000 (requires `tpd_limits`); not above the parent's `tpd` |
| `child.budget_usd` | none | Positive decimal string, up to six decimal places; not above a hard parent budget of the same period |
| `child.budget_period` | the parent's `budget_period` | `day`, `month`; `week`, `quarter`, `year` with `calendar_budget_periods`; `lifetime` with `lifetime_budget_limits` |

A template needs at least one of `child.tpm`, `child.tpd` and `child.budget_usd`. The policy's own `tpm`, `tpd` and `budget_usd` stay optional: when set, they are the parent's cumulative ceiling over all of its children. `soft_budget`, alert thresholds and temporary increases apply to the parent ceiling only; child ceilings are always hard.

How it is accounted:

- **Independent counters.** Each child has its own counters, named after the parent and the child (`team:acme/key:k1`). Two children never share one, so a busy key cannot use a quiet key's room, and two parents never share one either.
- **One transaction.** A request reserves its child counters and the parent ceilings together, in the same PostgreSQL transaction as every other applicable policy: it fits all of them or none. Concurrent requests of many children serialize on the counters, so no child passes its own ceiling and, when the policy sets its own `tpm`, `tpd` or `budget_usd`, the children together never pass it. A template without parent limits caps each child only.
- **Exact settlement.** Settlement moves the child and the parent by the same measured amount; an unknown outcome keeps both holds, as for any policy.
- **Who the child is.** The child is server-owned identity: the request's key, the key's team, or the user bound to the key by [financial attribution](/docs/features/quota-governance/). A request whose child cannot be established (a key with no attributed user under a `user` template, for example) is refused before any provider call with `422 quota_profile_unsupported (child_identity_required)`, never let through without its child ceiling.
- **Over the limit.** A child counter that refuses answers `429 quota_exceeded` with the template's policy ID and an extra `X-Gateway-Quota-Scope: child` header; a refusal by the parent's own ceiling has no such header.
- **Windows and restarts.** Child counters use the same UTC windows as every other counter (minute, day, calendar periods, lifetime), live in PostgreSQL and survive restarts; expired windows are pruned like the others.
- **Flag off.** With an enabled template in the YAML, `hierarchical_quotas` is required at boot; a disabled template may stay without it. If a console-managed template exists and the flag is later turned off, a request whose enforced dimensions the template limits is refused with `503 quota_unavailable` instead of running under the parent ceiling alone.
- **Editing.** `PUT /api/v1/admin/quota-policies/{id}` replaces the whole policy: a body without `child` removes the template. Read the policy first and send its `child` back to keep it. `child` and its fields cannot be `null`.
- **Realtime.** Each realtime response is reserved like an HTTP request, child counters included; a session whose child cannot be identified opens, and each response is then refused with `quota_profile_unsupported`.
- **Two templates, same parent and child kind.** They share the child counters, and the lower ceiling applies, as two policies on the same subject do.

`GET /api/v1/admin/quota-policies/{id}/children?limit=100` lists the children of one template with their current use and remaining room (minute, UTC day and the child budget period), highest share of its ceiling first; `limit` is 1–1,000 (default 100) and `truncated` says more children have counters. Children that used nothing in the current windows are not listed. The console shows the same under **Budget & TPM → Per-child usage**, and edits the template in the policy editor's **Per-child template** section. Requires `quotas:read`; editing requires `quota_management` and `quotas:manage`.

**Upgrade.** Migration 136 widens the stored charge bound of one reservation from 68 to 132 charges and 64 KiB; it changes no counter or history. A replica of an earlier version does not know `child`: it ignores a template and admits the covered requests without child counters (and a policy write from it drops the block). Upgrade every replica, then enable `hierarchical_quotas` everywhere, and only then add templates. To roll back, remove every `child` block and the flag first.

## Calendar budgets and upgrade

Use `week`, `quarter` or `year` for a calendar USD budget. These are exact named periods, not rolling durations:

| Period | Inclusive start, UTC | Exclusive reset, UTC |
| --- | --- | --- |
| `day` | Current date at 00:00 | Next date at 00:00 |
| `week` | Monday at 00:00 | Following Monday at 00:00 |
| `month` | First day of current month | First day of next month |
| `quarter` | January, April, July or October 1 | First day of next quarter |
| `year` | January 1 | Following January 1 |

Leap years use the actual calendar. For example, on February 29, 2024 the current quarter is `[2024-01-01T00:00Z, 2024-04-01T00:00Z)`, not a 90-day duration. The authoritative clock is PostgreSQL, shared by the replicas. The existing token minute/day periods do not change.

```yaml
features:
  usage_analytics: true
  durable_usage: true
  budget_limits: true
  calendar_budget_periods: true
  quota_management: true
quotas:
  policies:
    - id: platform-quarter
      subject: team
      subject_id: platform
      budget_usd: "1500"
      budget_period: quarter
      alert_thresholds: [80, 100]
```

Replace `platform` with the actual team ID, not its display name. Add approved connection-specific rates as described above; a public price catalog is not that approval. The same `budget_period` field is editable through **Budget & TPM** and `PUT /api/v1/admin/quota-policies/{id}` using the current quota version and base fingerprint. The new-period editor additionally requires valid V15 metadata and `quota_policy_access.calendar_write`; a catalog or flag never grants administrative permission. Commercial classification is supplied by the build; this feature does not choose a free/enterprise allocation.

You may stage a new-period policy while its flag is off. If `budget_limits` is on and that policy applies, inference fails closed with 503 before external work until the flag is enabled or the policy is changed/disabled. The gateway does not silently remove the USD ceiling. Turning off `budget_limits` retains the existing token-only behavior; USD is then not enforced. Check effective status before sending traffic.

For every protected USD subject, the gateway records the same reserved/settled amount in all five calendar windows, even when only day/month enforcement is selected. Only the selected period's ceiling denies the request; the other windows preserve consumption for a later period change. These are five views of one reservation, never five provider charges. Unknown usage remains held. A soft budget changes USD denial, not capture, unknown-hold safety or token ceilings. Threshold alerts belong to the selected policy/window.

### Upgrade from a version before calendar budgets

Migration120 adopts protected consumption from retained live and archived reservations into the current week, quarter and year. It counts each reservation once per money subject, using the original reservation's day window, and preserves the recorded rate/measurement and immutable archived original. Settled usage contributes its exact settled amount; released reservations contribute zero; unresolved reservations retain their hold, or their proven reconciled USD charge. Open reservations receive the additional current-period capture so later settlement/reconciliation adjusts the same counters correctly.

This adoption is **protected gateway history**, not a reconstruction of every provider invoice. Calls that previously ran without USD protection, including token-only calls, have no approved historical money charge to import. Public prices, analytics token estimates and missing proof never become a zero historical cost. The adoption fails atomically on corrupt/conflicting history or accounting overflow; it does not activate partially seeded balances.

1. Drain traffic and stop **all** older gateway replicas and workers that use this database. Keep them stopped through adoption and the coordinated upgrade. An older process already running does not learn the new counter/pruning contract.
2. Take a database backup with the matching encryption/session key material, following [backup and recovery](/docs/operate/operations/). Preserve immutable archives and financial evidence.
3. Run the new version's normal [migration command](/docs/reference/cli/) against that database, with the configured migration timeout appropriate for its retained ledger. Migration120 commits schema and history adoption together, or rolls back. A failure is a reason to investigate the exact data/timeout/capacity problem, not to delete holds or mark the migration applied by hand.
4. Start only the new version, inspect catalog/base adoption and counters, then enable the calendar flag and resume applicable traffic. Do not run mixed old/new financial writers. Validate a protected request and its correlated ledger/status before restoring the full workload.

The new-row capture check rejects old-shaped new USD reservations, but is an additional safeguard, not a rolling-upgrade guarantee. Startup's newer-schema guard also does not fence an old process already running. There is no automatic destructive schema downgrade: use the documented coordinated recovery/backup procedure; an old binary must not be pointed at the upgraded database.

### Read current calendar status

`GET /api/v1/admin/quota-policies/status?status_version=2` opts into a versioned snapshot: quota version, base fingerprint, database observation time, calendar flag and per-policy window start/reset. It keeps those separate from the global configuration version. The console uses that snapshot and shows UTC boundaries and whether USD enforcement is active/blocked. Missing/stale/malformed status never means zero consumption or unlimited headroom. Omitted status version retains the legacy response for existing clients: day/month USD stays unchanged, while a week/quarter/year policy contributes only its configured TPM/TPD fields. A calendar policy with no token limit is omitted from that legacy projection. Use V2 to inspect calendar budgets; the legacy projection does not imply that those budgets are absent or unenforced.

## Lifetime budgets

Use `budget_period: lifetime` for a permanent USD ceiling on an existing financial subject. Enable `lifetime_budget_limits` with `budget_limits`; it is independent of the optional calendar-period flag. The same field is available in YAML, the policy API and **Budget & TPM**. For example, use an actual managed key ID:

```yaml
features:
  usage_analytics: true
  durable_usage: true
  budget_limits: true
  lifetime_budget_limits: true
  quota_management: true
quotas:
  policies:
    - id: integration-total
      subject: key
      subject_id: key_actual_id
      budget_usd: "100"
      budget_period: lifetime
```

Add approved rates for the configured connection as with other budgets. No renewal schedule is created. Changing the policy ID or ceiling, switching periods, deleting a policy and creating it again do not clear a subject’s recorded consumption. A new subject ID is a different financial identity, not a reset of an existing one. There is no spend-reset operation in this profile.

Every protected USD reservation records the same obligation in one lifetime view and the five calendar views. These remain six views of one charge. Lifetime includes settled amounts and held unresolved reservations; proven USD reconciliation can replace the money hold without proving tokens. Traffic previously unprotected in USD is not retroactively priced from analytics or public catalogs.

You can stage a lifetime policy with its flag off. While USD protection is enabled, an applicable lifetime policy then blocks inference with503 before external work; the gateway never silently drops the ceiling. With the flag enabled, an exhausted hard lifetime ceiling returns429 **without Retry-After**, because waiting does not renew it. Other applicable calendar/token ceilings retain their own truthful reset hints. Soft budgets keep their established alert-only USD behavior and hard token limits.

### Upgrade and retained capacity

Migration121 adopts all retained protected live/archive money for each subject, including older years, with exact proofs and existing USD reconciliations. It adds the lifetime capture to every open monetary reservation so later settlement/reconciliation adjusts the permanent counter too. Closed/archive originals and their fingerprints remain unchanged. All older writers/workers must be stopped, a matching database/key backup retained, and the migration must complete atomically before new writers resume; follow the [coordinated upgrade](#upgrade-from-a-version-before-calendar-budgets). Never hand-edit a migration marker or clear counters to force startup.

Lifetime counters have no TTL or safe balance-preserving eviction. There is one additional permanent row per distinct protected financial subject, including each declared end user. Provision storage for that retained cardinality. The existing accounting model uses signed64-bit counters in10^-12USD units: each subject/window must fit within9,223,372.036854775807USD, including unselected views. Adoption or accounting overflow fails closed rather than wrapping, saturating or inventing headroom. A capacity failure needs an explicit accounting/migration solution; deleting history is not recovery.

### Read the lifetime status

Request `GET /api/v1/admin/quota-policies/status?status_version=3`. It carries the quota version/base fingerprint, database observation, both period flags and exact money. Lifetime rows have explicit null `budget_window_start` and `budget_resets_at`; the console displays **Never resets**. Null does not certify complete provider-invoice coverage. The internal fixed bucket identity is not exposed as a claim that coverage started in1970.

StatusV1 keeps day/month money only; V2 adds calendars. Neither publishes an unfamiliar lifetime USD profile: it retains any configured token fields and omits a tokenless lifetime row. V3 is the minimum lifetime-aware profile; temporary allowances require V4. The current console negotiates metadataV18/statusV5 and needs the independent `lifetime_write` capability; selectors1–15 retain calendar-only capability and16 retains calendar/lifetime. Before/after license guards also protect lifetime removal, conversion and YAML adoption. A flag or metadata row does not grant permission.

## Temporary budget increases

A temporary increase raises an existing USD ceiling until an absolute expiry; it does not add a spendable credit or reset consumption. Configure one optional profile per policy:

```yaml
features:
  usage_analytics: true
  durable_usage: true
  budget_limits: true
  quota_management: true
  temporary_budget_increases: true
quotas:
  policies:
    - id: rollout-allowance
      subject: key
      subject_id: key_actual_id
      budget_usd: "100"
      budget_period: month
      temporary_budget_increase:
        amount_usd: "25"
        expires_at: "2027-01-01T00:00:00Z"
```

| Key | What it does |
| --- | --- |
| `quotas.policies[].temporary_budget_increase.amount_usd` | USD added to the policy's ceiling until the expiry, an exact string with up to six decimal places |
| `quotas.policies[].temporary_budget_increase.expires_at` | When the increase ends: a complete RFC 3339 timestamp with its time zone |

Use an actual key ID, approved rates and your intended expiry. The example’s ceiling is125USD per month until that instant, then100USD; it is not25USD to consume once across months. A lifetime policy raises its same permanent ceiling instead. Amounts are exact strings with up to six decimal places. The configured base plus increase must remain within the existing1000000USD policy-ceiling bound. A positive base is required. There is no stacking or future activation schedule.

Expiry is a complete RFC3339 timestamp with an explicit timezone, normalized to UTC; a date alone or a time without a timezone is rejected. Expired profiles may remain as historical configuration. Repeating the same amount/expiry does not move the deadline. In the console, **Budget & TPM** shows base, effective ceiling, expiry and whether the increase was active, expired, staged or disabled at the database observation time. Displayed eligibility is not permission or provider health.

With `temporary_budget_increases` off, the increase is staged/inactive and the **base remains enforced**. Removing an optional allowance cannot weaken the base. Calendar/lifetime feature requirements and every other applicable ceiling still apply. Per-end-user policies raise each covered end user’s individual ceiling, not a shared pool.

### Expiry, reservations and alerts

The gateway locks the applicable counters, then checks the database clock for the final temporary decision before changing balances. A request that waited beyond expiry uses the base, even if it reached the gateway earlier. Existing reservation window identities keep their original capture; the later temporary decision time is stored separately. No workstation clock authorizes the increase.

Consumption and unknown reservations remain intact when an increase expires, is cleared, edited or disabled. A request already admitted can complete and settle after expiry; it is neither canceled nor replayed. A subject already above its restored base is refused until there is legitimate headroom. For lifetime, waiting does not renew that headroom, so its429 still has no Retry-After.

The reservation captures the original policy and the applied effective ceiling, observation and version/provenance. Settlement, reconciliation and threshold alerts use that capture, not a later edited policy or clock. The existing alert identity remains once per policy/subject/window/threshold; editing an increase does not promise a duplicate threshold notification. All calendar/lifetime views remain views of the same charge.

### Edit, clear and audit

The existing versioned policy API and console edit the same optional object. **Omission in an API update preserves its current value under the quota transaction; explicit `temporary_budget_increase: null` clears it.** This prevents an older client from accidentally erasing a field it does not know. YAML absence means no declared increase and follows explicit base adoption. To remove the USD budget, explicitly clear an existing increase too. CAS, audit, administrator permission and the independent `temporary_write` capability apply; a metadata row or flag grants no rights.

Temporary changes have a bounded append-only history at `GET /api/v1/admin/quota-policies/temporary-increases/history`, also available in the budget page. It records the policy, before/after temporary context, actor, quota version, real timestamp and request/trace IDs in the same transaction as the mutation. A **Declared YAML base** entry describes the adopted base even if a console override masks it; an **Effective policy** entry records a managed policy change. No context recorded never means the entire policy was absent or its balance was zero. History does not invent pre-feature configuration values and remains readable by authorized global quota readers when the operational flag is off.

### Upgrade and compatibility

Migration122 adds the bounded adopted temporary-base snapshot/change journal and the larger policy-decision snapshot capacity. Stop every older replica, administrative writer and settlement/reconciliation worker before applying it and creating temporary captures: old JSON readers would ignore the applied ceiling and use the base denominator. Keep the coordinated database/key backup and resume only the new binary. Do not run mixed writers or treat an old binary as a supported schema rollback.

StatusV4 and metadataV17 describe the new profile and effective ceiling. Earlier metadata selectors retain their exact capability shapes. StatusV1–3 keep token fields but hide the USD section of any policy carrying a temporary profile; useV4 for its complete supported quota view. Unknown measurements/status remain unavailable. The general administrative audit and its CSV retain their existing contract; the temporary history is a narrow financial view.

## Require the end user and tags

An end-user limit only counts the requests that declare an end user (there is no budget per usage tag; [attribution groups](/docs/features/attribution-groups/) budget server-decided groups). A request that leaves `X-Gateway-End-User` out is simply not counted against any end user. To close that gap, a **team**, a **key**, or both can require every inference request to declare an end user and usage tags with given names. A request that lacks one is refused before anything else happens to it.

### How to turn it on

```yaml
features:
  attribution_requirements: true   # off by default; enforces every require block
  end_user_tracking: true          # needed by require.end_user
  usage_analytics: true            # needed by end_user_tracking and usage_tags
  usage_tags: true                 # needed by require.tags
usage_tags:
  allowed_values:
    project: [apollo, gemini]
    cost_center: [cc-100, cc-200]
keys:
  - id: checkout-app
    team: platform
    # ...
    require:
      tags: [project]              # this key's requests must also carry project
team_requirements:
  - team: platform                 # every key of the team, whenever it was issued
    require:
      end_user: true
      tags: [cost_center]
```

`attribution_requirements` is the catalog flag (operator control, default `false`). It switches enforcement for every team and key at once and is changed like any runtime flag. Each `require` block is a per-team or per-key setting under it; both start empty, which requires nothing.

| Field | Default | What it requires |
| --- | --- | --- |
| `team_requirements[].team` | required | The team the entry binds, a YAML or console team ID; one entry per team, and its `require` block takes the fields below |
| `keys[].require.end_user`, `team_requirements[].require.end_user` | `false` | The `X-Gateway-End-User` header, one value of 1–128 printable characters. Needs `end_user_tracking`. The OpenAI `user` body field does **not** count: the header is what every end-user control reads at admission (the end-user RPM counter reads only the header). |
| `keys[].require.tags`, `team_requirements[].require.tags` | `[]` | Up to 8 unique usage tag names that the request's merged tags must contain: the `X-Gateway-Tags` header plus the team's defaults (`usage_tag_defaults`). Needs `usage_tags`, and each name must be in `usage_tags.allowed_values` when the requirement is written. Only the name is required; the value is checked by the taxonomy as usual. |

### Team and key: the stricter wins

The request must meet the **union** of the key's requirement and its team's:

- an end user is required when the team **or** the key requires one;
- the required tag names are those of the team **plus** those of the key.

A key's block can only add to its team's. A key with `require: {end_user: false}` in a team that requires an end user still has to send one. A team's requirement binds **every** key of the team at its next request, including keys issued before the requirement was set: managed keys read their team's requirement from PostgreSQL in the same query that authenticates them.

A team's requirement comes from two places, and both apply: the `team_requirements` entry that names it (YAML; the only source for teams declared in YAML) and, for teams created in the console, the requirement stored with the team. A YAML key whose `team` is a console team is bound by that team's stored requirement as well; it is read from PostgreSQL on each of its requests, and a read failure answers `503 attribution_unavailable` without calling the provider.

Keep the union within 8 tag names: a request carries at most 8 usage tags, so a key and team that together require more can never be met.

### What the client must send

```http
POST /v1/chat/completions
Authorization: Bearer gw_...
X-Gateway-End-User: customer-4821
X-Gateway-Tags: {"project":"apollo","cost_center":"cc-100"}
```

A request that lacks something answers **400** before any provider call, quota reservation, rate counter, guardrail or routing classifier:

```json
{"error":{"code":"missing_attribution","message":"This request lacks attribution that its policy requires: the X-Gateway-End-User header (required by the team policy); usage tag project (required by the key policy)"}}
```

The message lists every missing item and says whether the **team**, the **key** or **both** policies require it. It names tag names only, never values. With `end_user_tracking` off, the gateway cannot record an end user, so a requirement for one refuses every request and the message says so.

### Where it is checked

- **Every request admitted under an inference route scope** (`route:<capability>` other than `route:models`): chat completions, Responses, Messages, Gemini, embeddings, images, audio, video, rerank, moderations, OCR, decisions, realtime sessions and realtime client secrets, fine-tuning, token counting and the stored-response, conversation and container routes. These are the same requests rate policies count. The check runs once per request, before the rate limit.
- **Semantic fallbacks** are checked like a client request at their destination. They carry the client's `X-Gateway-End-User` and `X-Gateway-Tags`, so a request that met the requirement keeps meeting it. The fallback of one of the gateway's own in-process calls (below) is exempt like the call itself.
- **Batches** are checked when created: a batch line carries no client headers, so it cannot declare an end user and has only the team's default tags. A key whose requirement lines could not meet gets `400 missing_attribution` from `POST /v1/batches`, naming what is missing. Lines run later as the gateway's own work and are not checked one by one; a requirement added after the batch was created does not stop it.
- **Not checked:** the gateway's own in-process calls made for a request that was already admitted (provider guardrails, semantic cache embeddings, routing classifier and embeddings) or with no client present (evaluations, m7 ai). `GET /v1/models`, MCP, agents, files and vector stores are not inference routes.
- **Realtime from a browser:** a browser WebSocket cannot set custom headers, so a key that requires an end user cannot open a realtime session with an ephemeral client secret. Open it from a server that sends the header.

### Console and API

- **Keys:** **Virtual keys → Create key** has the attribution fields; **Attribution** in a managed key's **Manage** menu edits its own requirement. API: `require` on `POST /api/v1/admin/keys`, and `PUT /api/v1/admin/keys/{id}/require` with `{"require": {...}, "version": <require_version>}`. Global administrators edit any key, team administrators the keys of the teams they administer, so a team administrator can clear a key's own requirement; a requirement that team administrators must not relax belongs on the team. YAML keys take `require` from the configuration.
- **Teams:** the **Attribution** action on a console team card (global administrators). API: `PUT /api/v1/admin/teams/{id}/require` with the team's current `version`, which it advances. YAML teams answer `409 yaml_owned`; use `team_requirements`. Team listings show `require` (stored) and `yaml_require` (from `team_requirements`, when present).
- Writing a non-empty requirement while a flag it needs is off, or with a tag outside the taxonomy, answers `400 invalid_require`. Clearing a requirement is always accepted. A stale version answers `409 version_conflict`.

### Upgrade notes

Migration 113 adds the stored requirements to managed keys and console teams, empty for every existing row; nothing changes until `attribution_requirements` is on and a requirement is set. Configuration validation checks the shape of `require` blocks and `team_requirements` entries (unique valid tag names, at most 8, one entry per team); the flags and the tag taxonomy stay runtime settings, so `attribution_requirements`, `end_user_tracking` and `usage_tags` can always be switched off and the taxonomy edited. A requirement that the current flags or taxonomy make impossible to meet (for example a tag later removed from `usage_tags.allowed_values`) refuses its requests, and the `missing_attribution` message says why, until the requirement, the flag or the taxonomy is fixed. The admin API refuses to write such a requirement (`400 invalid_require`).

## Approved rates

The budget uses `quotas.rates`, a list of rates that **you approve** for enforcement, separate from the reference prices of [automatic pricing](/docs/features/automatic-pricing/). That way, a change in a public catalog does not change your limit without your review.

- Each rate identifies the provider, the exact upstream model and the connection:

  | Key | What it does |
  | --- | --- |
  | `quotas.rates[].provider_id` | ID of the configured provider connection the rate prices |
  | `quotas.rates[].model` | Exact upstream model ID the provider bills |
  | `quotas.rates[].connection` | Hash of the provider's protocol, Base URL and API version, shown in the console; a rate stops applying when the connection changes, so a new endpoint needs a new approval |
  | `quotas.rates[].reasoning` | Marks a model that reasons by default: an OpenAI-compatible chat call to it must carry `max_completion_tokens`, which bounds its reasoning, since `max_tokens` may not |
  | `quotas.rates[].revision` | Required identifier of this approval; give it a new value when you approve new prices |
- Text uses `input_usd_per_million` and `output_usd_per_million`. Image, audio and rerank use `unit`, `variant` and `unit_usd`.
- A realtime model adds `audio_input_usd_per_million` and `audio_output_usd_per_million` (both or neither), for the audio tokens its responses report separately.
- Prompt caching adds `cache_read_usd_per_million` and `cache_write_usd_per_million`, each optional. When the answer reports tokens read from or written to the provider's prompt cache, they are charged at these prices and the rest of the input at `input_usd_per_million`. Without the matching price, such an answer **keeps its reservation**: cached tokens are never charged as plain input. The write price is the five-minute write; a one-hour write uses `cache_write_1h_usd_per_million`, or keeps the reservation without it. On a TPM-only policy, cached tokens simply count as tokens.
- **Long context** adds a higher tier that providers bill for a whole request whose input crosses a threshold:

  ```yaml
  long_context:
    threshold_tokens: 200000          # input tokens, cache included
    input_usd_per_million: "6"
    output_usd_per_million: "22.5"
    cache_read_usd_per_million: "0.6" # optional, like the base tier's cache prices
  ```

  The tier is absent by default. `threshold_tokens` accepts 1–100,000,000; input and output prices are required when it is present, and the cache prices are optional. A request whose input exceeds the threshold settles input, output and cache at these prices. A reservation whose input estimate exceeds the threshold is priced at the highest prices of both tiers, since the answer may fall on either side.
- **The model's maximum output** is optional: `max_output_tokens` on a text rate (1–10,000,000) is the most output tokens the model writes in one answer, as its provider documents it. A request that asks for more is refused with `output_limit` before the call, instead of earning the provider's refusal after it, which would leave the reservation held. Without it, only `quotas.settings.max_output_tokens` bounds the limit. The gateway does not read this number from a model catalogue: catalogues are advisory and may be absent, and a rate is what you approved.
- **Images** need `image_input_tokens`: your ceiling of input tokens one image can bill on this model, taken from the provider's pricing rules (for example the largest tile count of the model's own tiling), and optionally `max_images` per request. `image_input_tokens` defaults to 0 (images are not approved); the allowed ceiling is 1–1,000,000. `max_images` defaults to 0 (no additional per-rate cap), accepts 1–1,000, and never bypasses the profile's 1,000-image bound or request-size limits. Each image is reserved at the larger of that ceiling and the tokens the provider documents for the image's size, read from its PNG, JPEG, GIF or WebP header (see [image sizes](/docs/features/quota-protocols/#image-sizes)), and settled from the prompt tokens the provider reports. Image URLs are accepted where the provider documents that it bills a URL as an image only (the OpenAI API, Claude Messages on the Anthropic API), reserved at its documented maximum per image; on any other connection they need `image_urls: true`, your statement that the ceiling bounds whatever such a URL bills. Without the ceiling, a request with images is refused with `422 quota_profile_unsupported` (reason `image_ceiling_not_approved_or_exceeded`), under a budget or a token ceiling alike: nothing else bounds what an image bills.
- **`image_floor: ceiling`** (with `image_input_tokens`) reserves each image at your ceiling alone, overriding the provider's documented tokens for its size: for a model whose provider changed its rule before the gateway's table follows. Without it, each image takes the larger of the two.
- **Service tiers** add `service_tiers` (`priority`, `flex`, `batch`), each with `input_usd_per_million`, `output_usd_per_million` and the optional cache prices. A chat or Responses request that asks for a tier reserves at the higher of the tier's and the standard prices and is refused (`service_tier_not_approved`) when the rate does not approve it; a request without `service_tier` reserves at the highest approved tier, `default` at the standard prices alone. Settlement uses the tier the provider reports; a tier without approved prices keeps the reservation. See [service-tier pricing](/docs/features/service-tier-pricing/).
- `response_models` accepts up to eight additional IDs that the provider may return in the response (for example, the dated snapshot of an alias). No wildcards.
- `revision` is an identifier such as `rev-1`. Changing the target invalidates the approval; a new rate needs a new `revision`.

## Global and provider budgets

| Flag | Default | What it turns on |
| --- | --- | --- |
| `global_budget_limits` | `false` | The `global` subject: one monetary ceiling shared by the whole installation; requires `budget_limits` |
| `provider_budget_limits` | `false` | The `provider` subject: a monetary ceiling on one exact provider connection; requires `budget_limits` |

A global ceiling covers supported protected inference across every replica sharing this gateway database. A provider ceiling covers one configured provider **connection ID** across its models, keys and teams. It does not group all connections using the same vendor or protocol. Both are monetary policies; they do not add TPM/TPD limits or grant model access.

```yaml
features:
  budget_limits: true
  global_budget_limits: true       # default false; requires budget_limits
  provider_budget_limits: true     # default false; requires budget_limits
quotas:
  policies:
    - id: installation-month
      subject: global
      subject_id: gateway           # exact fixed ID; not a hostname or replica ID
      budget_usd: "1000"
      budget_period: month
    - id: openai-connection-month
      subject: provider
      subject_id: openai            # an exact existing providers[].id
      budget_usd: "500"
      budget_period: month
```

The example assumes an existing `providers[].id: openai` and the normal usage/storage prerequisites above. The provider ID follows the existing financial identifier profile:2–64 lowercase ASCII letters/digits/underscore/hyphen, starting with a letter, and must exist in the reviewed provider catalog. Both new subjects require positive USD up to1000000, an existing supported budget period, and zero/absent `tpm` and `tpd`. They support the same optional temporary increase, soft-budget alerts and exact approved rates. A call must satisfy **every** matching global, selected-provider and existing owner/model ceiling in the same reservation transaction. The counter views are not separate bills.

With an applicable global/provider ceiling configured but its corresponding flag off, protected inference fails closed with503. Staging and authorized recovery reads still work. This differs from turning off a temporary allowance, which restores the valid base ceiling. Calendar/lifetime flag requirements still apply. Editing, disabling, reverting or recreating a policy never resets its shared balance or releases an unknown hold.

### Provider identity and supported traffic

The provider is the actual selected upstream connection, captured in the reservation. Credential-pool entries are not separate providers. Historical captures settle against their original connection and approved rate even if that provider has since been removed after its policy was cleared.

The existing supported protected native, translated, media/transcription and realtime paths share this reservation boundary; async operations retain their hold until terminal proof. A routing profile without a proven selected provider cannot skip a configured provider ceiling: candidate IDs may detect applicable protection and trigger the existing unsupported-profile refusal **before sending**, but never select the first target or invent its cost. This change does not enable new retry/fallback financial profiles. Existing operator guardrail/moderation exemptions and traffic without an approved monetary profile are not silently priced. The global view covers protected gateway inference, not every HTTP/MCP/tool expense or a complete provider invoice.

### Management and compatibility

The existing quota API and **Budget & TPM** editor use these same policies. The console fixes the global ID to `gateway` and selects a provider from its reviewed configuration. Provider references, including disabled policies, are checked against effective configuration under the existing control/quota version fence. Removing an in-use provider is refused; reverting a console provider to a YAML provider of the same ID keeps the reference valid. Startup or refresh cannot publish an orphaned configuration; a failed refresh preserves the last valid snapshot.

Current console metadata isV18 with separate `global_write`/`provider_write` capabilities; earlier selectors retain their exact shapes. StatusV5 reports both operational flags and the new monetary subjects. V1–4 omit unfamiliar global/provider rows, while preserving their existing old-subject profiles. History keeps its source/known-context distinctions; it does not create records for a time before the feature existed. Flags, commercial classification and permissions remain separate.

### Upgrade, retained coverage and contention

Migration123 adopts **one protected monetary obligation per original reservation**, not each copy of its subject/window views. It validates live/archive identities, archive hashes and original provider/rate agreement. Lifetime uses all retained protected history; current calendar views include the retained obligations in those windows. Every old open/unknown reserve receives all six new global/provider views at its original window identities, with backing counters even for ended windows and its attested reconciliation baseline. These buckets stay pinned until resolution. No reserve is released or prior unprotected traffic assigned an advisory cost.

Stop every pre123 financial writer, administrator writer and settlement/reconciliation worker first; take the coordinated database/key backup, migrate and resume only new binaries. Older live writers are not fenced by a newer startup-schema check. Corrupt, ambiguous or overflowing history fails atomically; do not discard holds or manually mark the migration applied. There is no supported old-binary rollback on the migrated state.

Global counter rows serialize the shared financial boundary across replicas. This is an explicit correctness/throughput tradeoff; existing pool/admission controls still apply, and final whole-branch load qualification remains separate. Historical coverage is retained **protected** accounting, not a reconstruction of all provider charges.

## Quota settings

Bounds on protected requests and on the overrun alert, with defaults, set under `quotas.settings` in the YAML and replaceable from the console (**Budget & TPM → Quota settings**) or the API; a zero or omitted field takes its default, and a revert returns to the YAML. Read effective values and `settings_source` with `GET /api/v1/admin/quota-policies`; replace or revert them with `PUT` or `DELETE /api/v1/admin/quota-settings`, using the current `version` and `base_fingerprint`. Writes require an authorized administrative session and `quota_management`, use CSRF protection and version checks, and are audited. They are not part of the approval fingerprint, so a YAML change needs no adoption.

| Setting | Default | Bounds | What it does |
| --- | --- | --- | --- |
| `quotas.settings.max_input_tokens` | 2,000,000 | 1-100,000,000 | Most input tokens one reservation may estimate, images included (`input_limit`) |
| `quotas.settings.max_output_tokens` | 1,000,000 | 1-10,000,000 | Most output tokens one reservation may hold. A request reserves the output limit it asks for; one that asks for more is refused (`output_limit`). A rate's `max_output_tokens` declares a lower maximum for its model |
| `quotas.settings.max_items` | 1,024 | 1-100,000 | Most messages, contents or input items in one request (`item_limit`) |
| `quotas.settings.max_tools` | 128 | 1-4,096 | Most function tools, or Gemini function declarations (`tool_limit`) |
| `quotas.settings.max_content_parts` | 128 | 1-4,096 | Most parts or blocks in one message (`content_part_limit`) |
| `quotas.settings.overrun_alert_tolerance_percent` | 0 | 0-1,000 | The `quota_reservation_overrun` alert fires only above this share of the reservation, in tokens or USD; the ledger records every overrun |
| `quotas.settings.overrun_alert_dedupe_seconds` | 0 | 0-86,400 | 0 raises one alert per reservation; a window folds only the same model and identical billed-policy subject set. Once any channel queues an event, or its metadata list fills, later overruns start another event |

A request over a limit gets `422 quota_profile_unsupported` with the reason in parentheses, before any provider call. Each reservation keeps the alert settings it was taken under.

A folded event records `count` and `reservation_ids`. Its reserved/measured amounts and `request_id` describe the latest included reservation, not a sum for the group; use the ledger for financial totals. Folding keys include every billed policy subject (such as team, key, user, project, organization or end user), independent of counter dimension. Queuing and folding serialize on the event row, so a channel never receives details that can later change. Delivery retries may repeat a notification; receivers should honor its [idempotency key](/docs/features/alerting/#how-delivery-works).

## How the reservation works

1. The key is authorized (route, model, access policy).
2. The gateway estimates the maximum the call can consume and **reserves** that amount in every applicable policy, in a single transaction: it reserves in all of them or in none.
   - Input: `payload bytes + tool and output schemas once more + 1024 × (messages, tools and tool calls) + 4096`, plus each image at the larger of the rate's `image_input_tokens` and the provider's documented tokens for it, up to the `max_input_tokens` [quota setting](#quota-settings) (2,000,000 by default). Byte-level tokenizers emit at least one byte per token, so the bytes bound the text; schemas count twice because chat templates re-serialize them; 1024 per item covers each message's template; 4096 covers a provider's fixed preamble, such as the system prompt it adds when tools are present.
   - Output: the request's `max_tokens` (or `max_completion_tokens`), required, reserved as the request asks for it: its worst case. There is no fixed cap: a limit above `quotas.settings.max_output_tokens` (1,000,000 by default), or above the `max_output_tokens` its approved rate declares for the model, is refused with `output_limit` before the call. A coding agent that asks for 128,000 output tokens on every call therefore reserves 128,000 at the output price; give the budget room for it, or lower the limit with the target's [`max_output_tokens`](/docs/features/request-parameter-policy/). Where `max_tokens` may not bound reasoning, a call that asks for reasoning must use `max_completion_tokens` (see [protected profiles](/docs/features/quota-protocols/#agents-what-the-chat-profile-accepts)); a rate with `reasoning: true` requires it on every OpenAI-compatible chat call.
   - With input guardrails on, the estimate uses the request as they rewrote it.
   - Money: input at the highest input-side price the rate approves (a cache write usually costs more than plain input), output at the output price, so no mix of categories the answer can report costs more than the reservation.
3. Only after the reservation is confirmed does the call go to the provider.
4. With a complete and valid response, the reservation is swapped for the real usage reported by the provider: a smaller difference goes back to the balance; a larger one is debited in full. The response is complete once the provider's answer has ended, even if the client disconnects right after. When the gateway translates the provider's answer (Bedrock, Anthropic, Gemini or Cohere behind the chat route, or any translated route), the measurement is the provider's own native usage, read by the adapter before translation; see [protected profiles](/docs/features/quota-protocols/#translated-providers).
5. If the call never went out, the reservation is released. If it went out and something went wrong (timeout, cancellation before the answer ended, truncated response, missing counters), **the reservation stays**, because the provider may have charged for it. A stream whose client disconnects is such a cancellation; with [`stream_settle_on_disconnect`](/docs/features/stream-usage/#when-the-client-disconnects) the gateway reads the provider's answer to its end instead and settles the measured amount. A reservation that can never be reconciled is given back only by an administrator's [audited manual release](/docs/features/quota-finance/#releasing-an-unknown-reservation-by-hand).

Practical consequences:
- The sum of reservations never exceeds the limit. Real usage can, if the provider reports more than the estimate; the excess is debited in full, shows as `overrun_tokens` in the ledger and the proof, and raises the `quota_reservation_overrun` [alert](/docs/features/alerting/) event, written with the settlement so none is lost.
- `X-Request-Id` can repeat; each request has its own internal ID in the ledger.
- A crash neither releases reservations nor repeats calls to the provider.
- A reservation uses the rates and windows in force when it was made; editing the policy afterwards does not rewrite the past or reset consumption.
- Switching a protected policy between supported calendar periods reuses the consumption already recorded in that calendar, including outstanding holds. See [calendar budgets and upgrade](#calendar-budgets-and-upgrade).
- Each replica prunes, once an hour, the counters of windows that ended more than an hour earlier, in small batches that never wait on admission or on another replica. A window still referenced by an open reservation (reserved or unknown) is kept until that reservation settles or is reconciled. Without the pruning, every end user an application declares would leave one row per window forever.

With no policy applicable to a key, nothing changes for it. With a policy, a call that the gateway cannot measure safely is **rejected before sending**, not let through without control.

**One exemption: the moderation guardrail's check.** A [moderation guardrail](/docs/features/guardrails/#moderation-model) sends the request's text to a moderations alias through the gateway, as the caller. Moderation has no quota profile, so that call would be refused (`422 quota_profile_unsupported`) under every policy that applies to the caller and the guardrail would fail every request. The check is the gateway's own call, made because the operator configured it, so it is exempt from this admission:

- no reservation, no `422`, and nothing counted against any budget, TPM or TPD, whichever subject the policy names (key, team, user, project, organization, end user, or the moderation alias);
- the guarded request itself is reserved, settled and refused over the limit as usual. Input guardrails run before that reservation, which is estimated from the request as they rewrote it. So that a provider that bills moderation is not charged for a check of a request already bound to be refused, the gateway first asks, right before the first moderation check and without reserving anything, whether this admission is certain to refuse the request whatever the guardrails do to its text: what settled requests already spent on an applicable calendar budget or TPD counter leaves no room for the smallest reservation the request could take (its output limit plus the fixed 4,096-token input allowance, with its images and shape), or a ceiling is below that reservation by itself. Then the request answers `429 quota_exceeded` for that policy, with the `Retry-After`, `X-Gateway-Quota-Policy` and `X-Gateway-Quota-Dimension` this admission uses, and neither the moderation provider nor the model's provider is called. The precheck applies the admission's own comparison to that lower bound and counts only what cannot free first: not the reservations of requests in flight, not a TPM minute, and not a calendar window that ends within the time the checks and the admission can take (7 seconds per provider check, plus 5). So it never refuses a request the admission would admit, short of an operator action in those seconds. Anything less than certain (room smaller than this request's estimate, room held only by requests in flight, a profile refusal, storage trouble, a quota store other than PostgreSQL) runs the check and leaves the answer to the admission, which then refuses after the moderation call as before; the [guardrail page](/docs/features/guardrails/#moderation-model) has the details;
- a policy whose subject is the moderation alias refuses every direct call to it (`422`) and never applies to guardrail checks;
- the check still appears in the request log and the usage ledger under the caller's key and team, with the request ID `<request_id>.guardrail` (`.guardrail-output` on the answer) and tokens and cost unknown. A provider that bills moderation charges the connection's account; that cost is outside the budget and visible only on the provider's bill;
- it is not counted toward the caller's [RPM](/docs/features/access-control/#request-limits-rpm) either; the guarded request is, once.

Only that in-process call is exempt. A client calling `/v1/moderations` directly under an applicable policy still gets `422 quota_profile_unsupported`, and no header or body field can claim the exemption; the gateway's other in-process calls (semantic fallbacks, routing embeddings, evaluations, batch lines) go through this admission like a client request.

## Background responses

A Responses request with `background: true` answers at once, before the model has produced anything, so its reservation cannot be settled with that answer. Without the flag, a budget or TPM policy refuses it with `422 quota_profile_unsupported` (`unsupported_parameter`). With the operator flag `quota_background_responses` (off by default; requires `responses_lifecycle` and `budget_limits` or `tpm_limits`, and the PostgreSQL store):

- **At create** the request is reserved like any other Responses call (same estimate, same `429 quota_exceeded` when a limit is reached, before the provider is called). `stream` must be `false` and `store` must not be `false`. The reservation stays open, bound to the provider's response in a durable row.
- **When it ends** the reservation settles from the provider's own response object, the first time any replica sees it terminal:
  - a client `GET /v1/responses/{id}` or `POST /v1/responses/{id}/cancel` (the object is read before it is returned);
  - or the background worker, which asks the provider every `charge_accounting.background_poll_seconds` (default 30, 5–3600) about the responses still open.
- **What it settles to:**

| The provider shows | The reservation |
| --- | --- |
| `completed` or `incomplete` with usage the approved rate prices | Settled at the exact usage |
| `cancelled` or `failed` with no output and no usage, never seen `in_progress` | Released |
| `cancelled` or `failed` with no output and no usage after it was seen `in_progress` (it may have billed its prefill) | Held as unknown |
| `cancelled` or `failed` with usage | Settled at that usage |
| Anything else terminal (a hosted tool, another model, an unpriced category) | Held as unknown, for [reconciliation](/docs/features/durable-usage/) |
| Nothing terminal within `charge_accounting.background_max_age_seconds` (default 86400, 600–604800) | Held as unknown; the worker stops asking |

- **Once only:** the store decides the first terminal observation and ignores the rest, so a repeated `GET`, the worker and another replica never charge twice. A replica restart loses nothing: the row and the reservation are in PostgreSQL, and any replica settles them.
- **Delete:** `DELETE /v1/responses/{id}` on a response whose reservation is still open answers `409 background_response_pending`; cancel it or wait until it ends. When the tracking state cannot be read, it answers `503 background_state_unavailable` instead of deleting.
- **Workers:** each pass leases the responses it polls; a replica only gives back its own lease. A row that keeps failing never blocks the expiry of the others. Ended rows are removed 31 days after they end.
- **Overrun:** a settlement above the reservation's tokens is logged as `quota_reservation_overrun` (`source: background_response`) and debited in full.
- **Connection:** the response is only asked about on the provider connection it was created on. If that connection changes or disappears, the reservation waits, then expires as unknown.
- **Receipts:** with `single_charge_settlement`, the create's receipt is not linked to the reservation (it settles later, from the terminal response, not with the receipt).
- **Console:** **Logs → Delivery receipts → Background responses** shows the poll interval, the maximum age and how many background responses are open, settled, released, held or expired (`background_responses` in `GET /api/v1/admin/durable-usage`).
- **Turning it off** stops the polling and the settlement on `GET`; open reservations stay held, and the worker still holds those past their maximum age as unknown, so none stays open forever.
- **Upgrade:** migration 179 adds the tracking table. An older binary rejects the flag name and the two `charge_accounting` fields in YAML: remove them before rolling back; open reservations then stay held until a reconciliation.

## Realtime

A [realtime](/docs/features/realtime/) session is not reserved as a whole: **each response inside it** is reserved, settled and, when its outcome is unknown, held, like an HTTP request.

- The connection checks only that quota storage answers (`503 quota_unavailable` otherwise) and, under a budget, that the model's approved rate has `audio_input_usd_per_million` and `audio_output_usd_per_million` (`422 quota_profile_unsupported` otherwise).
- Each `response.create` (or each `response.created` the provider starts by itself) is reserved with the estimate described in [realtime](/docs/features/realtime/#the-reservation), priced at the higher of the text and audio prices. A refusal drops the request (or cancels the provider's response) and sends the client an `error` event with `budget_exceeded`, `tpm_exceeded` or `tpd_exceeded` and `retry_after`; the session stays open.
- `response.done` settles it: TPM with the token totals, the budget with text and audio tokens each at its own approved price. Cached input is charged at the full price.
- A response cut by the end of the session keeps its reservation, like an HTTP answer cut mid-stream.

## Responses

| Situation | Response |
| --- | --- |
| Limit exceeded | `429 quota_exceeded`, with `Retry-After`, `X-Gateway-Quota-Policy` and `X-Gateway-Quota-Dimension`; the message names the policy and when it resets and, for the caller's own ceiling (its key, team, user, end user or a per-child counter), the exact limit: `Budget limit exceeded: policy tiny-budget allows US$0.000008 per UTC calendar day; it resets at 2026-11-24T00:00:00Z` (`Token limit exceeded: policy tpm allows 1000 tokens per minute; …`; a lifetime budget says it never resets). A global, provider, model, organization or customer ceiling is the operator's financial inventory: its refusal names the policy and the reset only (`Budget limit exceeded: policy global-monthly; it resets at …`). With [`span_store`](/docs/features/traces/) the request span has a `quota_refused` event with the same policy, dimension, reset and, under the same rule, limit |
| Profile or rate without coverage | `422 quota_profile_unsupported`, before sending to the provider |
| Database unavailable or configuration base diverged | `503` |
| Realtime response over a limit | An `error` event inside the session (`budget_exceeded`, `tpm_exceeded`, `tpd_exceeded`), not an HTTP status |

## Console and API

The **Budget & TPM** menu uses the same API:

| Endpoint | What it does |
| --- | --- |
| `GET /api/v1/admin/quota-policies` | Policies, version, fingerprint and connections |
| `PUT` / `DELETE /api/v1/admin/quota-policies/{id}` | Create, edit or revert to the YAML |
| `PUT` / `DELETE /api/v1/admin/quota-rates` | Replace the approved rates or revert to the YAML |
| `PUT` / `DELETE /api/v1/admin/quota-settings` | Replace the [quota settings](#quota-settings) or revert to the YAML |
| `POST /api/v1/admin/quota-policies/adopt-base` | Adopt a new YAML without resetting balances |
| `GET /api/v1/admin/quota-policies/status` | Committed balance and next reset |
| `GET /api/v1/admin/quota-policies/ledger` | Reservations, paginated, without prompts or secrets |
| `GET /api/v1/admin/quota-policies/{id}/children` | Current use of each child of a [per-child template](#per-child-templates) |

- **Who can:** admin edits; global viewer and operator read. Team roles do not see the financial inventory.
- **Did the YAML change?** The base fingerprint diverges and admission stays blocked until an admin adopts the new base. This prevents an old replica from applying the old configuration again.
- **Committed balance** includes open, unknown and settled reservations; it is not confirmed spend. In a TPM-only policy, `budget_applied` is `false` and `reserved_usd: "0"` does not mean a free call.
- **API reference**, in the console, has ready-made examples.

## Turning it on and off safely

- Enable it on every replica before relying on the limit: replicas without enforcement do not respect the ceiling.
- Turning it off lets new calls through without a reservation, but does not erase earlier commitments. Calls made without a policy are not charged later, when a new policy appears.
- To go back to an earlier gateway version, first remove the flags, fields and overrides it does not know. Do not delete balances or migrations.

## Limits

- The reservation is a conservative estimate, not a tokenizer, and it does not guarantee the amount on the external invoice.
- The gateway does not control provider price changes, charges from another source or wrong provider counters.
- `/v1/models` and MCP do not consume these limits.
- Budgets and TPM do not limit how many requests run at once; for that, use a [concurrency cap per key or team](/docs/features/access-control/#concurrent-requests-per-key-and-team).
- Alerts stay in the console; for email, Slack or a webhook, use [alerts](/docs/features/alerting/).

## See also

- [Attribution, TPD and alerts](/docs/features/quota-governance/).
- [Protected profiles](/docs/features/quota-protocols/): what each type of call requires.
- [Financial reconciliation](/docs/features/quota-finance/) and [billing imports](/docs/features/native-billing-imports/).
- [Asynchronous video](/docs/features/quota-video/).


## Configuration and price semantics

Quota policy identities, owners, approval fingerprints and rates remain typed domain data. Shared [parameter definitions](/docs/reference/parameter-registry/) consolidate consumed validation/defaults; they do not approve a rate or activate enforcement. Protected rates and budgets use validated decimal strings, separate from the advisory price catalog and valuation adjustments. Existing managed changes retain version, audit and approval checks; file changes retain their documented rollout/adoption requirements.

The quota-settings editor binds a draft to the version and base fingerprint that were reviewed when it was opened. A concurrent update returns a conflict and keeps that draft; cancel and reopen to review the new state. A draft closes after a successful save and is discarded on observed loss of access or invalid configuration metadata.
