openresty / lua-resty-limit-traffic

Lua library for limiting and controlling traffic in OpenResty/ngx_lua
819 stars 150 forks source link

Initialization problem #77

Open bourne-3 opened 6 months ago

bourne-3 commented 6 months ago

I have some confusion as to where limit_req.new should be initialized My requirement is to limit the flow based on rules. For example, depending on the requested URI, the flow limit for each URI may be different. In this case, does it need to be initialized for every request during the access phase? Will this consume a lot of resources? For example, in my access_by_lua file, I have such a function. Among them, rate, uri and brutal are all read from scheduled tasks and will be updated according to the configuration.


local function access_limit()
    local limit_req = require "resty.limit.req"

    local rate = ... // read specific rate from config
    local uri = ... // read specific uri from config
    local brust = ... // read specific rate from config

    local lim, err = limit_req.new("client_white", rate, brust)
    if not lim then
        ngx.log(ngx.ERR,
                "failed to instantiate a resty.limit.req object: ", err)
        return ngx.exit(503)
    end

    local delay, err = lim:incoming(uri, true)
    if not delay then
        if err == "rejected" then
            return ngx.exit(503)
        end
        ngx.log(ngx.ERR, "failed to limit req: ", err)
        return ngx.exit(500)
    end

    if delay >= 0.001 then
        local excess = err
        ngx.log(ngx.ERR,
                "excess: ", excess)

        ngx.sleep(delay)
    end
end

Will this cause limit_req.new to be instantiated for each request, resulting in slower performance? Also, assuming that the rate or brutal under the same URI changes, will reinitialization lead to changes in the previous configuration under the same URI?