CodexBloom - Programming Q&A Platform

Azure API Management - How to configure custom policies for rate limiting based on subscription tiers?

👀 Views: 94 đŸ’Ŧ Answers: 1 📅 Created: 2025-07-02
azure-api-management rate-limiting policy XML

I've been working on setting up Azure API Management (APIM) for a microservices architecture and need to implement custom rate limiting based on different subscription tiers... My goal is to limit the number of calls for basic users to 100 requests per minute, while premium users should have a limit of 500 requests per minute. I've tried using the built-in policies, but the configuration seems to be affecting all users uniformly, regardless of their subscription level. Here's what I have in my policy configuration: ```xml <policies> <inbound> <base /> <set-variable name="userTier" value="@(context.Subscription?.Properties["Tier"] ?? "Basic")" /> <choose> <when condition="@(context.Variables["userTier"] == "Basic")"> <rate-limit calls="100" renewal-period="60" /> </when> <when condition="@(context.Variables["userTier"] == "Premium")"> <rate-limit calls="500" renewal-period="60" /> </when> <otherwise> <return-response> <set-status code="403" reason="Forbidden" /> <set-header name="Content-Type" exists-action="override"> <value>application/json</value> </set-header> <set-body> {"error":"Subscription tier not recognized."} </set-body> </return-response> </otherwise> </choose> </inbound> <backend> <base /> </backend> <outbound> <base /> </outbound> </policies> ``` However, when I test the API with both subscription tiers using Postman, I receive a 429 status code (Too Many Requests) even when I stay within the limits specified. This suggests that the rate limit is not being applied correctly. I've also confirmed that the `Tier` property is set correctly in the Azure Portal for each subscription. Is there something I'm missing in the policy configuration? Any insights or suggestions on how to achieve tier-based rate limiting would be appreciated! What am I doing wrong? Thanks for taking the time to read this! The project is a REST API built with Xml. Thanks, I really appreciate it!