Using rate limitation for files smaller than the defined limit.

leki75 nginx-forum at nginx.us
Mon Jul 30 12:22:42 UTC 2012


Hi!

We use nginx rate limiting function but realized that it does not work
for files smaller than the limit specified in limit_rate directive.
Analyzing the source code it turned out that forcing the limit is second
based. We modified the source to be able to rate limit more precisely
and it also works for smaller files.

Here is the patch:
leki at szunyog:~/src/agwlimit/nginx-1.2.2$ diff -u
src/http/ngx_http_write_filter_module.c{.old,}
--- src/http/ngx_http_write_filter_module.c.old 2012-07-30
08:32:13.155354399 +0200
+++ src/http/ngx_http_write_filter_module.c     2012-07-30
13:55:01.074823215 +0200
@@ -211,8 +211,15 @@
     }
 
     if (r->limit_rate) {
-        limit = r->limit_rate * (ngx_time() - r->start_sec + 1)
-                - (c->sent - clcf->limit_rate_after);
+        if (ngx_cached_time->msec < r->start_msec) {
+            limit = r->limit_rate * (ngx_time() - r->start_sec - 1)
+                    + r->limit_rate * (ngx_cached_time->msec + 1000 -
r->start_msec) / 1000
+                    - (c->sent - clcf->limit_rate_after);
+        } else {
+            limit = r->limit_rate * (ngx_time() - r->start_sec)
+                    + r->limit_rate * (ngx_cached_time->msec -
r->start_msec) / 1000
+                    - (c->sent - clcf->limit_rate_after);
+        }
 
         if (limit <= 0) {
             c->write->delayed = 1;

As we tested the pathced nginx it worked fine. Could we use it in
production or do you see any mistakes we made? Is there any reason you
don't count on milliseconds?

Regards,
    Gabor

Posted at Nginx Forum: http://forum.nginx.org/read.php?2,229094,229094#msg-229094



More information about the nginx mailing list