Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Redis script (Lua) to implement a leaky bucket
-- Redis script to implement a leaky bucket
-- see
-- (c) Florent CHAUVEAU <>
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'ZREMRANGEBYSCORE', key, '-inf', min)
local last ='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
if ts > next then
-- the current ts is > than last+1/cps
-- we'll keep ts
next = ts
end'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