Skip to content

Instantly share code, notes, and snippets.

@x0bandeira
Last active April 19, 2017 21:02
Show Gist options
  • Save x0bandeira/49830f80f49c8b8d6589 to your computer and use it in GitHub Desktop.
Save x0bandeira/49830f80f49c8b8d6589 to your computer and use it in GitHub Desktop.
Shared throttling mechanism with Redis
-- 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