Skip to content

Instantly share code, notes, and snippets.

@mezzatto
Last active August 29, 2015 14:01
Show Gist options
  • Save mezzatto/ea6f769c6d5c1eb0a55a to your computer and use it in GitHub Desktop.
Save mezzatto/ea6f769c6d5c1eb0a55a to your computer and use it in GitHub Desktop.
sorted set rate limiter
local ts = tonumber(table.remove(ARGV))
local weight = tonumber(table.remove(ARGV))
local limit = tonumber(ARGV[1])
redis.call('zremrangebyscore', KEYS[1], 0, tonumber(ts) - 60)
local curr = redis.call('zrangebyscore', KEYS[1], tonumber(ts), tonumber(ts))
redis.call('zremrangebyscore', KEYS[1], tonumber(ts), tonumber(ts))
redis.call('zadd', KEYS[1], ts, tonumber(curr[1] or '0') + tonumber(weight))
local all = redis.call('zrange', KEYS[1], 0, -1)
local total = 0
for i,m in ipairs(all) do
total = tonumber(total) + tonumber(m)
end
redis.call('expire', KEYS[1], 60)
return total > limit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment