Last active
April 19, 2017 21:02
-
-
Save x0bandeira/49830f80f49c8b8d6589 to your computer and use it in GitHub Desktop.
Shared throttling mechanism with Redis
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- KEYS[1] namespace/key | |
-- ARGV[1] current timestamp | |
-- ARGV[2] max uses per second | |
local t = tonumber(redis.call("get", KEYS[1] .. ":t")) or 0 | |
local c = tonumber(redis.call("get", KEYS[1] .. ":c")) or 0 | |
local current = tonumber(ARGV[1]) | |
local max = tonumber(ARGV[2]) | |
if current - t >= 1 then | |
redis.call("mset", KEYS[1] .. ":t", current, KEYS[1] .. ":c", 1) | |
return {current, 1, 1} | |
elseif c >= max then | |
return {t, c, 0} | |
else | |
redis.call("incr", KEYS[1] .. ":c") | |
return {t, c + 1, 1} | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment