Azure APIM-Rate Limit By Key

2024-04-01T07:15:22.31+00:00

Hi Team,

We want to implement the rate limit but without using the subscription id and as per the below code from doc there is a counter-key and how we will define this key and as this key we need to pass as a header. Please let us know if any snippets are available for this requirement

<policies>

<inbound>

    <base />

    <rate-limit-by-key  calls="10"

          renewal-period="60"

          increment-condition="@(context.Response.StatusCode == 200)"

          counter-key="@(context.Request.IpAddress)"

          remaining-calls-variable-name="remainingCallsPerIP"/>

</inbound>

<outbound>

    <base />

</outbound>
```</policies>

Thanks,

Simanchala

---

---

---

---

---

***

***

***

***

***

***

***
Azure API Management
Azure API Management
An Azure service that provides a hybrid, multi-cloud management platform for APIs.
1,760 questions
{count} votes

1 answer

Sort by: Most helpful
  1. JananiRamesh-MSFT 21,246 Reputation points
    2024-04-01T10:48:35.8966667+00:00

    @Simanchala M [External], Technology Thanks for reaching out. The rate-limit-by-key policy in Azure APIM allows you to limit the number of requests that can be made to an API based on a specific key. The counter-key attribute is used to specify the key that should be used to track the number of requests made by a client.

    In the example you provided, the counter-key is set to @(context.Request.IpAddress), which means that the number of requests made by each IP address will be tracked separately. This is a common approach to rate limiting, as it allows you to limit the number of requests made by each client without requiring them to provide a subscription ID or other identifier.

    To use this policy in your API, you can add it to the inbound policy section of your API's policy file. You can then configure the calls, renewal-period attributes to specify the rate limit that you want to enforce.

    <inbound>
        <base />
        <rate-limit-by-key calls="10"
                          renewal-period="60"
                          counter-key="@(context.Request.Headers.GetValueOrDefault("X-Rate-Limit-Key", " "))"
                          remaining-calls-variable-name="remainingCallsPerKey" />
    </inbound>
    

    In this example, the counter-key attribute is set to @(context.Request.Headers.GetValueOrDefault("X-Rate-Limit-Key", " ")), which means that the value of the X-Rate-Limit-Key header will be used as the key for rate limiting.

    You can then pass the X-Rate-Limit-Key header in the request to specify the key to use for rate limiting. For example, you could set the X-Rate-Limit-Key header to a unique identifier for each client, such as a user ID or API key.

    Do let me know incase of further queries, I would be happy to assist you.

    0 comments No comments