Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 862
Baran Avatar asked Mar 09 '26 17:03

Baran


1 Answers

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
            });
    }));
like image 146
Guru Stron Avatar answered Mar 15 '26 05:03

Guru Stron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!