Skip to content

Instantly share code, notes, and snippets.

@hpirosha
Last active August 29, 2015 13:56
Show Gist options
  • Save hpirosha/8972921 to your computer and use it in GitHub Desktop.
Save hpirosha/8972921 to your computer and use it in GitHub Desktop.
--[[
RATELIMIT LUA script does the following :
1. Increments counter for the supplied bucket.
2. Deletes the subsequent buckets.
3. Renews expiry time for the subjectKey
KEYS[1]: subject's key
ARGV[1]: bucket number
ARGV[2]: subject expiry in seconds
ARGV[3]: buckets to clear ahead
ARGV[4]: bucket count
RETURNS: nothing
]]
-- increment the bucket counter
redis.call('HINCRBY', KEYS[1], ARGV[1], 1)
-- clear the buckets ahead, create space separated bucket ids
local buckets = ARGV[3]
local ids = ''
for i=1, buckets do
local id = (ARGV[1] + i) % ARGV[4]
if (i == 1) then
ids = id
else
ids = ids .. ' ' .. id
end
end
redis.call('HDEL', KEYS[1], ids)
-- renew the key's expiry time
redis.call('EXPIRE',KEYS[1], ARGV[2])
return ids
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment