Azure API Management: how APIM works as an AI gateway for LLMs
Azure API Management (APIM) is Microsoft's managed platform for publishing, securing, and observing APIs, and it also governs traffic to large language models through capabilities Microsoft calls the AI gateway. Teams on Azure can apply token limits, token metrics, semantic caching, content safety checks, and failover across model deployments with the policy engine that fronts their REST APIs. This explainer, part of the AI gateways and LLM routing hub, covers what APIM is, how each AI gateway feature works, and its documented limits as of November 2026.
What is Azure API Management?#
Azure API Management is a platform as a service from Microsoft that sits in front of backend APIs and manages their lifecycle, from import and policy enforcement to publishing and monitoring. Microsoft's overview of API Management describes a hybrid, multicloud platform built from three components: an API gateway, a management plane, and a developer portal.
- API gateway (data plane): receives client requests, verifies keys, JWTs, and certificates, enforces quotas and rate limits, and emits logs, metrics, and traces.
- Management plane: where providers define APIs, group them into products, and set policies.
- Developer portal: a website where API consumers read documentation and subscribe to get keys.
The gateway component is the Azure API gateway that client traffic passes through, and it is where the AI gateway policies run. Behavior comes from policies: XML statements that run in sequence on the request or response, at global, workspace, product, API, or operation scope.
"APIM Azure" and "Azure APIM" name the same service, which is sold in three tier groups:
- Classic: Developer (non-production, no SLA), Basic, Standard, and Premium. Only Premium supports multi-region deployment.
- v2: Basic v2, Standard v2, and Premium v2, on a newer platform with faster provisioning and scaling.
- Consumption: a serverless gateway that scales with demand and bills per execution.
How the AI gateway in Azure API Management works#
The AI gateway in Azure API Management is a set of capabilities inside the existing API gateway, not a separate service. A team imports a model endpoint as an API, APIM creates a backend and authenticates to it, and policies in the inbound and outbound sections enforce token limits, caching, content safety, and metrics on each call.
The AI gateway overview lists three schemas the LLM policies understand: OpenAI Chat Completions or Responses, Anthropic Messages (in the v2 tiers), and Google Vertex AI. Models can run in Microsoft Foundry or with providers such as Amazon Bedrock, so the Azure AI gateway isn't limited to Azure OpenAI. Models come in three ways:
- Microsoft Foundry import: a wizard that creates the API, a backend, and managed identity authentication, so the hop from APIM to the model needs no API key.
- Language model API import: for OpenAI-compatible endpoints, or as a passthrough API for incompatible providers such as Amazon Bedrock.
- Unified model API: one OpenAI Chat Completions endpoint that translates requests for OpenAI or Anthropic backends, with model aliases and failover across providers. The unified model API page lists it as generally available in the v2 tiers and in early access for classic tiers.
Each policy blocks a call in a different way:
| Policy | Section | What it does | What a blocked client receives |
|---|---|---|---|
llm-token-limit |
Inbound | Enforces a token rate, a token quota, or both | 429 over the rate, 403 over the quota |
llm-emit-token-metric |
Inbound | Sends token counts to Application Insights | Nothing |
llm-semantic-cache-lookup |
Inbound | Returns a cached completion for a similar prompt | A cached response |
llm-semantic-cache-store |
Outbound | Writes completions to the cache | Nothing |
llm-content-safety |
Inbound or outbound | Checks prompts or completions with Azure AI Content Safety | 403, or a stream that ends early |
Earlier policy names used an azure-openai- prefix, but the AI gateway section of the policy reference lists only the llm-* policies.
Token limits with llm-token-limit#
The llm-token-limit policy caps how many tokens each consumer can use, as a tokens-per-minute (TPM) rate, a token quota over a fixed window, or both. A caller over the rate receives 429 Too Many Requests, and a caller over the quota receives 403 Forbidden. The counter key can be a subscription ID, an IP address, or any policy expression.
This example from the AI gateway overview sets a rate limit of 500 tokens per minute per subscription:
<llm-token-limit counter-key="@(context.Subscription.Id)"
tokens-per-minute="500" estimate-prompt-tokens="false" remaining-tokens-variable-name="remainingTokens">
</llm-token-limit>Quotas reset Hourly, Daily, Weekly, Monthly, or Yearly. The required estimate-prompt-tokens attribute decides when APIM counts: with true, it estimates prompt tokens before forwarding, so an over-limit prompt can be blocked before it reaches the model; with false, it counts from each response's usage section, so the request that crosses the limit still reaches the model. The llm-token-limit reference documents these limits:
- It isn't available in the Consumption tier.
- It counts prompt and completion tokens only.
- It tracks usage separately at each gateway, including workspace gateways and each regional gateway.
- Streaming requests always use estimated token counts.
- Concurrent requests can temporarily exceed the limit.
- In the v2 tiers, which use a token bucket,
tokens-per-minuteshould match at every scope sharing acounter-key, or limits behave unpredictably.
The per-gateway counter matters most for budgets: in a multi-region Premium instance, one subscription can spend a monthly quota in full at each regional gateway.
Token metrics and LLM logs in Azure API Management#
Azure API Management reports LLM usage in two ways. The llm-emit-token-metric policy sends token counts to Application Insights as custom metrics with chosen dimensions, and a diagnostic setting sends per-request logs, including token counts and optionally full prompts and completions, to a Log Analytics workspace for billing and audit.
Microsoft's example tags metrics with the client IP, API ID, and a user ID header:
<llm-emit-token-metric namespace="llm-metrics">
<dimension name="Client IP" value="@(context.Request.IpAddress)" />
<dimension name="API ID" value="@(context.Api.Id)" />
<dimension name="User ID" value="@(context.Request.Headers.GetValueOrDefault("x-user-id", "N/A"))" />
</llm-emit-token-metric>The llm-emit-token-metric reference sets hard limits:
- Each policy takes up to five custom dimensions.
- APIM tracks at most 100 unique values per dimension and 1,000 active time series per namespace, and past either limit it discards new data without an error.
- Some OpenAI models return streamed token counts only when the request sets
include_usagetotrue.
The 100-value cap means a user ID dimension stops recording new users after the hundredth, so per-user chargeback belongs in logs. A diagnostic setting sends Logs related to generative AI gateway to Log Analytics; per the LLM logging guide, messages over 32 KB are split into chunks, and each request and response is capped at 2 MB. Records land in the ApiManagementGatewayLlmLog table. The guide to LLM observability covers the application tracing that gateway logs don't show.
Semantic caching with llm-semantic-cache-lookup and llm-semantic-cache-store#
Semantic caching in Azure API Management returns a stored completion when a new prompt is close in meaning to an earlier one, measured by embedding vectors. It pairs llm-semantic-cache-lookup in the inbound section with llm-semantic-cache-store in the outbound section, backed by an external Redis-compatible cache with the RediSearch module.
The semantic caching how-to requires an embeddings deployment with its own backend and an Azure Managed Redis instance with RediSearch, a module that can be enabled only when the cache is created. Its inbound example adds the rate limit Microsoft recommends after the lookup:
<llm-semantic-cache-lookup
score-threshold="0.15"
embeddings-backend-id="embeddings-backend"
embeddings-backend-auth="system-assigned"
ignore-system-messages="true"
max-message-count="10">
<vary-by>@(context.Subscription.Id)</vary-by>
</llm-semantic-cache-lookup>
<rate-limit calls="10" renewal-period="60" />The outbound store sets the time-to-live in seconds:
<llm-semantic-cache-store duration="60" />score-threshold runs from 0.0 to 1.0, and lower values demand closer matches. The example uses 0.15, but the lookup policy reference suggests starting at 0.05 and warns that values above 0.2 may return mismatched responses. The limits to check before turning on semantic caching:
- Neither policy runs on workspace gateways.
- A failed lookup raises no error, which is why the rate limit after it protects the backend.
- APIM doesn't check linked access on
embeddings-backend-id, so anyone who can write policy can send embeddings calls through any backend with the instance's managed identity. - Similarity matching can return responses that are incorrect, outdated, or unsafe for the new prompt.
Set vary-by on every cache, because without a partition key a near match from one tenant can answer another tenant's prompt. The guide to semantic caching for LLMs compares APIM's thresholds with other gateways.
Content safety with llm-content-safety#
The llm-content-safety policy sends prompts, and optionally completions, to Azure AI Content Safety and blocks flagged content with a 403. It filters four harm categories (Hate, SelfHarm, Sexual, and Violence) at a severity threshold, applies custom blocklists, and, with shield-prompt set to true, checks prompts for user attacks such as prompt injection.
The policy acts as a gateway-level guardrail for LLM APIs, MCP tools, and A2A agent APIs. Setup needs a Content Safety resource, an APIM backend that reaches it with managed identity, and the Cognitive Services User role for APIM's identity. This example from the llm-content-safety reference blocks hate and violence at severity 4 or higher:
<policies>
<inbound>
<llm-content-safety backend-id="content-safety-backend" shield-prompt="true">
<categories output-type="EightSeverityLevels">
<category name="Hate" threshold="4" />
<category name="Violence" threshold="4" />
</categories>
</llm-content-safety>
</inbound>
</policies>The limits that affect clients:
- Prompts are checked in 10,000-character windows, and responses in 1,000-character windows by default.
- On a streaming response, the policy stops forwarding events after a violation and returns no
403, so client code should treat a stream that ends early as a possible block. - APIM doesn't check linked access on
backend-id, the same gap as the semantic cache.
The guardrails and AI security directory lists other tools that run similar checks.
Backend pools and circuit breakers for LLM failover#
Azure API Management spreads traffic across model deployments with a backend pool and stops sending requests to a failing deployment with a circuit breaker rule on that backend. Both are settings on backend entities, and together they provide load balancing and failover across Azure OpenAI or Foundry deployments.
The backends reference caps a pool at 30 backends and offers three load balancing options, each with optional cookie-based session awareness:
- Round-robin, the default, spreads requests evenly.
- Weighted splits requests by each backend's relative weight, for cases such as blue-green deployments.
- Priority-based sends requests to the highest priority group first and spreads them within a group evenly or by weight.
The usual Azure pattern places provisioned throughput (PTU) deployments in priority 1 and pay-as-you-go deployments in priority 2. APIM uses a lower priority group only when every backend in the higher group is unavailable because its circuit breaker has tripped, so a priority pool without breaker rules never fails over to priority 2.
A circuit breaker rule trips on a number or percentage of failures within an interval, for a range of status codes. While it's tripped, APIM sends nothing to that backend and returns 503 Service Unavailable to the client. Microsoft's Bicep example trips on three 5xx responses in one hour and accepts the backend's Retry-After value:
resource symbolicname 'Microsoft.ApiManagement/service/backends@2023-09-01-preview' = {
name: 'myAPIM/myBackend'
properties: {
url: 'https://mybackend.com'
protocol: 'http'
circuitBreaker: {
rules: [
{
failureCondition: {
count: 3
errorReasons: [
'Server errors'
]
interval: 'PT1H'
statusCodeRanges: [
{
min: 500
max: 599
}
]
}
name: 'myBreakerRule'
tripDuration: 'PT1H'
acceptRetryAfter: true
}
]
}
}
}An overloaded Azure OpenAI service returns 429 Too Many Requests with a Retry-After value that can be as long as a day, so Microsoft advises breaker rules that handle 429 responses. Each backend takes only one rule, the breaker isn't supported in the Consumption tier, and trips are approximate because gateway instances don't synchronize. List 429 alongside 500 to 599 in the rule's statusCodeRanges array, and expect a tripped PTU backend to stay out of rotation for the full Retry-After period. The guide to LLM routing covers fallback strategies beyond backend settings.
MCP servers and A2A agents in Azure API Management#
Azure API Management can act as an MCP gateway for remote Model Context Protocol servers. It exposes a REST API it already manages as an MCP server, with operations becoming tools, or passes through an existing MCP server, and it applies policies for rate limits, JWT validation, IP filtering, and caching to the tools.
The MCP server overview lists the gaps: APIM supports MCP tools but not MCP resources or prompts, MCP features aren't supported in workspaces, and policies apply to every tool in a server. MCP management runs in the classic and v2 tiers and on the self-hosted gateway, not in Consumption. The MCP security guide covers the threats these controls address.
APIM also imports A2A agent APIs on the classic and v2 managed gateways. Microsoft Foundry can use an APIM instance as its AI gateway, in preview as of November 2026, to set token quotas and register agents and MCP tools from the Foundry interface.
Azure API Management AI gateway support by tier and gateway type#
The AI gateway applies to all Azure API Management tiers, but individual features don't. The Consumption tier lacks token limits, circuit breakers, MCP servers, and A2A agents, and workspace gateways lack semantic caching and MCP. The table combines the policy reference matrix with the gateways overview, as of November 2026.
| Feature | Classic | v2 | Consumption | Self-hosted | Workspace |
|---|---|---|---|---|---|
llm-token-limit |
Yes | Yes | No | Yes | Yes |
llm-emit-token-metric |
Yes | Yes | Pages conflict | Yes | Yes |
| Semantic cache lookup and store | Yes | Yes | Yes | Yes | No |
llm-content-safety |
Yes | Yes | Pages conflict | Yes | Yes |
| Backend circuit breaker | Yes | Yes | No | Yes | Yes |
| Load-balanced backend pool | Yes | Yes | Yes | Yes | Yes |
| MCP servers | Yes | Yes | No | Yes | No |
| A2A agent APIs | Yes | Yes | No | No | No |
For token metrics, the policy matrix says No for Consumption while the policy page says it applies to all tiers; for content safety, the matrix says Yes while the policy page's tier list leaves Consumption out. The self-hosted gateway is available in the classic Developer and Premium tiers, and the tier comparison lists Log Analytics request logs, where LLM logs go, as unavailable in Consumption.
When Azure API Management fits as an AI gateway#
Azure API Management fits as an AI gateway when most model traffic runs on Azure OpenAI or Foundry, when the organization already publishes APIs through APIM, and when identity and monitoring run on Entra ID and Azure Monitor. The fit weakens as traffic spreads to providers outside Azure or to tiers without full AI gateway support.
The constraints to design around:
- Token counters, breaker state, and load balancing are tracked per gateway instance or regional gateway, not across the service.
- Each backend takes one breaker rule, and failover between priority groups depends on it.
- Metric dimensions stop at 100 values, which rules out per-user token metrics at scale.
Teams whose model traffic mostly goes to providers outside Azure often compare APIM with dedicated AI gateways, self-hosted or managed, which the AI gateways directory lists by deployment model.
Next steps#
To evaluate Azure API Management, start with the explainer on what an AI gateway is for the request pipeline these policies implement. Then test llm-token-limit, a priority backend pool with a circuit breaker rule, and vary-by cache partitioning on a non-production instance before moving production traffic.
Frequently asked questions
What is Azure API Management used for?
- Azure API Management is used to publish, secure, and monitor APIs from one gateway. Organizations put it in front of internal and partner APIs to enforce authentication, rate limits, quotas, and transformations, to give developers a portal with documentation and keys, and to collect logs and metrics. Its AI gateway features extend the same control to LLM APIs, MCP servers, and agent APIs, including token limits, semantic caching, and content safety checks.
Is Azure API Management PaaS or SaaS?
- Azure API Management is platform as a service (PaaS). Microsoft runs the gateway, management plane, and developer portal as managed Azure resources, while customers define the APIs, policies, products, and backends and choose a tier such as Developer, Standard v2, Premium, or Consumption. Customers who need the gateway closer to their workloads can run the self-hosted gateway, a Linux container managed from the Azure service, in the Developer and Premium tiers.
Is Azure APIM an API gateway?
- Yes, Azure APIM includes an API gateway and adds more around it. The gateway, also called the data plane, receives client requests, verifies keys and tokens, applies policies, and forwards calls to backends. APIM pairs that gateway with a management plane for configuring APIs and policies and a developer portal for API consumers. Its AI gateway features run inside the same gateway rather than as a separate gateway type.
Does Azure API Management work with models outside Azure OpenAI?
- Yes. The LLM policies work with APIs that follow the OpenAI Chat Completions or Responses schema, the Anthropic Messages schema in the v2 tiers, or the Google Vertex AI schema. APIM imports OpenAI-compatible endpoints directly, wraps incompatible providers such as Amazon Bedrock as passthrough APIs, and can expose several providers behind one OpenAI-compatible endpoint with the unified model API, which translates requests to OpenAI or Anthropic formats.
Can Azure API Management be used as an MCP gateway?
- Yes, for remote MCP servers in the classic and v2 tiers and on the self-hosted gateway. APIM can turn a managed REST API into an MCP server whose operations become tools, or pass through an existing MCP server, and then apply rate limits, JWT validation, IP filtering, and caching. As of November 2026, it supports MCP tools but not MCP resources or prompts, and its MCP features don't run in workspaces.
Does the Azure API Management Consumption tier support token limits?
- No. The llm-token-limit policy isn't available in the Consumption tier, and neither is the backend circuit breaker that priority-based failover depends on. Semantic caching and load-balanced backend pools are listed as supported there. Microsoft's own pages disagree on whether token metrics and content safety run in Consumption, so test both before relying on them, or choose a classic or v2 tier for production AI traffic.
Terms in this guide
Cite this guide
The AI Engineering Editors. "Azure API Management: how APIM works as an AI gateway for LLMs." The AI Engineering, updated Nov 25, 2026. https://theaiengineering.com/articles/azure-api-management
- Title
- Azure API Management: how APIM works as an AI gateway for LLMs
- Author
- The AI Engineering Editors
- Publisher
- The AI Engineering
- Published
- Updated