@@ -9,22 +9,22 @@ internal class RedisFixedWindowManager
9
9
private readonly IConnectionMultiplexer _connectionMultiplexer ;
10
10
private readonly RedisFixedWindowRateLimiterOptions _options ;
11
11
private readonly RedisKey RateLimitKey ;
12
+ private readonly RedisKey RateLimitExpireKey ;
12
13
13
14
private static readonly LuaScript _redisScript = LuaScript . Prepare (
14
- @"local expires_at_key = @rate_limit_key .. "":exp""
15
- local expires_at = tonumber(redis.call(""get"", expires_at_key))
15
+ @"local expires_at = tonumber(redis.call(""get"", @expires_at_key))
16
16
17
17
if not expires_at or expires_at < tonumber(@current_time) then
18
18
-- this is either a brand new window,
19
19
-- or this window has closed, but redis hasn't cleaned up the key yet
20
20
-- (redis will clean it up in one more second)
21
21
-- initialize a new rate limit window
22
22
redis.call(""set"", @rate_limit_key, 0)
23
- redis.call(""set"", expires_at_key, @next_expires_at)
23
+ redis.call(""set"", @ expires_at_key, @next_expires_at)
24
24
-- tell Redis to clean this up _one second after_ the expires_at time (clock differences).
25
25
-- (Redis will only clean up these keys long after the window has passed)
26
26
redis.call(""expireat"", @rate_limit_key, @next_expires_at + 1)
27
- redis.call(""expireat"", expires_at_key, @next_expires_at + 1)
27
+ redis.call(""expireat"", @ expires_at_key, @next_expires_at + 1)
28
28
-- since the database was updated, return the new value
29
29
expires_at = @next_expires_at
30
30
end
@@ -43,6 +43,7 @@ public RedisFixedWindowManager(
43
43
_connectionMultiplexer = options . ConnectionMultiplexerFactory ! . Invoke ( ) ;
44
44
45
45
RateLimitKey = new RedisKey ( $ "rl:{ partitionKey } ") ;
46
+ RateLimitExpireKey = new RedisKey ( $ "rl:{ partitionKey } :exp") ;
46
47
}
47
48
48
49
internal async Task < RedisFixedWindowResponse > TryAcquireLeaseAsync ( )
@@ -57,6 +58,7 @@ internal async Task<RedisFixedWindowResponse> TryAcquireLeaseAsync()
57
58
new
58
59
{
59
60
rate_limit_key = RateLimitKey ,
61
+ expires_at_key = RateLimitExpireKey ,
60
62
next_expires_at = now . Add ( _options . Window ) . ToUnixTimeSeconds ( ) ,
61
63
current_time = nowUnixTimeSeconds ,
62
64
increment_amount = 1D ,
@@ -86,6 +88,7 @@ internal RedisFixedWindowResponse TryAcquireLease()
86
88
new
87
89
{
88
90
rate_limit_key = RateLimitKey ,
91
+ expires_at_key = RateLimitExpireKey ,
89
92
next_expires_at = now . Add ( _options . Window ) . ToUnixTimeSeconds ( ) ,
90
93
current_time = nowUnixTimeSeconds ,
91
94
increment_amount = 1D ,
0 commit comments