TExcelTAD

Rate & Connection Limits

A login endpoint that accepts a thousand password guesses per second, a search API that one scraper can saturate, an upload form that accepts a 10 GB body: limits at the proxy protect the app before it spends any work. Nginx has three tools: limit_req (requests per time), limit_conn (concurrent connections) and size limits like client_max_body_size.

limit_req: the leaky bucket

nginx
http {
    limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;   # key, shared memory, rate
    server {
        location = /login {
            limit_req zone=login burst=3 nodelay;
            limit_req_status 429;                                   # the default is 503
            proxy_pass http://app;
        }
    }
}
  • The key decides who shares a budget: $binary_remote_addr (per client IP; the binary form uses 4 or 16 bytes instead of up to 39 characters), $http_authorization or $cookie_session (per user), $server_name (per site). Requests with an empty key aren't limited, which is how geo + map exempt internal networks.
  • rate is enforced with millisecond precision: 10r/s means one request every 100 ms, not "10 in any second". r/m is per minute.
  • burst is a queue for requests that arrive faster than the rate. Without nodelay, queued requests are delayed to match the rate; with nodelay they pass immediately but still use up burst slots, which free up at the rate. delay=N (since 1.15.7) is in between: the first N excess requests pass at once, the rest of the burst are delayed.
  • Excess beyond the burst is rejected with limit_req_status (use 429 Too Many Requests).

Three locations with the same rate (2 requests per second), each hit by 8 requests in quick succession:

bash · try it yourself
mkdir -p www/strict www/burst www/queued
for d in strict burst queued; do echo ok > www/$d/index.html; done
cat > nginx.conf <<'EOF'
pid nginx.pid;
error_log error.log;
events {}
http {
  access_log off;
  limit_req_zone $binary_remote_addr zone=a:1m rate=2r/s;
  limit_req_zone $binary_remote_addr zone=b:1m rate=2r/s;
  limit_req_zone $binary_remote_addr zone=c:1m rate=2r/s;
  limit_req_status 429;
  server {
    listen 127.0.0.1:8080;
    root www;                                   # a static file as the content: see the note below
    location /strict/  { limit_req zone=a; }
    location /burst/   { limit_req zone=b burst=3 nodelay; }
    location /queued/  { limit_req zone=c burst=3; }
  }
}
EOF
nginx -p "$PWD" -c nginx.conf -e stderr
for loc in strict burst; do
  echo "$loc: $(for i in $(seq 8); do curl -s -o /dev/null -w '%{http_code} ' 127.0.0.1:8080/$loc/; done)"
done
(for i in $(seq 8); do curl -s -o /dev/null -w '%{http_code} %{time_total}\n' 127.0.0.1:8080/queued/ & done; wait) > queued.txt
echo "queued: $(cut -d' ' -f1 queued.txt | sort | uniq -c | xargs)"
awk '$1==200 && $2>m {m=$2} END {print (m>1.2 && m<1.8) ? "slowest accepted request: about 1.5 s" : "unexpected: " m}' queued.txt
grep -c 'limiting requests' error.log
nginx -p "$PWD" -c nginx.conf -e stderr -s quit 2>/dev/null
strict: 200 429 429 429 429 429 429 429
burst: 200 200 200 200 429 429 429 429
queued: 4 200 4 429
slowest accepted request: about 1.5 s
15
  • strict (no burst): only the first request passed; the next one arrived a few milliseconds later, long before the 500 ms the rate allows.
  • burst=3 nodelay: the first request plus three burst slots passed immediately, then 429s. This is usually what you want for APIs: no added latency for short bursts, a hard cap for floods.
  • burst=3 (queued): 4 requests also passed, but the queued ones were held back to the rate, so the last accepted one took about 1.5 s. Delaying is friendly to browsers loading many resources but ties up connections.

Note: the session serves small files rather than writing return 200; in the locations. return runs in the rewrite phase, which comes before the phase where limit_req and limit_conn act (How Nginx Processes a Request), so a location that ends in return is never rate-limited. Real endpoints use proxy_pass or files, which run after the limits.

Every rejection is logged in the error log (limiting requests, excess: … by zone "a"; the 15 lines counted above are 7 + 4 + 4 rejections). Before enforcing a new limit, run it with limit_req_dry_run on; (since 1.17.1): nothing is rejected, but the log shows who would have been, and $limit_req_status (since 1.17.6) can go into the access log.

Choosing the key and the numbers

Pitfall Effect Fix
per-IP limits behind a load balancer every client has the balancer's IP and shares one budget realip module with set_real_ip_from the balancer's range
per-IP limits for offices, mobile carriers (CGNAT) thousands of users behind one address per-user key for logged-in traffic, generous per-IP limits
one zone for the whole site a page with 40 assets eats the budget limit only expensive endpoints: login, search, export, password reset
rate=1r/s for an API used by scripts a client sending 2 requests in 100 ms gets a 429 allow a burst

Several limit_req lines can apply to the same location (all must pass): for example a per-IP limit plus a per-server global limit that protects the backend as a whole.

limit_conn: concurrent connections

limit_conn counts requests in progress per key. It suits downloads, long requests and slow endpoints, where the number of open requests, not their rate, is what hurts:

bash · try it yourself
cat > app.py <<'EOF'
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
class H(BaseHTTPRequestHandler):
    def do_GET(self):
        time.sleep(1); self.send_response(200); self.end_headers(); self.wfile.write(b"report\n")
    def do_POST(self):
        self.rfile.read(int(self.headers["Content-Length"])); self.send_response(200); self.end_headers()
    def log_message(self, *a): pass
ThreadingHTTPServer(("127.0.0.1", 9000), H).serve_forever()
EOF
python3 app.py &
for i in $(seq 50); do curl -s -X POST -d x 127.0.0.1:9000/ > /dev/null && break; sleep 0.1; done
cat > nginx.conf <<'EOF'
pid nginx.pid;
error_log error.log;
events {}
http {
  access_log off;
  limit_conn_zone $binary_remote_addr zone=perip:1m;
  limit_conn_status 429;
  server {
    listen 127.0.0.1:8080;
    client_max_body_size 1k;
    location /reports/ { limit_conn perip 2; proxy_pass http://127.0.0.1:9000; }
    location /upload   { proxy_pass http://127.0.0.1:9000; }
  }
}
EOF
nginx -p "$PWD" -c nginx.conf -e stderr
(for i in 1 2 3 4 5; do curl -s -o /dev/null -w '%{http_code}\n' 127.0.0.1:8080/reports/q & done; wait) > statuses.txt
echo "5 parallel reports: $(sort statuses.txt | uniq -c | xargs)"
head -c 500  /dev/zero | curl -s -o /dev/null -w "500 B upload: %{http_code}\n" --data-binary @- 127.0.0.1:8080/upload
head -c 5000 /dev/zero | curl -s -o /dev/null -w "5 kB upload:  %{http_code}\n" --data-binary @- 127.0.0.1:8080/upload
nginx -p "$PWD" -c nginx.conf -e stderr -s quit 2>/dev/null; kill %1
5 parallel reports: 2 200 3 429
500 B upload: 200
5 kB upload:  413

Two reports ran at once; the other three were refused immediately instead of piling up on the backend. The 5 kB upload was rejected with 413 ("Content Too Large" in current HTTP; Nginx 1.24 still says "Request Entity Too Large") before any of it reached the app (the default client_max_body_size is 1m; raise it per location for upload endpoints only).

Slow clients

A different attack opens many connections and sends headers or bodies one byte at a time (Slowloris). Nginx's event model makes idle connections cheap, and the timeouts close them: lower client_header_timeout and client_body_timeout (default 60 s) to 10–15 s on public servers, and limit_conn per IP caps how many such connections one address can hold. HAProxy's stick tables offer richer versions of all of this (rates per URL, per-user error rates, sharing counters between nodes).

Test yourself

limit_req zone=api burst=5 nodelay; with rate=10r/s. A client sends 20 requests in 10 ms. About how many succeed?

  1. 10
  2. 6: one at the rate plus five burst slots, the rest are rejected
  3. 20
  4. 5

What is the difference between burst=3 and burst=3 nodelay?

  1. None
  2. Without nodelay, burst requests are delayed to match the rate; with nodelay they are served at once (both reject beyond the burst)
  3. nodelay disables the limit
  4. nodelay rejects all burst requests

Why is a per-IP limit_req behind a cloud load balancer often wrong?

  1. Load balancers block it
  2. Every request comes from the balancer's address, so all clients share one budget unless the realip module restores the client address
  3. IPv6
  4. It is too slow