Skip to content

Commit 01c76f7

Browse files
authored
fix(rate-limiting) remove unneeded phase handlers for better accuracy (Kong#6802)
### Summary The PR Kong#5460 tried to fix rate-limiting accuracy issues as reported with Kong#5311. That PR has stayed open for over a year now. There is a smaller change in that PR that we can make without a lot of work or debating, and this PR contains that only: 1. it removes extra phase handlers and context passing of data and now does everything in `access` phase (this could make it more accurate as well, compared to post-poning that to log phase) 2. it now also sets rate-limiting headers when the limits have exceeded
1 parent 3ea85fe commit 01c76f7

File tree

1 file changed

+11
-25
lines changed

1 file changed

+11
-25
lines changed

kong/plugins/rate-limiting/handler.lua

Lines changed: 11 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ local RateLimitingHandler = {}
4747

4848

4949
RateLimitingHandler.PRIORITY = 901
50-
RateLimitingHandler.VERSION = "2.2.0"
50+
RateLimitingHandler.VERSION = "2.2.1"
5151

5252

5353
local function get_identifier(conf)
@@ -145,8 +145,9 @@ function RateLimitingHandler:access(conf)
145145
if usage then
146146
-- Adding headers
147147
local reset
148+
local headers
148149
if not conf.hide_client_headers then
149-
local headers = {}
150+
headers = {}
150151
local timestamps
151152
local limit
152153
local window
@@ -182,38 +183,23 @@ function RateLimitingHandler:access(conf)
182183
headers[RATELIMIT_LIMIT] = limit
183184
headers[RATELIMIT_REMAINING] = remaining
184185
headers[RATELIMIT_RESET] = reset
185-
186-
kong.ctx.plugin.headers = headers
187186
end
188187

189188
-- If limit is exceeded, terminate the request
190189
if stop then
191-
return kong.response.error(429, "API rate limit exceeded", {
192-
[RETRY_AFTER] = reset
193-
})
190+
headers = headers or {}
191+
headers[RETRY_AFTER] = reset
192+
return kong.response.error(429, "API rate limit exceeded", headers)
194193
end
195-
end
196194

197-
kong.ctx.plugin.timer = function()
198-
local ok, err = timer_at(0, increment, conf, limits, identifier, current_timestamp, 1)
199-
if not ok then
200-
kong.log.err("failed to create timer: ", err)
195+
if headers then
196+
kong.response.set_headers(headers)
201197
end
202198
end
203-
end
204-
205-
206-
function RateLimitingHandler:header_filter(_)
207-
local headers = kong.ctx.plugin.headers
208-
if headers then
209-
kong.response.set_headers(headers)
210-
end
211-
end
212-
213199

214-
function RateLimitingHandler:log(_)
215-
if kong.ctx.plugin.timer then
216-
kong.ctx.plugin.timer()
200+
local ok, err = timer_at(0, increment, conf, limits, identifier, current_timestamp, 1)
201+
if not ok then
202+
kong.log.err("failed to create timer: ", err)
217203
end
218204
end
219205

0 commit comments

Comments
 (0)