Skip to content

Instantly share code, notes, and snippets.

@ryanlewis
Forked from florentchauveau/leaky_bucket.lua
Created March 16, 2021 00:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanlewis/dadc5e0ad55cceb388161549e86fa5a3 to your computer and use it in GitHub Desktop.
Save ryanlewis/dadc5e0ad55cceb388161549e86fa5a3 to your computer and use it in GitHub Desktop.
Redis script (Lua) to implement a leaky bucket
-- Redis script to implement a leaky 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])
local cps = tonumber(ARGV[2])
local key = KEYS[1]
-- remove tokens < min (older than now() -1s)
local min = ts -1
redis.call('ZREMRANGEBYSCORE', key, '-inf', min)
local last = redis.call('ZRANGE', key, -1, -1)
local next = ts
if type(last) == 'table' and #last > 0 then
for key,value in pairs(last) do
next = tonumber(value) + 1/cps
break -- break at first item
end
end
if ts > next then
-- the current ts is > than last+1/cps
-- we'll keep ts
next = ts
end
redis.call('ZADD', key, next, next)
return tostring(next - ts)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment