AspNetCoreRateLimit icon indicating copy to clipboard operation
AspNetCoreRateLimit copied to clipboard

How to persist RateLimiter tokens?

Open DillionVVV opened this issue 1 year ago • 1 comments

I am using .Net RateLimiting and specifically the TokenBucketRateLimiter. Example:

services.AddRateLimiter(limiterOptions =>
{
    limiterOptions.AddPolicy(userPolicyName, context =>
    {
       string username = Utils.getUsername(context);
           return RateLimitPartition.GetTokenBucketLimiter
           (username , _ =>
               new TokenBucketRateLimiterOptions
               {
                   TokenLimit = myOptions.TokenLimit,
                   QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
                   QueueLimit = 0,
                   ReplenishmentPeriod = TimeSpan.FromDays(myOptions.ReplenishmentPeriod),
                   TokensPerPeriod = myOptions.ReplenishmentPeriod,
                   AutoReplenishment = myOptions.AutoReplenishment
               });  
    });
});

This works, but doesn't survive service restarts (tokens get resetted every time the service restarts). From what I could find, it's using internally a memory store for tokens.

How can I change the store used for tokens? I'd prefer to use postgres for persistence if possible, but any kind of persistence will do.

DillionVVV avatar Oct 02 '24 08:10 DillionVVV

You need to use a persistent store (eg: Redis). Check this out https://github.com/cristipufu/aspnetcore-redis-rate-limiting

cristipufu avatar Oct 04 '24 05:10 cristipufu