Skip to content

fix(limit): unable to obtain new tokens when frequently accessing redis token bucket #4700

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions core/limit/tokenscript.lua
Original file line number Diff line number Diff line change
@@ -18,14 +18,21 @@ if last_refreshed == nil then
end

local delta = math.max(0, now-last_refreshed)
local filled_tokens = math.min(capacity, last_tokens+(delta*rate))
local add = delta * rate
local filled_tokens = math.min(capacity, last_tokens+add)
local allowed = filled_tokens >= requested
local new_tokens = filled_tokens
if allowed then
new_tokens = filled_tokens - requested
end

redis.call("setex", KEYS[1], ttl, new_tokens)
redis.call("setex", KEYS[2], ttl, now)
if new_tokens ~= last_tokens then
redis.call("setex", KEYS[1], ttl, new_tokens)
end

if add > 0 then
redis.call("setex", KEYS[2], ttl, now)
end

return allowed

return allowed