Search code examples
.net-coreasp.net-web-apibackendrate-limiting.net-7.0

How to increase Rate Limit at runtime?


I've read the docs but couldn't see if it is possible.

For example, how to implement a token bucket limiter that is increased limit if user pays for it? There is autoReplenish property but what happens if you set it to false? Can we increase the limit at runtime? Is there an injectable service for it?

Has anyone experienced it?


Solution

  • For example, how to implement a token bucket limiter that is increased limit if user pays for it?

    The doc shows something very similar to what you have requested - you can return different partition keys and limiters for paid and unpaid users:

    builder.Services.AddRateLimiter(opts => opts
        .AddPolicy(policyName: "somePolicyName", partitioner: httpContext =>
        {
            var userName = httpContext.User.Identity?.Name ?? string.Empty;
    
            // determine somehow if user is paid, for example set corresponding claim for token
            // or any other method:
            var isPaid = httpContext.User.HasClaim("paid", "true");
            if (isPaid)
            {
                return RateLimitPartition.GetTokenBucketLimiter("Paid!:" + userName, _ =>
                    new TokenBucketRateLimiterOptions 
                    {
                        // values for paid users
                    });
            }
    
            return RateLimitPartition.GetTokenBucketLimiter("Unpaid!:" + userName, _ =>
                new TokenBucketRateLimiterOptions
                {
                    // values for free users
                });
        }));