Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RateLimiting in dotnet 7

I have been implementing RateLimiting in dotnet 7, but when it reaches the limit it blocks all endpoints. I only want to block the one requested endpoint by the ip user when it get the limit.

This is my code in the Startup file in ConfigureServices:

       services.AddRateLimiter(options =>
        {
            options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(content =>
                RateLimitPartition.GetFixedWindowLimiter(
                    partitionKey: content.Request.Headers.Host.ToString(),
                    factory: partition => new FixedWindowRateLimiterOptions
                    {
                        AutoReplenishment = true,
                        PermitLimit = 5,
                        QueueLimit = 0,
                        Window = TimeSpan.FromSeconds(20)
                    }
                    ));
            options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
        });
like image 459
David Ruiz Avatar asked Sep 03 '25 02:09

David Ruiz


1 Answers

You can try this ,you can modify your rate limiter implementation to use a per-endpoint rate limiter instead of a global rate limiter.

services.AddRateLimiter(options =>
{
    options.EndpointLimiterFactory = (context, endpointKey) =>
        PartitionedRateLimiter.Create<string, string>(key =>
            RateLimitPartition.GetFixedWindowLimiter(
                partitionKey: key,
                factory: partition => new FixedWindowRateLimiterOptions
                {
                    AutoReplenishment = true,
                    PermitLimit = 5,
                    QueueLimit = 0,
                    Window = TimeSpan.FromSeconds(20)
                })
            )(endpointKey);
    options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
});

we're using the EndpointLimiterFactory property to create a new PartitionedRateLimiter instance for each endpoint. The endpointKey parameter is used as the partition key for the rate limiter.

With this configuration, each endpoint will have its own rate limiter instance, allowing you to enforce per-endpoint rate limits without blocking all endpoints when the rate limit is exceeded for a specific endpoint.

like image 136
Zeeshan Avatar answered Sep 04 '25 17:09

Zeeshan