Reputation: 955
Is there a way to use .NET 7 Rate Limiting on Azure Function v4 (dotnet-isolated) HttpTrigger?
I've added RateLimiter in my ConfigureServices like this:
var builder = new HostBuilder()
.ConfigureFunctionsWorkerDefaults()
.ConfigureServices(s =>
{
// ...
s.AddRateLimiter(_ =>
{
_.AddPolicy("myfunction", httpContext =>
RateLimitPartition.GetSlidingWindowLimiter(httpContext.Request.Headers["X-Forwarded-For"],
_ => new SlidingWindowRateLimiterOptions
{
AutoReplenishment = true,
PermitLimit = 1,
Window = TimeSpan.FromSeconds(5)
}));
});
})
.Build();
and
[Function("myfunction")]
[EnableRateLimiting("myfunction")]
public async Task<IActionResult> MyFunction(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequestData req)
{ // ...
}
I'm pretty sure it shouldn't even work like this, but just to give an example of the scenario. My architecture is Azure Static Web App --> API Management (NOTE! consumption plan) --> Azure Function, and I can get the valid client IP from the X-Forwarded-For
header in the Azure Function, but
So, is it possible to apply the rate limiting policy to a Azure Function on a function level?
Thanks!
Upvotes: 0
Views: 1601
Reputation: 312
Just ported ThrottlingTroll to Azure Functions (.NET 7 Isolated).
Works as an Azure Functions Middleware.
Supports
429 TooManyRequests
or impeding
responses from HTTP-triggered functions),429 TooManyRequests
from egress to ingress.Stores counters in memory or in a distributed cache.
Install from NuGet:
dotnet add package ThrottlingTroll.AzureFunctions
and then configure like this:
builder.ConfigureFunctionsWorkerDefaults((hostBuilderContext, workerAppBuilder) => {
workerAppBuilder.UseThrottlingTroll(hostBuilderContext, options =>
{
options.Config = new ThrottlingTrollConfig
{
Rules = new[]
{
new ThrottlingTrollRule
{
UriPattern = "myfunction",
LimitMethod = new FixedWindowRateLimitMethod
{
PermitLimit = 1,
IntervalInSeconds = 5
},
// Identifying clients by their IP addresses
IdentityIdExtractor = request =>
{
request.Headers.TryGetValue("x-forwarded-for", out var clientIpAddress);
return clientIpAddress;
}
}
}
};
});
});
Upvotes: 4
Reputation: 8694
As @Silent mentioned, you can use rate-limiting policy in Azure APIM Consumption Plan.
You can import multiple Function APIS to the Azure APIM Service and can add the Rate-limiting policy to each API Level.
I have consumption plan APIM, and I’d very much like to have a IP based rate limiter instead of API based, like it is with consumption plan APIM
I understand that you need to limit the number of requests per IP basis. If yes and this is the scenario, we have “IP address throttling” concept to limit the requests/API Calls from the IP address as mentioned in this MS Doc of Custom key-based throttling in Rate-limiting policy.
Note:
Yes, the rate-limit-by-key
is not available in APIM Consumption Plan.
Upvotes: 1