Skip to content

Instantly share code, notes, and snippets.

@bilalatli
Last active October 15, 2020 12:01
Show Gist options
  • Select an option

  • Save bilalatli/4178bfc09909585e2c92e20ede336c97 to your computer and use it in GitHub Desktop.

Select an option

Save bilalatli/4178bfc09909585e2c92e20ede336c97 to your computer and use it in GitHub Desktop.
Redis Rate Limiter (LUA Script)

Installation

Install this lua script into redis server.

Bash Install

redis-cli SCRIPT LOAD "$(cat redis-rate-limiter.lua)"

// This command return your script name for execute

PHP Install

$redis = new Redis();
$luaHash = $redis->script('LOAD', "{Your Lua Script}");

// $luaHash - is your script name for execute

Execution

For example is your lua hash : 0f1aebdd29a98ffa61bf5406f54aa8a9b8bc1be8

Bash Execution

// redis-cli EVALSHA 1 {RedisKey} {HitCount} {MilliSecond}
redis-cli EVALSHA 1 RateLimit:AUTH_TOKEN 5 10000

// It means, RateLimit:AUTH_TOKEN can send 5 request in 10 second.
local cnt = redis.call('INCR', KEYS[1])
if cnt > tonumber(ARGV[1])
then
return tonumber(cnt) - tonumber(ARGV[1])
end
if cnt == 1
then
redis.call('PEXPIRE', KEYS[1], ARGV[2])
end
return 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment