Skip to content

Commit cadf138

Browse files
author
omarmohamed
committed
add cache threshold
1 parent eef6457 commit cadf138

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

lua/rate_limit.lua

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ function _M.apply_rate_limiting(ngx, path, key, rule, cache)
1616
end
1717

1818
if provider == 'redis' then
19-
return require('redis').throttle(ngx, cache_key, rule)
19+
return require('redis').throttle(ngx, cache_key, rule, cache)
2020
end
2121

2222
return false

lua/redis.lua

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
local _M = {}
22
local redis = require("resty.redis")
3+
local CACHE_THRESHOLD = 0.001
34

45
-- reference: https://redis.io/learn/develop/dotnet/aspnetcore/rate-limiting/sliding-window
56
local SLIDING_WINDOW_SCRIPT = [[
@@ -29,7 +30,7 @@ function _M.connect(ngx, host, port)
2930
return red
3031
end
3132

32-
function _M.throttle(ngx, cache_key, rule)
33+
function _M.throttle(ngx, cache_key, rule, cache)
3334
if not os.getenv('CACHE_HOST') or not os.getenv('CACHE_PORT') then
3435
ngx.log(ngx.ERR, "Failed to use cache provider, please set both CACHE_HOST and CACHE_PORT")
3536
return false
@@ -48,6 +49,15 @@ function _M.throttle(ngx, cache_key, rule)
4849
return false
4950
end
5051

52+
if res == 1 then
53+
local ttl, err = red:ttl(cache_key)
54+
if ttl and ttl > CACHE_THRESHOLD then
55+
require('util').add_to_local_cache(ngx, cache, cache_key, 1, ttl)
56+
elseif err then
57+
ngx.log(ngx.ERR, "failed to fetch TTL: ", err)
58+
end
59+
end
60+
5161
local ok, err = red:set_keepalive(10000, 100)
5262
if not ok then
5363
ngx.log(ngx.ERR, "failed to set keepalive: ", err)

0 commit comments

Comments
 (0)