Skip to content

Instantly share code, notes, and snippets.

@callhub
Created February 3, 2014 09:48
Show Gist options
  • Save callhub/8781114 to your computer and use it in GitHub Desktop.
Save callhub/8781114 to your computer and use it in GitHub Desktop.
Lua script for atomic API rate checking in Redis
local current, expected, cur_val, callcount, maxcps
current = redis.call('GET', KEYS[1])
callcount = tonumber(ARGV[1])
maxcps = tonumber(ARGV[2])
cur_val = 0
if current then
cur_val = tonumber(current)
end
expected = cur_val + callcount
if expected > maxcps then
return nil
else
redis.call('incrby', KEYS[1], callcount)
redis.call('expire', KEYS[1], 10)
return 1
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment