Skip to content

Commit 8911787

Browse files
committed
Fix FixedWindow cluster key
fixes #25
1 parent cdd244f commit 8911787

File tree

1 file changed

+7
-4
lines changed

1 file changed

+7
-4
lines changed

src/RedisRateLimiting/FixedWindow/RedisFixedWindowManager.cs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,22 +9,22 @@ internal class RedisFixedWindowManager
99
private readonly IConnectionMultiplexer _connectionMultiplexer;
1010
private readonly RedisFixedWindowRateLimiterOptions _options;
1111
private readonly RedisKey RateLimitKey;
12+
private readonly RedisKey RateLimitExpireKey;
1213

1314
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))
1616
1717
if not expires_at or expires_at < tonumber(@current_time) then
1818
-- this is either a brand new window,
1919
-- or this window has closed, but redis hasn't cleaned up the key yet
2020
-- (redis will clean it up in one more second)
2121
-- initialize a new rate limit window
2222
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)
2424
-- tell Redis to clean this up _one second after_ the expires_at time (clock differences).
2525
-- (Redis will only clean up these keys long after the window has passed)
2626
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)
2828
-- since the database was updated, return the new value
2929
expires_at = @next_expires_at
3030
end
@@ -43,6 +43,7 @@ public RedisFixedWindowManager(
4343
_connectionMultiplexer = options.ConnectionMultiplexerFactory!.Invoke();
4444

4545
RateLimitKey = new RedisKey($"rl:{partitionKey}");
46+
RateLimitExpireKey = new RedisKey($"rl:{partitionKey}:exp");
4647
}
4748

4849
internal async Task<RedisFixedWindowResponse> TryAcquireLeaseAsync()
@@ -57,6 +58,7 @@ internal async Task<RedisFixedWindowResponse> TryAcquireLeaseAsync()
5758
new
5859
{
5960
rate_limit_key = RateLimitKey,
61+
expires_at_key = RateLimitExpireKey,
6062
next_expires_at = now.Add(_options.Window).ToUnixTimeSeconds(),
6163
current_time = nowUnixTimeSeconds,
6264
increment_amount = 1D,
@@ -86,6 +88,7 @@ internal RedisFixedWindowResponse TryAcquireLease()
8688
new
8789
{
8890
rate_limit_key = RateLimitKey,
91+
expires_at_key = RateLimitExpireKey,
8992
next_expires_at = now.Add(_options.Window).ToUnixTimeSeconds(),
9093
current_time = nowUnixTimeSeconds,
9194
increment_amount = 1D,

0 commit comments

Comments
 (0)