Skip to content

Commit c39c1bf

Browse files
Add TTL to Redis token bucket implementation (#1757)
1 parent 5c50a0a commit c39c1bf

File tree

1 file changed

+16
-7
lines changed

1 file changed

+16
-7
lines changed

pages/rate-limit/token-bucket.md

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -73,27 +73,36 @@ local cost = tonumber(ARGV[3])
7373
local now = tonumber(ARGV[4]) -- Current unix time in seconds
7474

7575
local fields = redis.call("HGETALL", key)
76+
7677
if #fields == 0 then
77-
redis.call("HSET", key, "count", max - cost, "refilled_at", now)
78-
return {1}
78+
local expiresInSeconds = cost * refillIntervalSeconds
79+
redis.call("HSET", key, "count", max - cost, "refilled_at", now)
80+
redis.call("EXPIRE", key, expiresInSeconds)
81+
return {1}
7982
end
83+
8084
local count = 0
8185
local refilledAt = 0
8286
for i = 1, #fields, 2 do
8387
if fields[i] == "count" then
84-
count = tonumber(fields[i+1])
85-
elseif fields[i] == "refilled_at" then
86-
refilledAt = tonumber(fields[i+1])
87-
end
88+
count = tonumber(fields[i+1])
89+
elseif fields[i] == "refilled_at" then
90+
refilledAt = tonumber(fields[i+1])
91+
end
8892
end
93+
8994
local refill = math.floor((now - refilledAt) / refillIntervalSeconds)
9095
count = math.min(count + refill, max)
9196
refilledAt = refilledAt + refill * refillIntervalSeconds
97+
9298
if count < cost then
93-
return {0}
99+
return {0}
94100
end
101+
95102
count = count - cost
103+
local expiresInSeconds = (max - count) * refillIntervalSeconds
96104
redis.call("HSET", key, "count", count, "refilled_at", now)
105+
redis.call("EXPIRE", key, expiresInSeconds)
97106
return {1}
98107
```
99108

0 commit comments

Comments
 (0)