orq.aiAdvent of RoutingDocs

Door 14 · still sealed

Hands off the wax, elf. This door opens on Dec 14.

-days--hours--min--sec

Rudolph is still polishing this one. Back to the calendar

Door 14 · Dec 14 Budgets & alerts

The workshop budget

Give one API key a daily spending cap, get an email at 80%, and know exactly which 429 your app sees at 100%.

Ten days to Christmas Eve, in the counting house. Santa holds last night's model bill at arm's length, and it still reaches the floor.

  1. Santa

    Ledger! Why is the bill so high? I was asleep. The whole workshop was asleep!

  2. Ledger

    Not everyone. The test script on the advent-test key ran all night. I counted its tokens like candy canes, and we ran out of candy canes.

  3. Santa

    Then take that key away! No, wait. I need those tests running by tonight.

  4. Ledger

    Keep the key, put it on an allowance. Five dollars a day. At 80% I get an email. At 100% it gets a 429 until midnight UTC.

  5. Santa

    An allowance. Like the reindeer. Fine, but if my tests hit that 429 tonight, it comes out of your stocking.

clientYour appkey: advent-testorq.aiWorkshop budget$5 / day · alert at 80%providerModelclaude-haiku-5-5blocked429 responsecost_budget_exceededdownnotifierLedger's inboxone email per periodunder capat 100%past 80%
  1. clientYour appkey: advent-test
  2. orq.aiWorkshop budget$5 / day · alert at 80%
  3. providerModelclaude-haiku-5-5
    blocked429 responsecost_budget_exceededdown
  4. notifierLedger's inboxone email per period
Each call checks the budget on the way in and pays on the way out: under the cap it reaches the model, crossing 80% emails Ledger once, and at 100% the next call bounces with a 429.

How it works

Ledger’s fix is one budget on one key. A budget ties spending limits to a scope, and the router checks it on every request that matches:

  1. Scope. Pick what the budget applies to: Workspace, Project, Identity, API Key, Provider or Model. Only one budget is allowed per target.
  2. Period limits. Pick a reset period and at least one limit: cost in USD (limits.amount), tokens (limits.token_limit) or requests per minute (rate_limit.requests_per_minute).
  3. Check, then settle. Before a request starts, the router checks that the budget is not fully used. After it completes, its cost and tokens settle into every matching budget. Once cost or token usage reaches 100%, matching requests get 429 Too Many Requests until the period resets. A requests-per-minute limit blocks only for the rest of its 60-second window.
  4. Alerts. After each request, the router compares cost usage with your alert thresholds and messages the notifiers you attached: email, Slack or a webhook. Each alert fires at most once per period.

A new budget starts enforcing on the next request. Spend from before it existed does not count.

Try it with curl

Budgets are managed with a Management Key that has the Budgets permission; project-scoped API keys cannot manage budgets. Creating the notifier also needs the Notifiers permission on that key. In the console, go to Settings > Organization > Budgets (Admin members only).

First, a workspace-wide email notifier (leave out project_id; budget alerts accept only workspace-scoped notifiers). Note the _id in the response:

curl -X POST https://my.orq.ai/v2/notifiers \
  -H "Authorization: Bearer $ORQ_MANAGEMENT_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "display_name": "Workshop books",
    "type": "NOTIFIER_TYPE_EMAIL",
    "emails": ["ledger@example.com"]
  }'

Then the budget on the key, with an alert at 80%:

curl -X POST https://my.orq.ai/v2/budgets \
  -H "Authorization: Bearer $ORQ_MANAGEMENT_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "scope": {"api_key": {"api_key_id": "<key id>"}},
    "limits": {"period": "BUDGET_PERIOD_DAILY", "amount": 5},
    "alerts": [
      {"threshold_percent": 80, "notifier_ids": ["<notifier id>"]}
    ]
  }'

The same flags exist in the CLI: orq budgets create --scope ... --limits ... --alerts .... To unblock by hand: orq budgets reset-consumption <budget-id>.

Budgets do not work on legacy API keys, the ones created before the current key model. Create a new key and scope the budget to it.

Reset periods

Period Resets at
Daily Midnight UTC
Weekly Monday midnight UTC
Monthly 1st of the month, midnight UTC
Yearly January 1st, midnight UTC
One-time Never

Use a Monthly budget on an Identity to cap spend per customer, and a budget on a staging or CI key so it cannot eat production credits. Use One-time with an expiration date (expires_at) for a time-boxed experiment.

When the budget runs out

The 429 body carries a code (cost_budget_exceeded, token_budget_exceeded or requests_per_minute_exceeded), the exceeded dimension, and scope_kind plus scope_target_id for the budget that said no. Only requests that match that budget are blocked.

The router does not retry cost and token budget 429s (cost_budget_exceeded, token_budget_exceeded). To unblock before the reset, an admin raises the limit, which works at once, or calls POST /v2/budgets/{budget_id}/reset-consumption. Raising the limit does not remove existing usage. Resetting consumption also re-arms the alerts, so the 80% email can fire again in the same period.

When a matching budget sets a cost limit, the X-RateLimit-Remaining-Cost response header tells your app how many dollars are left in the period.

Nice list

  • Give staging and CI keys their own budget, so a test run cannot eat the credits production needs.
  • Expect one email per threshold per period. Each alert fires at most once, then re-arms on reset or when you change the limit.
  • Match on the code field of a 429, not the message: cost_budget_exceeded, token_budget_exceeded or requests_per_minute_exceeded.
  • Read X-RateLimit-Remaining-Cost on each response. When a matching budget sets a cost limit, it tells your app how many dollars are left before the 429.

Naughty list

  • Retrying a cost_budget_exceeded error. Budget 429s are not retried: they clear only when the budget resets, is raised, or is reset by hand, so your retry loop just knocks on a locked door.
  • Adding an alert on tokens. Alerts track cost only: a BUDGET_ALERT_DIMENSION_TOKENS alert is rejected, and requests-per-minute limits never alert.
  • Creating a second budget for the same key. Only one budget is allowed per target, and the API answers 409.
  • Managing budgets with a project-scoped API key. Those keys cannot touch budgets: use a Management Key with the Budgets permission.

Elf's challenge

Put a test key on pocket money: a One-time budget of a few cents. Spend it, then send one more request. What status and code come back, and is there a Retry-After header?

Stuck? Ask Ledger for a hint

A 429 with code cost_budget_exceeded and dimension cost. No Retry-After: a One-time budget never resets on a clock, so it stays blocked until an admin raises the limit, resets consumption, deletes the budget, or its expiration date passes.

Christmas crackerWhat do Santa's list and a workshop budget have in common?Pull it for the punchline

Both get checked twice: once before the call, once after it lands.