Tuesday, 28 May 2024

Rate limiting in asp.net core

 There are 4 rate limiting algorithms:

Fixed window : The AddFixedWindowLimiter method uses a fixed time window to limit requests. When the time window expires, a new time window starts and the request limit is reset.

below are steps to configure fixed window rate limiter

1. Add Rate Limiter:

       builder.Services.AddRateLimiter(_ => _
                .AddFixedWindowLimiter(policyName: fixedPolicy, options =>
                {
                    options.PermitLimit = myOptions.PermitLimit;//2, getting values from config
                    options.Window = TimeSpan.FromSeconds(myOptions.Window);//2000 
                    options.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
                    options.QueueLimit = myOptions.QueueLimit;// 2
                    
                }      
             ));
2.      app.UseRateLimiter();

3. call RequireRateLimiting("policyname like fixed") either on minimal api endpoint or MapControllerwithDefaultRoute().

4. We can use [EnableRateLimiter] , [DisableRateLimiter] attributes if we don't want to configure rate limiter globally.
5 we can configure multiple ratelimiting policies on AddRateLimiter and we can use specific policy for specific controller/Action method.

concurrency limiter :
The concurrency limiter limits the number of concurrent requests. Each request reduces the concurrency limit by one. When a request completes, the limit is increased by one. Unlike the other requests limiters that limit the total number of requests for a specified period, the concurrency limiter limits only the number of concurrent requests and doesn't cap the number of requests in a time period

No comments:

Post a Comment

How to create and use middleware in asp.net core

Middleware is piece of code that's assembled into an app pipeline to handle requests and responses.  Each middleware component in the re...