Last active
August 29, 2015 14:01
-
-
Save mezzatto/ea6f769c6d5c1eb0a55a to your computer and use it in GitHub Desktop.
sorted set rate limiter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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