An Azure API Management policy is an XML statement that runs on each request or response, in one of four sections: inbound, backend, outbound or on-error. The patterns below cover the four jobs we see most: authenticate the caller, limit use, transform the message and handle failure. Adapt the values to your tenant and test each in a non-production instance first.
It builds on our Azure API Management page and the AI gateway policy walkthrough. Microsoft documents every policy in its policy reference.
Auth
Validate a token before anything else in inbound. The validate-jwt policy checks signature, expiry and claims.
<inbound>
<base />
<validate-jwt header-name="Authorization" failed-validation-httpcode="401"
failed-validation-error-message="Unauthorized">
<openid-config url="https://login.microsoftonline.com/{tenant-id}/v2.0/.well-known/openid-configuration" />
<audiences>
<audience>api://orders-api</audience>
</audiences>
<required-claims>
<claim name="roles" match="any">
<value>Orders.Read</value>
</claim>
</required-claims>
</validate-jwt>
</inbound>Keep the tenant ID, audience and role names in named values so the same policy promotes across environments. Do not log the Authorization header.
Rate limits
Use rate-limit-by-key to count by caller identity rather than by IP address, and quota-by-key for longer-term caps.
<inbound>
<base />
<rate-limit-by-key calls="100" renewal-period="60"
counter-key="@(context.Request.Headers.GetValueOrDefault("Authorization","").AsJwt()?.Subject)" />
<quota-by-key calls="100000" renewal-period="2592000"
counter-key="@(context.Request.Headers.GetValueOrDefault("Authorization","").AsJwt()?.Subject)" />
</inbound>Pick the counter key deliberately. A shared key such as a client IP behind a corporate proxy throttles many users as one. Where several gateway units serve one instance, counters are approximate, so set limits with headroom.
| Need | Policy | Window |
|---|---|---|
| Protect the backend from bursts | rate-limit-by-key | Seconds to minutes |
| Plan or tier allowance | quota-by-key | Day or month |
| Cap by data volume | quota-by-key with bandwidth | Day or month |
| Block known bad sources | ip-filter | Always |
Transform
Transform only what the backend or the consumer cannot change. Each transform is logic you now own.
<inbound>
<base />
<set-header name="X-Correlation-Id" exists-action="skip">
<value>@(context.RequestId.ToString())</value>
</set-header>
<rewrite-uri template="/v2/orders/{id}" />
<set-backend-service base-url="https://orders.internal.example.com" />
</inbound>
<outbound>
<base />
<set-header name="X-Powered-By" exists-action="delete" />
</outbound>- Strip backend headers that reveal the stack in outbound.
- Pass a correlation ID so a call can be traced from gateway to backend logs.
- Use XML-to-JSON or JSON-to-XML policies for format bridges, and keep a test for each.
Error handling
Retry only calls that are safe to repeat, and return one error shape for all failures. The retry policy sits in the backend section.
<backend>
<retry condition="@(context.Response.StatusCode >= 500)" count="2" interval="2" first-fast-retry="true">
<forward-request buffer-request-body="true" />
</retry>
</backend>
<on-error>
<base />
<return-response>
<set-status code="502" reason="Bad Gateway" />
<set-header name="Content-Type" exists-action="override">
<value>application/json</value>
</set-header>
<set-body>@{ return new JObject(new JProperty("error","upstream_failure"),
new JProperty("requestId", context.RequestId.ToString())).ToString(); }</set-body>
</return-response>
</on-error>- Do not retry POST requests that are not idempotent.
- Never return the raw exception message. Return an ID and log the detail.
- Treat timeouts as part of the design: set the forward-request timeout lower than the client's.
Order and scope
| Rule | Why |
|---|---|
| Authentication first, then limits | Do not count calls from unauthenticated callers against a customer's quota |
| Put shared logic at product or global scope | One change, one place |
| Always include base in each section | Otherwise a parent scope's policies are dropped |
| Keep policies in source control | Review and roll back like code |
Testing policies before they reach production
- Use the trace feature in the test console to see which policies ran and what they changed.
- Keep a small set of recorded requests for each API: valid, no token, expired token, wrong role, over limit and backend down. Replay them after each policy change.
- Use API revisions to try a change without disturbing the current version.
- Review policy diffs in pull requests. Policy XML is code.
- Check Application Insights for the new error codes after a release.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Missing base element | Parent policies silently stop applying | Add base in every section |
| Retry on non-idempotent POST | Duplicate orders or payments | Retry only safe operations |
| Rate limit by IP behind a proxy | One busy office blocks itself | Count by caller identity |
| Logging the Authorization header | Tokens in logs | Mask or omit |
| Hard-coded URLs and IDs | Policy breaks on promotion | Use named values |
| Detailed error text in responses | Leaks internals | Return an ID and log the detail |
Where to go next
Policies are only part of the design. Network isolation, key handling and logging belong to the security checklist
If you route model calls through the gateway, the token limit and metric policies in our AI gateway guide follow the same structure. Microsoft also publishes policy snippets and examples in its reference, which are worth reading before writing your own.



