Not Every 429 Is a Rate Limit: Token Budgets Across Azure AI Gateway, API Management and Foundry

Not Every 429 Is a Rate Limit: Token Budgets Across Azure AI Gateway, API Management and Foundry

TL;DR

A model call can now be stopped in four places: a gateway token rate limit, a gateway quota or spend limit, a Foundry budget (cost controls, in preview) and the deployment’s own quota. Several of them answer with HTTP 429, and a Foundry budget block on chat completions even sends Retry-After: 30. The OpenAI SDKs retry that twice by default, about a minute of waiting, although it can’t succeed until the budget resets or someone changes the cost control.

Read the response, not just the status code. Retry short rate limits, stop on quotas, spend limits and budgets, and log which limit fired. Put limits about who is calling in the gateway, budgets for projects, deployments and agents in Foundry, and keep one meter for chargeback.

In a hurry? Jump to the decision guide, the retry rules or one owner per limit, then come back for the headers.

For years a 429 from a model endpoint usually meant one thing: you’re going too fast, so wait a moment and try again. The OpenAI SDKs and most retry libraries are built on that assumption.

It doesn’t hold any more. Teams are moving from one shared pool of tokens to limits and budgets per team, per app and per agent, and the platform now has several places that can say no. Foundry’s new cost controls block calls once a budget is spent, AI Gateway is GA with token and cost limits per caller, and API Management’s token policy splits rate from quota. They don’t all use the same status code, and the ones that do don’t all mean the same thing. A client that treats every 429 as “wait and retry” will retry budget blocks that can’t succeed, burn its attempts on long windows, and fill the dashboards with noise that hides real capacity problems.

This post maps the layers, shows what each one sends back, and sets out the retry, ownership and chargeback rules I’d agree before AI Gateway billing starts on 1 January 2027. It builds on my AI Gateway GA post, which covers where each gateway fits.

The product details below were checked against Microsoft Learn, Microsoft’s product blogs, the official Azure AI Gateway labs and the OpenAI SDK repositories on 2 December 2026.

Four places a model call can stop

flowchart TB
    accTitle: Four places a model call can be stopped, and what each one sends back
    accDescr: A call from an app or agent passes the gateway first, API Management or AI Gateway. There, a token rate limit returns 429 with Retry-After, and a quota or spend limit returns 403, or in AI Gateway a 429 with a long wait for hour and day token windows. Inside Foundry, a cost control budget returns 429 with the x-ms-budget-cause header, and the deployment's own quota or provisioned throughput returns 429 with retry-after-ms. Only then does the model run.
    APP["App or agent"]:::app
    subgraph GW["Gateway · API Management or AI Gateway"]
      L1["Token rate limit
429 with Retry-After · slow down"]:::retry L2["Quota or spend limit
403, or 429 with a long wait · stop"]:::stop end subgraph FD["Microsoft Foundry"] L3["Budget, cost controls preview
429 with x-ms-budget-cause · stop"]:::stop L4["Deployment quota or provisioned throughput
429 with retry-after-ms · slow down"]:::retry end M["Model"]:::app APP --> L1 --> L2 --> L3 --> L4 --> M classDef app fill:#efe6df,stroke:#4b2b1e,color:#4b2b1e classDef retry fill:#eef0d8,stroke:#7c8a35,color:#3e461a classDef stop fill:#f6d9d2,stroke:#a63a1e,color:#5c1f10

Four checks give two kinds of answer. The slowdown checks ask you to wait and retry. The stop checks ask you to stop until a window resets or someone raises the limit. Only the status code looks alike. Inside Foundry, the order of the two checks isn’t documented, so read them as a pair.

One ordering detail is documented and matters: Foundry checks cost controls after the gateway, so a request the gateway rejects never counts against a Foundry budget. Foundry also only knows what reaches it. Identities that only the gateway sees, such as which app or user made the call, play no part in Foundry’s cost controls. That’s why Microsoft’s own guidance is to put token limits for each app and user in the gateway, and budgets for projects, deployments and agents in Foundry.

The decision guide

Three round badges. Rate limit, with an hourglass: wait, then retry. Quota or spend limit, with a gauge in the red: stop until it resets. Budget, with a coin: stop and tell a person

Three stops need three responses. Retry the first. Stop on the second and third, and make the third somebody’s problem, because raising a budget is a person’s decision.

  • API Management token rate, per minute: The llm-token-limit policy returns 429 with Retry-After. Wait and retry within a cap.
  • API Management token quota, hourly to yearly: The llm-token-limit policy returns 403 with Retry-After. Stop until the window resets or the quota rises.
  • AI Gateway token limit, per minute, hour or day: The gateway returns 429 with Retry-After and a “token limit is exceeded” message. Retry only if the wait is short; a daily window can mean hours.
  • AI Gateway cost limit: The gateway returns 403 with a “cost quota is exceeded” message and a wait in a policy header. Stop and surface it.
  • Foundry budget, spending or tokens: A cost control returns 429 with x-ms-budget-cause: budget_exceeded. Chat completions also include Retry-After: 30, while agent streams return 200 and an error event. Stop, don’t retry, and tell a person.
  • Foundry deployment quota: Tokens and requests per minute return 429 with retry-after-ms and x-ratelimit-* headers. Wait and retry, or use another deployment.
  • Foundry provisioned throughput at 100 per cent: The deployment returns 429 with retry-after-ms and retry-after. Wait and retry, or spill over.

From a shared pool to budgets per team

Most platforms I see started with one Azure OpenAI resource, one allocation of tokens per minute and a gateway that spread it across callers. That works until finance asks who spent what, or one team’s batch job starves another team’s chatbot. The answer for a while has been a gateway token limit per caller and showback from the gateway’s logs. What changed in the last few weeks:

  • Foundry cost controls, in public preview, add spending and token budgets on a Foundry resource or project, narrowed to projects, deployments, agents or hosted agent sessions, and they can block.
  • Azure AI Gateway went GA on 17 November with token, request and cost limits per caller.
  • Learn’s token limit page for Foundry now says existing token limit settings in the Foundry portal are read only and are changed in the API Management policy instead, although two Foundry cost pages updated the same week still point to the portal.
flowchart TB
    accTitle: Dates for gateway billing and budgets
    accDescr: Azure AI Gateway became generally available on 17 November 2026, and Foundry cost controls entered public preview the same month. Paid AI Gateway billing starts on 1 January 2027, and preview AI Gateway resources stop working on 15 January 2027 and are then removed.
    A["17 November 2026 · Azure AI Gateway generally available"]:::past
    B["November 2026 · Foundry cost controls in public preview"]:::past
    C["1 January 2027 · AI Gateway paid billing starts"]:::soon
    D["15 January 2027 · Preview AI Gateway resources
stop working and are removed"]:::deadline A --> B --> C --> D classDef past fill:#efe6df,stroke:#4b2b1e,color:#4b2b1e classDef soon fill:#fde4d3,stroke:#d8571f,color:#6b2a0c classDef deadline fill:#f6d9d2,stroke:#a63a1e,color:#5c1f10

Two dates matter in January. Paid AI Gateway billing starts on 1 January, and two weeks later the preview tier goes. Foundry’s cost controls have no GA date yet, so plan around them as preview.

Layer 1: API Management token limits

llm-token-limit is the policy most Azure teams already run. It does two jobs in one statement: a rate, tokens-per-minute, and a quota, token-quota over a token-quota-period of hourly, daily, weekly, monthly or yearly. The two answer differently. Going over the rate returns 429 Too Many Requests. Running out of quota returns 403 Forbidden. Both send Retry-After with the recommended wait in seconds, unless you rename that header. Quota windows are fixed, starting at the UTC time truncated to the period.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<policies>
<inbound>
<base />
<llm-token-limit
counter-key="@(context.Subscription.Id)"
tokens-per-minute="20000"
token-quota="5000000"
token-quota-period="Monthly"
estimate-prompt-tokens="false"
remaining-quota-tokens-header-name="x-remaining-quota-tokens"
remaining-tokens-header-name="x-remaining-tokens"
tokens-consumed-header-name="x-tokens-consumed" />
</inbound>
<outbound>
<base />
</outbound>
</policies>

A rate and a quota can apply to each subscription. One counter per API Management subscription carries a rate for each minute and a monthly quota. The three response header names are mine; pick your own and document them for callers. If callers sign in with Entra ID rather than subscription keys, key the counter on the caller’s validated identity instead of anything the caller can set.

Details worth knowing before you rely on it:

  • Estimation changes enforcement. With estimate-prompt-tokens="false", the policy uses the token counts in the model’s response, so a request can still reach the model after the limit is spent; the next ones are blocked. With true, it estimates prompt tokens before sending. Streaming requests always estimate prompt and completion tokens, whatever the setting.
  • Only prompt and completion tokens count. Nearly simultaneous requests can also briefly exceed the limit, because the real count only arrives with each response.
  • Counters are per gateway. Each regional gateway in a multiple region deployment, and each workspace gateway, keeps its own count. A caller that can reach two gateways can use roughly twice the limit.
  • One counter per key is shared across scopes. The same counter key at API and product scope shares one counter. In the v2 tiers, which use a token bucket rather than the classic tiers’ sliding window, keep tokens-per-minute identical wherever the same key appears.
  • It runs in the Developer, Basic, Basic v2, Standard, Standard v2, Premium and Premium v2 tiers, not Consumption, and covers OpenAI compatible Chat Completions and Responses APIs, the Anthropic Messages API in v2 tiers and Google Vertex AI.
  • Use the new name. The old azure-openai-token-limit page now redirects to llm-token-limit, and the policy index lists only the llm-* policies.

That model coverage matters for budgets. Foundry’s cost controls don’t count Claude models yet, so for Claude in a v2 tier, the gateway’s token quota is your only token budget for the period; the deployment’s own quota still caps the rate.

Layer 2: AI Gateway token and cost limits

AI Gateway, now GA as its own resource type, has two limits per caller that matter here:

  • Token limits take a count, a period of a minute, an hour or a day, and a counter key: the caller’s identity, IP address, both, or one shared counter. They attach to a model, an alias or the whole gateway.
  • Cost limits take an amount in US dollars, a period from an hour to a year, a counter by caller identity, IP address or one shared counter, and overrides for individual API keys or Entra identities.

You set them in the portal under Policies, with the az aigateway policy commands, or through REST, Bicep and Terraform.

What the caller sees:

  • A token limit returns 429 with Retry-After and a message that the token limit is exceeded, without calling the model. That’s true for hour and day windows too, so a 429 from AI Gateway can mean “come back in a few hours”. There’s no remaining token header, and because counters update after each response, fast bursts can overshoot.
  • A cost limit returns 403 with a message that the LLM cost quota is exceeded, again without calling the model. The body carries no error code. In Microsoft’s daily example the wait comes back in the message text and in a policy header, x-alias-cost-per-day-retry-after (x-cost- instead of x-alias- for a limit on a model), next to consumed and remaining headers. The example shows no standard Retry-After, so don’t rely on one. Spend is estimated from the tokens the provider reports and public prices, over fixed calendar windows.

A caution on sources: most of these response details come from Microsoft’s official AI Gateway labs and the diagnostics guide in the Azure AI Gateway repository rather than the product reference, so test them against your own gateway before you write client code around them.

And a price check, since billing starts in a month. Microsoft’s GA post says the first 10,000 requests a month are free per gateway, while the product site and the API Management Ignite post say per Azure subscription. Above that it’s US$500 a month per gateway, billed hourly, with 10 million requests included, then US$20 for each extra million, billed in steps of 10,000 requests. Microsoft also says prices may vary by region and that regional prices will be published when billing begins, so New Zealand teams should budget with a margin until then. If you piloted the preview tier, create a new AI Gateway resource before 15 January 2027: preview resources stop working then and are removed, and there’s no conversion in place.

Layer 3: Foundry budgets

Foundry cost controls are the new piece, and they’re properly preview: no SLA, and Microsoft doesn’t recommend them for production workloads yet. Here’s how they work.

  • Scope: You create a cost control on a Foundry resource or on a project, then narrow it with filters: project (resource controls only), deployment (which includes agent requests), agent, or hosted agent session, up to 20 session IDs. Session budgets apply only to hosted agents, and stopping and resuming a session doesn’t reset its usage. There’s no budget per user or Microsoft Entra group in this preview; that’s the gateway’s job.
  • Type and period: A Spending budget is in US dollars, priced from a snapshot of your negotiated prices, or retail prices where there aren’t any. A Tokens budget counts all tokens, or input or output only. You can’t change the type or the counted tokens later. Usage resets daily, weekly or monthly, and every control has an end date.
  • What counts: Only GPT and OpenAI o series models count; models from other providers, such as Claude and DeepSeek, don’t yet. A new GPT model is supported about a week after release, once its price is available to cost controls, and until then Spending budgets skip its usage for good while Tokens budgets count it. Model router isn’t fully supported. Provisioned throughput deployments aren’t counted at all, and neither are tool charges such as web search or hosted agent compute.
  • How current: Controls count usage as requests run, but during the preview the running total isn’t reconciled with your bill and usually runs slightly high, so thresholds trip a little early. The request that crosses a threshold can still complete, changes can take up to 15 minutes to apply, and if Foundry can’t check a request in time, the request runs. Billed cost shows up 8 to 24 hours after usage, and Microsoft’s FinOps post says it can take up to 72 hours on pay as you go subscriptions.
  • Who: Anyone with a Foundry role, or Reader, can see cost controls. Creating one at resource level needs Foundry Account Owner, Foundry Owner, Owner or Contributor; at project level, Foundry Project Manager can too.
sequenceDiagram
    accTitle: What a client sees when a Foundry budget blocks a call
    accDescr: The client sends a request through the gateway to Foundry, which checks the cost control after the gateway. For a chat completions call that isn't streaming, Foundry returns 429 with x-ms-budget-cause set to budget_exceeded and Retry-After 30. With default settings the SDK retries twice through the gateway, which counts each attempt. Each retry gets the same answer, and the call fails about a minute later. For an agent response that streams, Foundry returns 200, starts the stream and then sends an error event inside it.
    autonumber
    participant C as Client
    participant G as Gateway
    participant F as Foundry
    C->>G: Model or agent request
    G->>F: Within this caller's gateway limits
    F->>F: Check the cost control
    alt Chat completions, not streaming
        F-->>C: 429, x-ms-budget-cause budget_exceeded, Retry-After 30
        C->>G: The SDK retries, twice by default
        G->>F: The same request, counted by the gateway again
        F-->>C: 429 again
        Note over C: About a minute later, the call fails
    else Agent response, streaming
        F-->>C: 200, the stream starts
        F-->>C: Error event inside the stream
        Note over C: The status code says success
    end

One block has two disguises. A nonstreaming block looks like a rate limit and invites a retry. A streaming agent block looks like success until the error event arrives.

When a budget blocks, a nonstreaming request returns HTTP 429 with x-ms-budget-cause: budget_exceeded and a message that starts “Budget exceeded for cost control”. Other headers name the control (x-ms-applicable-policy-id, or x-ms-applied-cost-control-id in some responses), its reset time in UTC (x-ms-budget-window-reset) and its type (x-ms-cost-control-type: Cost for a Spending budget, Tokens for a Tokens budget). Here’s the catch: a blocked chat completions call currently also returns Retry-After: 30. That doesn’t mean the budget will allow anything in 30 seconds, but it’s exactly what the OpenAI SDKs look for, so by default a blocked call takes about a minute to fail. Microsoft’s guidance is to turn off automatic retries for these calls and check x-ms-budget-cause before retrying anything. Some APIs, agents among them, can also return the same error code as a rate limit, so the header is the reliable signal.

When an agent streams, the HTTP status is 200 and the block arrives as an error event inside the stream. Microsoft documents only that its message starts “Budget exceeded for cost control”, not the event’s format. I couldn’t find guidance for streaming model calls that don’t go through an agent, so test both before you depend on either.

There are two preview traps. A project’s cost controls count chat completions requests but don’t block them, and controls on the default project don’t block requests to the resource endpoint; use a resource control to block those. Requests that a cost control covers carry an x-ms-budget-state header whose values aren’t documented yet, so don’t build logic on it.

Alerts need more care than the blocks:

  • One threshold per control: Each cost control takes one alert threshold, at 50, 75, 80, 90 or 100 per cent or a fixed amount, at or below the block, which starts at 100 per cent and can be lowered. More alert levels need another cost control.
  • Event Grid with a key: Alerts go to an Event Grid topic that uses the CloudEvents 1.0 schema and key based authentication, as costControl.alert events, and setting them up needs the EventGrid Contributor role on the topic.
  • Test key rotation: Foundry creates a shared connection to the topic when you save, and Microsoft doesn’t document how it handles key rotation. If you rotate the topic’s keys, check that alerts still arrive, because alerts silently skip a connection they can’t use.
  • No control ID: The event doesn’t name or identify the cost control, so tell controls apart by data.unit, data.limit and data.startDate, or give each control its own topic.
  • One event per request: An event is sent for every request while usage is at or above the threshold, so deduplicate before anything pages a person.

Layer 4: the deployment’s own quota

Underneath all of this, each deployment still has its own quota. A standard deployment returns 429 when you exceed its tokens per minute or requests per minute, and requests per minute are enforced over short windows of 1 to 10 seconds. The response carries retry-after-ms and x-ratelimit-* headers such as x-ratelimit-remaining-tokens and x-ratelimit-remaining-requests. Microsoft distinguishes three kinds of 429 here (a rate limit, a capacity limit and a temporary limit adjustment) by the error message and the headers rather than the status. A temporary adjustment shows up as an x-ratelimit-limit-tokens value lower than the deployment’s configured limit.

Provisioned throughput behaves differently. At 100 per cent utilisation the service returns 429 straight away with retry-after-ms and retry-after, which Microsoft describes as a traffic management signal rather than an error. You can spill over to a standard deployment, either per request with the x-ms-spillover-deployment header or for every request by setting a spillover deployment on the provisioned deployment. Provisioned throughput is billed per provisioned throughput unit (PTU) per hour, or through monthly or yearly reservations, whatever you send through it, so token budgets and the bill won’t match.

Designing retries that don’t burn budget

Start with what the SDKs do today:

  • The OpenAI Python SDK retries twice by default, on connection errors, 408, 409, 429 and 5xx responses. It honours retry-after-ms or Retry-After up to two minutes and doesn’t retry at all when asked to wait longer. Without a usable header it backs off for up to 8 seconds, starting at about half a second, with jitter.
  • The Node SDK retries on the same statuses, also twice. It honours the header only up to a minute; beyond that it ignores the header and retries after its own short backoff anyway.
  • So by default, the Python SDK fails fast on an AI Gateway hourly or daily window, while the Node SDK retries it twice within seconds.
  • Neither retries a 403, so API Management quota blocks and AI Gateway cost limits already fail fast.
  • A 429 from a Foundry budget looks retryable to both, which is the failure after about a minute described above.
  • Neither retries a stream once you’ve started reading it.

These are the rules I’d give application teams:

  1. Own the retries. Turn SDK retries off wherever a budget can block, as Microsoft recommends, and put one retry function in your platform’s starter template.
  2. Classify before you retry. x-ms-budget-cause means a budget: stop. A 403 means stop too: usually a quota or spend limit, but IP filters and authorisation failures also return 403, so log the body. A 429 with a short retry-after-ms or Retry-After means slow down: wait and retry. A 429 with a long wait means a window: fail fast or fall back.
  3. Give each call a wait budget. An interactive request might wait 10 seconds in total; a batch job might wait minutes. Never wait longer than the caller can.
  4. Cap attempts, add jitter and break the circuit. A circuit breaker per limit stops a thousand requests each discovering the same exhausted quota.
  5. Fall back on purpose. Another deployment, a smaller model or a queued job, chosen per use case, rather than a blind retry.
  6. Log the classification with the correlation ID, so the platform team can see which limit fired.
flowchart TB
    accTitle: How a client should react to a blocked model call
    accDescr: When a call is blocked, first check for the x-ms-budget-cause header. If it's there, a budget is spent, so stop, surface it and don't retry. Otherwise, a 403 means stop: usually a quota or spend limit, though IP filters and authorisation failures also return 403, so log the body. A 429 whose Retry-After or retry-after-ms fits within the caller's wait budget means wait and retry with jitter and capped attempts. Anything else means fail fast or fall back to another deployment, a smaller model or a queue.
    S["Call blocked"]:::app
    Q1{"x-ms-budget-cause
present?"}:::ask B["Budget spent
stop, surface it, no retry"]:::stop Q2{"403?"}:::ask Q["Quota, spend limit or access denied
stop and log the body"]:::stop Q3{"429 with a wait that fits
the caller's wait budget?"}:::ask W["Wait, then retry
jitter, capped attempts"]:::retry F["Fail fast or fall back
another deployment, a smaller model, a queue"]:::fall S --> Q1 Q1 -- "yes" --> B Q1 -- "no" --> Q2 Q2 -- "yes" --> Q Q2 -- "no" --> Q3 Q3 -- "yes" --> W Q3 -- "no" --> F classDef app fill:#efe6df,stroke:#4b2b1e,color:#4b2b1e classDef ask fill:#fbf1cf,stroke:#b98d1d,color:#5a450e classDef retry fill:#eef0d8,stroke:#7c8a35,color:#3e461a classDef stop fill:#f6d9d2,stroke:#a63a1e,color:#5c1f10 classDef fall fill:#fde4d3,stroke:#d8571f,color:#6b2a0c

Check the header before the status. The budget header comes first because a budget block arrives as a 429. After that, the status code and the length of the wait decide.

Here’s a sketch of that logic in Python, with the SDK’s own retries switched off. It isn’t production code, but it shows the order of the checks:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import random
import time

from openai import OpenAI, APIStatusError

client = OpenAI(base_url=GATEWAY_URL, max_retries=0) # authentication omitted


class BudgetExceeded(Exception):
pass


class LimitReached(Exception):
pass


def wait_seconds(headers):
try:
if "retry-after-ms" in headers:
return float(headers["retry-after-ms"]) / 1000
if "retry-after" in headers:
return float(headers["retry-after"])
except ValueError:
pass # an HTTP date or something unexpected: don't guess
return None


def complete(messages, max_wait=10.0, attempts=3):
waited = 0.0
for attempt in range(1, attempts + 1):
try:
return client.chat.completions.create(model="chat", messages=messages)
except APIStatusError as e:
headers = e.response.headers
if headers.get("x-ms-budget-cause"):
raise BudgetExceeded(headers.get("x-ms-budget-window-reset")) from e
if e.status_code == 403:
raise LimitReached("quota, spend limit or access denied") from e
if e.status_code != 429:
raise
delay = wait_seconds(headers)
if delay is not None:
delay *= random.uniform(1.0, 1.2) # jitter
if attempt == attempts or delay is None or waited + delay > max_wait:
raise LimitReached("rate limited beyond this call's wait budget") from e
time.sleep(delay)
waited += delay

Stop early and wait briefly. Budgets and quotas raise straight away with what the caller needs to explain them, and only a short, honest wait is retried.

Estimates versus the bill

Every number in this stack is an estimate until the invoice arrives. AI Gateway prices tokens at public rates, so negotiated discounts don’t show. Foundry’s running total isn’t reconciled with the bill during the preview. And no gateway limit or Foundry budget reflects provisioned throughput’s hourly charge or tool charges such as web search. That’s fine as long as nobody treats a limit as the bill. Limits stop runaway usage. Cost Management tells you what you’ll actually pay.

One owner per limit, one meter for chargeback

Four panels. AI platform team: gateway token and cost limits per caller. FinOps: budget amounts, alerts and showback. Foundry owners: deployment quota and provisioned throughput. Application teams: retries, backoff and fallbacks

One owner applies each limit. Four teams make four kinds of decision. Where two teams touch a limit, one sets the number and the other configures it, and both know which is which.

  • Which callers can use which model, and how fast: The AI platform team owns gateway token rate limits for each caller.
  • How much each caller may use or spend in a period: The AI platform team owns gateway quotas and cost limits, with amounts agreed with FinOps.
  • How much a project, deployment or agent may spend: FinOps sets the amounts and alerts, while Foundry owners configure the cost controls. Use a resource control when you need a hard block.
  • How much capacity each deployment has: Foundry owners manage deployment quota and provisioned throughput.
  • How clients react to each limit: Application teams own retry policy, circuit breakers and fallbacks.
  • Who pays for what: FinOps owns showback from gateway logs and reconciliation with Cost Management.

Gateway logs, tokens per caller, feed a showback report through an arrow labelled apportion. Cost Management, the actual bill, feeds the same report through an arrow labelled reconcile. Foundry budgets, guardrails rather than a meter, lead to alerts and blocks, not to the report

Use one meter for one bill. The gateway says who used what, Cost Management says what it cost, and Foundry budgets raise the alarm or stop a runaway, but they never feed the report. Nothing gets counted twice.

The double counting trap is easy to fall into. The gateway logs tokens per call, Foundry counts tokens per project, deployment and agent, and Cost Management has the bill. Add any two together and you’ve counted the same tokens twice. My rule is that showback, and any chargeback built on it, comes from one meter, the gateway, because it’s the only layer that knows the caller. Apportion the Cost Management bill by each caller’s share of the gateway’s estimated cost per model, and use Foundry budgets as guardrails and alerts, not as a second ledger.

The exception worth chasing is traffic that skips the gateway. If a team calls Foundry directly, its usage shows up in Cost Management but not in your showback, so make the gateway the only way in.

Observability: log which limit fired

When a call fails, three teams want to know which limit fired, and each layer records it somewhere different. Make it one query:

  • Carry one correlation ID. Honour the caller’s ID end to end into Log Analytics, and if a caller doesn’t send one, have the gateway create one and return it. The same ID should appear in the app log and the gateway log. Foundry’s alert events carry no request ID, so join them by project, agent, deployment and time.
  • Log the classification in the client: the status, x-ms-budget-cause, the cost control ID and type, the wait the response asked for, and what the client did next.
  • Keep the gateway’s view. In API Management, the ApiManagementGatewayLlmLog table, from the “Logs related to generative AI gateway” diagnostic category, holds prompt, completion and total tokens, the model and deployment names, whether the call streamed, and optionally the messages. Its CorrelationId joins to ApiManagementGatewayLogs, which has the status code, product and subscription, plus LastError columns that record where a rejected request failed. Token data can be missing when a stream breaks, and messages are split into 32 KB chunks, so count each request once.
  • Use metrics for trends and logs for money. llm-emit-token-metric sends prompt, completion and total tokens to Application Insights with up to five custom dimensions, but API Management caps each dimension at 100 unique values and each metric namespace at 1,000 time series, and silently drops anything over. Don’t build chargeback per caller on metrics once you have more than 100 callers.

A query that counts each request once and attributes its tokens to a product and subscription looks like this:

1
2
3
4
5
6
7
8
9
10
ApiManagementGatewayLlmLog
| where TimeGenerated > ago(30d)
| summarize Tokens = max(TotalTokens) by CorrelationId, ModelName
| join kind=inner (
ApiManagementGatewayLogs
| where TimeGenerated > ago(30d)
| distinct CorrelationId, ApimSubscriptionId, ProductId
) on CorrelationId
| summarize Tokens = sum(Tokens) by ProductId, ApimSubscriptionId, ModelName
| order by Tokens desc

Count each request once. Taking the maximum per correlation ID guards against rows split across chunks, and the join adds who called. Multiply by your price per model for the showback estimate, then reconcile with Cost Management.

My take

Limits about who is calling belong in the gateway, because it’s the only layer that knows the caller. Budgets for a project, a deployment or an agent belong in Foundry, because that’s where those things live. And neither of them is the bill.

The bigger change is in client code. “Retry on 429” was always a simplification; now it’s a bug. A Foundry budget block that retries twice costs a minute of someone’s time and fixes nothing, and a client that retries a daily AI Gateway window every few seconds is just noise. I’d make the classification function part of the platform’s SDK or starter template, so application teams get the right behaviour without having to read this post.

Be careful with the preview. Foundry cost controls are useful today as an early warning and as a hard stop on a runaway agent. But they skip some models, can let the crossing request through, let requests run when they can’t check in time, and don’t cover provisioned throughput. I’d use them as a safety net with alerts, not as the control finance relies on, until they’re GA and reconciled with billing.

And keep it boring: one owner per limit, one meter for showback, one correlation ID across the logs. The interesting part should be the agents, not the argument about whose 429 it was.

Key Takeaways

  • Four layers can now stop a model call, and several answer with 429, so the status code alone won’t tell you which one fired.
  • API Management returns 429 for its rate and 403 for its quota. AI Gateway returns 429 for token limits on any window, including hours and days, and 403 for cost limits.
  • A Foundry budget block returns 429 with x-ms-budget-cause and, on chat completions, Retry-After: 30. Turn off SDK retries for those calls and check the header first. Agent streams get 200 and an error event.
  • Classify, then retry: wait only for short rate limits within the caller’s wait budget, and stop on quotas, spend limits and budgets.
  • Put limits for each caller in the gateway and project, deployment and agent budgets in Foundry. Use one meter, the gateway, for showback, and reconcile it with Cost Management.
  • Foundry cost controls are preview: they skip some models and provisioned throughput, overstate spending slightly, and let a request through when they can’t check it in time.
  • AI Gateway paid billing starts on 1 January 2027, and preview gateways stop working on 15 January 2027.

References

Image Credits

  • Cover image generated by Copilot

Not Every 429 Is a Rate Limit: Token Budgets Across Azure AI Gateway, API Management and Foundry

https://clouddev.blog/Azure/AI/not-every-429-is-a-rate-limit-token-budgets-across-azure-ai-gateway-api-management-and-foundry/

Author

Ricky Gummadi

Posted on

2026-12-02

Updated on

2026-12-03

Licensed under

Comments

Choose your design

Only the look changes. Your posts, ads, comments and other integrations stay in place, with the same light/dark and cookie preferences.

Choose the look you prefer