redis-doc
redis-doc copied to clipboard
Command INCR - Pattern: Rate limiter
Hi,
The Pattern: Rate limiter in command INCR doc [1] has a case to be invalid.
When the request count haven't hit the quota, if fire huge of requests at the same time, most/many of those may cross the validation. The time window exists between after the checking and updating the counter. I verified the issue by created num of threads and execute the example code in Java.
It can be fixed by put in a Lua script like:
local current = tonumber(redis.call("get", "the key"))
if (current ~= nil and current >= 10) then
error("too many requests per second")
end
redis.call("incr", "the key")
redis.call("expire", "the key", 10)
This is a common case for heavy traffic system/API or protected from attack. I think it's better to update this or mention in the doc.
Thanks!
I write a blog post in detail here: http://atealxt.github.io/2016/12/11/redis-pattern-rate-limiter.html
Hi @atealxt,
It would be best if you could just open a PR with the proposed changed to the doc - I'm not sure where you want to apply them.
Also please note that in the script you've supplied you're not using the KEYS
and ARGV
tables to pass the key names and script arguments.