Duczer East
Healthcare

In-perimeter AI on governed clinical and operational data.

Financial Services

Private AI and data platforms built to clear model-risk and audit review.

Financial services

Private AI, KYC/AML, API gateways and data governance for banks.

Insurance

Change data capture, governed agents and integration for insurers.

Healthcare

PHI document intelligence, FHIR APIs and in-perimeter AI for health systems and plans.

GuideIntegration & Security7 min read

Azure API Management Policy Cookbook: Auth, Rate Limits, Transforms and Errors

Copy-and-adapt policy snippets, with the sections and scopes that trip people up.

Authored byCo-Founder and Managing Partner, Duczer East
Part of the Insights topic: API Management & Integration
On this page
  1. Auth
  2. Rate limits
  3. Transform
  4. Error handling
  5. Order and scope
  6. Testing policies before they reach production
  7. Common mistakes
  8. Where to go next

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.

NeedPolicyWindow
Protect the backend from burstsrate-limit-by-keySeconds to minutes
Plan or tier allowancequota-by-keyDay or month
Cap by data volumequota-by-key with bandwidthDay or month
Block known bad sourcesip-filterAlways

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

RuleWhy
Authentication first, then limitsDo not count calls from unauthenticated callers against a customer's quota
Put shared logic at product or global scopeOne change, one place
Always include base in each sectionOtherwise a parent scope's policies are dropped
Keep policies in source controlReview 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

MistakeEffectFix
Missing base elementParent policies silently stop applyingAdd base in every section
Retry on non-idempotent POSTDuplicate orders or paymentsRetry only safe operations
Rate limit by IP behind a proxyOne busy office blocks itselfCount by caller identity
Logging the Authorization headerTokens in logsMask or omit
Hard-coded URLs and IDsPolicy breaks on promotionUse named values
Detailed error text in responsesLeaks internalsReturn 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.

Related: Azure API Management consulting · Use case: Azure API Management cost review · Azure APIM as an AI gateway · Azure APIM vs AWS API Gateway · Azure APIM developer portal launch checklist

Frequently asked questions

Where do Azure API Management policies run?

In four sections of each policy definition: inbound, backend, outbound and on-error. They can be set at global, product, API and operation scope, and are inherited with the base element.

What is the difference between rate-limit and quota?

Rate limit caps calls in a short window to protect the backend. Quota caps total calls or bandwidth over a longer period and supports usage-based plans. Use both when you have tiers.

Should I use subscription keys for security?

Use keys to identify and meter callers, and add token validation such as validate-jwt for authentication. Keys alone are weak against leaks.

How do I test a policy change safely?

Apply it to a non-production instance or a revision of the API, and use the trace feature in the test console. Keep policies in source control and deploy them with your pipeline.

Do these policies work in every tier?

Most do, but gateway differences exist, for example for the self-hosted gateway and the Consumption tier. Check the policy page for the Applies to line before relying on one.

Authored by

Co-Founder and Managing Partner, Duczer East

David deBoisblanc is co-founder of Duczer East and a digital transformation and innovation leader in data-centric AI, agentic systems, and enterprise integration. He shapes intent-driven AI solutions that modernize how organizations use data, drawing on deep experience with Cloudera and complex enterprise integration landscapes.

Newsletter

The Practitioner's Briefing

Senior-level insights on agentic AI, data engineering and enterprise integration, delivered to your inbox.

One email when there is something worth reading. Unsubscribe any time.

Let's Talk

Want to discuss the ideas raised here?

Tell us what you are working on. A senior practitioner replies, and only your email is required.

Get a quote