ratelimit

Simple rate limiter

Returns 1 if rate limit exceeded, otherwise 0
Keys
  1. Key to use as an expiring counter, e.g. "ratelimit:ip:127.0.0.1"
Args
  1. Maximum number of calls
  2. Amount of time in milliseconds

Example

This example sets a rate limit of 5 calls per 10 seconds. Repeatedly running the script 6 times in under ten seconds, we see the rate-limiter's effect.

> evalsha 089ccf077629d371793d5e928a3f06e9e483eb08 1 ratelimit:192.168.1.1 5 10000
(integer) 0
> evalsha 089ccf077629d371793d5e928a3f06e9e483eb08 1 ratelimit:192.168.1.1 5 10000
(integer) 0
> evalsha 089ccf077629d371793d5e928a3f06e9e483eb08 1 ratelimit:192.168.1.1 5 10000
(integer) 0
> evalsha 089ccf077629d371793d5e928a3f06e9e483eb08 1 ratelimit:192.168.1.1 5 10000
(integer) 0
> evalsha 089ccf077629d371793d5e928a3f06e9e483eb08 1 ratelimit:192.168.1.1 5 10000
(integer) 0
> evalsha 089ccf077629d371793d5e928a3f06e9e483eb08 1 ratelimit:192.168.1.1 5 10000
(integer) 1

Source

local cnt = redis.call('INCR', KEYS[1])
if cnt > tonumber(ARGV[1])
then
  return 1
end
if cnt == 1
then
  redis.call('PEXPIRE', KEYS[1], ARGV[2])
end
return 0

SHA

089ccf077629d371793d5e928a3f06e9e483eb08

Last updated 30 Jul 2014.

← More scripts from the Memetria Library

License

All scripts on this site are in the public domain, unless otherwise noted, and are provided without warranty express or implied. Memetria make no claim for the effectiveness, safety, security or quality of the scripts contained within.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.