Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nginx set remaining count for limit_req in X-RateLimit-Remaining header

I'm actually a little surprised that I couldn't find anything after a couple hours of googling, but the problem is as follows:

I want nginx to serve as my throttle for my API.

My config file contains a well-cited example of limit_req_zone:

limit_req_zone $binary_remote_addr zone=limit:2m rate=10r/m;

along with my location directive containing the expected limit_req zone=limit nodelay;

I would love to have nginx attach headers to the response message for both the X-RateLimit-Remaining and X-RateLimit-Reset attributes. Basically have nginx use the active count of the rate=10r/m to populate X-RateLimit-Remaining and timeframe of the same rate=10r/m value to populate X-RateLimit-Reset with how many seconds are left before a refresh.

http {
    limit_req_zone $binary_remote_addr zone=login:10m rate=2r/s;
    limit_req_status 429;
    limit_conn_status 429;

    server {
        listen       80;
        server_name  [removed];

        location / {
            limit_req zone=limit nodelay;

            proxy_pass http://reverse-proxy-example;
            add_header  X-RateLimit-Remaining [nginx variable?];
            add_header  X-RateLimit-Reset [nginx variable?]
        }
}

Thoughts? Possible? Would love to avoid hitting the application to get these numbers.

like image 407
shaselton Avatar asked Sep 05 '25 08:09

shaselton


1 Answers

I would say that this isn't possible with the upstream version of nginx.

You can find the documentation for the limit_req directive through http://nginx.org/r/limit_req, which redirects to http://nginx.org/docs/http/ngx_http_limit_req_module.html#limit_req, which conclusively shows that the module doesn't have any known variables within it.

Looking at http://ngx.su/src/http/modules/ngx_http_limit_req_module.c confirms the conjecture.

Another option is to look at http://nginx.org/docs/varindex.html, which lists all the variables — looking for limit will only get you to $limit_rate, which is an unrelated variable.


P.S. Consider that the limit_req is done through a leaky bucket method.

  • https://en.wikipedia.org/wiki/Leaky_bucket

Without going into further details or making stuff up (the wikipedia article is huge!), I'd guess that it may not be entirely trivial to present this information to the end user in a consistent and actionable manner.

like image 191
cnst Avatar answered Sep 09 '25 01:09

cnst