Skip to content

Instantly share code, notes, and snippets.

@dolfly
Forked from florentchauveau/bucket_add.lua
Created October 19, 2018 08:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dolfly/8df10ae1ad3fe2e7ce5a66eaa30d2ac0 to your computer and use it in GitHub Desktop.
Save dolfly/8df10ae1ad3fe2e7ce5a66eaa30d2ac0 to your computer and use it in GitHub Desktop.
Redis script (Lua) to add an event to a token bucket
-- Redis script to add an event to a token bucket
-- see https://medium.com/callr-techblog/rate-limiting-for-distributed-systems-with-redis-and-lua-eeea745cb260
-- (c) Florent CHAUVEAU <florent.chauveau@gmail.com>
local ts = tonumber(ARGV[1])
-- set the token bucket to 1 second (rolling)
local min = ts -1
-- iterate overs keys
for i,key in pairs(KEYS) do
-- remove tokens < min
redis.call('ZREMRANGEBYSCORE', key, '-inf', min)
-- add a new token (ts)
redis.call('ZADD', key, ts, ts)
-- make the key expire in 10s
redis.call('EXPIRE', key, 10)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment