Skip to content

Instantly share code, notes, and snippets.

@vseryakov
Last active June 12, 2017 22:56
Show Gist options
  • Save vseryakov/da179d7a59c7dee61712 to your computer and use it in GitHub Desktop.
Save vseryakov/da179d7a59c7dee61712 to your computer and use it in GitHub Desktop.
local name = KEYS[1];
local rate = tonumber(KEYS[2]);
local max = tonumber(KEYS[3]);
local interval = tonumber(KEYS[4]);
local now = tonumber(KEYS[5]);
local count = tonumber(redis.call('HGET', name, 'count'));
local mtime = tonumber(redis.call('HGET', name, 'mtime'));
if not mtime then
count = max;
mtime = now;
end
if now < mtime then
mtime = now - interval;
end
if count < max then
count = math.min(max, count + rate * ((now - mtime) / interval));
redis.call('HSET', name, 'count', count);
end
redis.call('HSET', name, 'mtime', now);
if count < 1 then
return 0;
else
redis.call('HSET', name, 'count', count - 1);
return 1;
end
@vseryakov
Copy link
Author

Testing:

for d in 1 2 3 4 5; do redis-cli --eval rate.lua b 3 3 1000 $(node -e 'console.log(Date.now())'); done

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment