Trying to implement Rate Limiting Policy on API Management in Azure

593 Views Asked by At

I'm trying to setup a policy within Azure APIM where I can rate limit calls to the API, but also whitelist a range of IP's so they're not stopped by the Rate Limit Policy.

Ideally I want to limit the amount of calls per IP to 60 times within 60secs, unless it's from a whitelisted IP address (We use a set range to pull info to an external dependency which would exceed the rate, so would need them to still do that)

So far, I've tried the following (The IP's and backend-id have been changed for here :) ):

    <set-backend-service id="apim-generated-policy" backend-id="name-of-my-function-app" />
    <rate-limit-by-key calls="60" renewal-period="60" counter-key="@(context.Request.IpAddress)" increment-condition="@(context.Response.StatusCode == 204 ^ context.Response.StatusCode == 404)" remaining-calls-variable-name="remainingCallsPerIP" />
    <ip-filter action="allow">
        <address-range from="10.0.0.0" to="10.0.0.254"/>
        <address-range from="10.1.0.0" to="10.1.0.254"/>
        <address-range from="10.2.0.0" to="10.2.0.254"/>
        <address>10.20.30.40</address>
    </ip-filter>

I have the 'rate-limit-by-key calls' portion working on another project - but the issue is when I try to apply an IP filter/whitelist into it.

What I'm finding is that the rate limit isn't applying using the above code, but it's applying a rate limit, but only if you're part of that IP filter.

I reckon I need to try slip in an IF module somehow so that if you're part of that IP range, it would ignore the calls? Would that be the best way of creating the policy, or is there another way?

1

There are 1 best solutions below

1
On

Managed to fiddle around with it, and I've answered my own question.

If anyone needs it, the answer is:

<policies>
<inbound>
<base />
<set-backend-service id="apim-generated-policy" backend-id="name-of-my-function-app" />
<rate-limit-by-key calls="100" renewal-period="60" counter-key="@(context.Request.Ip)" >
<whitelist>
<add ip="10.0.0.0/24"/>
<add ip="10.1.0.0/24"/>
<add ip="10.2.0.0/24"/>
<add ip="20.77.50.57"/>
  </whitelist>
  <on-exceeded>
    <return-response>
      <set-status code="429" reason="Too Many Requests" />
    </return-response>
  </on-exceeded>
</rate-limit-by-key>
</inbound>
</policies>