How to Rate Limit Requests in nginx With limit_req: Read burst, nodelay and delay Correctly, Key Clients Behind a Proxy and on IPv6, Tune the Numbers From Your Own Access Log, and Test the Policy
A measured nginx 1.30.8 lab that shows what limit_req, burst, nodelay and delay really do, with a Python model that matches nginx on 492 of 492 requests, real-IP and IPv6 keys, log-based tuning with...
A login form that anyone can hit a thousand times a second, a search page that costs your database real money, a scraper that treats your site as a free API: the cheapest defence for all three sits in front of them. A rate limit in nginx answers the extra requests with a short “slow down” before your application has done any work. The catch is that nginx’s rate limiter does not work the way most people picture it, and a configuration that looks right can limit nothing at all.
Table Of Content
- The idea in plain words: a bucket with a hole
- What you need before you start
- Step 1: Set up the lab
- Step 2: Your first limit, and the trap that makes it do nothing
- Why the first line says nothing was limited
- What 5r/s really means
- Step 3: Allow bursts with burst, nodelay and delay
- Which one should you choose?
- Step 4: Check your understanding with a short model
- A mistake that taught me something
- Step 5: Count the right client behind a proxy or CDN
- Step 6: Group IPv6 clients by network, not by address
- Audit the key against what nginx really prints
- Step 7: Choose the numbers from your own log, then roll out in dry-run mode
- Record a dry run
- Check the model against nginx’s own dry-run verdicts
- Ask what-if questions
- The site as a whole
- The login page gets a stricter limit of its own
- Enforce and compare
- Step 8: Answer the client properly and let monitors through
- Step 9: Size the zone so it does not forget
- Step 10: Rate is not concurrency, so add limit_conn for expensive endpoints
- Step 11: Put it together and test it
- The policy file
- Tests that state each promise
- Break it on purpose
- Confirm the whole thing works end to end
- Where to go next
- Sources
This tutorial teaches you to write a limit that behaves the way you expect, and to prove it. You will run a private copy of nginx 1.30.8, send it measured bursts of requests and watch what rate, burst, nodelay and delay really do. You will write a short Python model of nginx’s algorithm and check it against the real server on 492 requests. You will key the limit correctly behind a proxy and for IPv6, choose the numbers from your own access log with dry-run mode, return a useful 429 answer, and finish with a policy file and a test suite that catches 16 of 16 planted mistakes. If you would rather see the algorithms written out in Python first, our earlier posts on token bucket and sliding window limiters and on hardening an application-level limiter cover the same ideas inside an application; this one is about the limit that runs in front of it.
The idea in plain words: a bucket with a hole
Rate limiting means counting each client’s requests over time and refusing the ones that arrive too fast. Four words come up constantly, so here they are before you meet them in configuration files. A key is what you count per: usually the client’s IP address, sometimes an API key or a user ID. A zone is the block of shared memory where nginx keeps one small record per key. The rate is how fast a key’s record drains, written like 5r/s (five requests per second) or 30r/m (thirty per minute). The burst is how many requests a key may be ahead of that rate before nginx refuses.
The nginx documentation says the limit is applied with the “leaky bucket” method. Picture a bucket with a small hole in the bottom. Each request pours one cupful in. The hole lets cupfuls out at the configured rate. The bucket can hold burst cupfuls on top of the one that is currently draining, and a request that would overflow it is refused. The module’s documentation is exact about what happens to the extra requests: “If the requests rate exceeds the rate configured for a zone, their processing is delayed such that requests are processed at a defined rate.” And then: “Excessive requests are delayed until their number exceeds the maximum burst size in which case the request is terminated with an error.”
The source code is shorter than the documentation. This is the whole decision for a key that nginx has seen before, from ngx_http_limit_req_module.c in the 1.30.8 tag (lines 454 to 464). nginx counts in thousandths of a request, so one request is 1000 units, and ms is the time since that key’s last accepted request:
excess = lr->excess - ctx->rate * ms / 1000 + 1000;
if (excess < 0) {
excess = 0;
}
*ep = excess;
if ((ngx_uint_t) excess > limit->burst) {
return NGX_BUSY;
}
In words: take what was left in the bucket, subtract what drained since last time, add the new request. If the total is above the burst, refuse the request and leave the bucket exactly as it was, because the function returns before the new value is stored. That last detail matters later: a refused request is not charged. You will see all of this happen with real traffic in a few minutes.
What you need before you start
You need Python 3 (I used 3.13.14 and did not try other versions), pytest for the final step, about thirty minutes, and free local ports 8081 and 9001. I ran everything on Windows 11 in Git Bash with the nginx.org zip, which is a 32-bit build; nothing needs installing because nginx runs from a folder. The nginx.org Windows page is blunt about the platform: “Only the select() and poll() (1.15.9) connection processing methods are currently used, so high performance and scalability should not be expected.” It also says the Windows version “is considered to be a beta version”. That matters for speed, not for the accounting: the limiter’s source file is byte-identical in the 1.30.8 and 1.31.10 tags (I diffed them), and the arithmetic does not depend on the operating system. For production use Linux. If you want to follow along there, install nginx 1.30 or newer and set the NGINX_EXE environment variable to the binary; I did not run the lab on Linux.
No nginx knowledge is assumed beyond being able to read a block like location / { ... }. One trick keeps the lab on a single machine: every address from 127.0.0.1 to 127.255.255.254 is a loopback address, so the test client can bind its socket to 127.0.0.2, 127.0.0.3 and so on, and nginx sees each as a different client.
Step 1: Set up the lab
Create an empty folder and put every file from this tutorial in it. The first script downloads the stable 1.30.8 zip from nginx.org and unpacks it next to the scripts. It prints the SHA-256 of what it downloaded so you can compare it with your own copy; nginx.org also publishes a PGP signature beside the zip if you want to verify it properly.
# setup_nginx.py
"""setup_nginx.py: download the Windows build of nginx 1.30.8 from nginx.org and unpack it next to these scripts."""
import hashlib
import io
import pathlib
import urllib.request
import zipfile
HERE = pathlib.Path(__file__).resolve().parent
URL = "https://nginx.org/download/nginx-1.30.8.zip"
if (HERE / "nginx-1.30.8").exists():
print("already unpacked: nginx-1.30.8")
else:
request = urllib.request.Request(URL, headers={"User-Agent": "Mozilla/5.0"})
data = urllib.request.urlopen(request, timeout=60).read()
print(f"downloaded {len(data):,} bytes, sha256 {hashlib.sha256(data).hexdigest()}")
zipfile.ZipFile(io.BytesIO(data)).extractall(HERE)
print("unpacked: nginx-1.30.8")
python setup_nginx.py
downloaded 2,775,867 bytes, sha256 ccd0c03ff665d4534e6595e455624ededc9eeb11a81a6a128920fcc928be1151
unpacked: nginx-1.30.8
The second file is the helper that every later script imports. It starts one private nginx per experiment, each in its own folder with its own configuration and logs, so experiments cannot disturb each other. It wraps the configuration you give it in a standard frame with a JSON access log, and it offers four small functions: get sends one request, burst releases several requests at the same instant, play runs a schedule of requests in the background, and arrival_ms tells you when nginx first saw a request.
# rl_nginx.py
"""rl_nginx.py: run a private nginx, send requests to it, and read its JSON access log."""
import http.client
import json
import os
import pathlib
import shutil
import socket
import subprocess
import threading
import time
HERE = pathlib.Path(__file__).resolve().parent
EXE = pathlib.Path(os.environ.get("NGINX_EXE") or HERE / "nginx-1.30.8" / ("nginx.exe" if os.name == "nt" else "nginx"))
PORT = 8081
PROLOG = """\
worker_processes 1;
error_log logs/error.log %(level)s;
pid logs/nginx.pid;
events { worker_connections 1024; }
http {
log_format rl escape=json '{"t":"$msec","rt":"$request_time","ip":"$remote_addr","st":$status,'
'"lim":"$limit_req_status","uri":"$request_uri","cls":"$http_x_class","rid":"$http_x_rid"%(fields)s}';
access_log logs/access.log rl;
default_type text/plain;
root html;
"""
class Nginx:
"""One throwaway nginx. `http_body` is everything that goes inside the http { } block."""
def __init__(self, name, http_body, level="warn", fields="", includes=()):
self.dir = HERE / "runs" / name
self.prefix = str(self.dir).replace("\\", "/") + "/"
for sub in ("conf", "logs", "temp", "html"):
(self.dir / sub).mkdir(parents=True, exist_ok=True)
(self.dir / "html" / "ok.txt").write_text("ok", encoding="utf-8")
for name_ in includes: # files that the config pulls in with `include`
shutil.copy(HERE / name_, self.dir / "conf" / name_)
for log in ("access.log", "error.log"):
(self.dir / "logs" / log).unlink(missing_ok=True)
text = (PROLOG % {"level": level, "fields": fields}) + http_body + "\n}\n"
(self.dir / "conf" / "nginx.conf").write_text(text, encoding="utf-8", newline="\n")
self.proc = None
def _cmd(self, *extra):
return [str(EXE), "-p", self.prefix, "-c", "conf/nginx.conf", *extra]
def start(self):
check = subprocess.run(self._cmd("-t"), cwd=self.dir, capture_output=True, text=True)
if check.returncode != 0:
raise RuntimeError("nginx -t failed:\n" + check.stderr)
self.proc = subprocess.Popen(self._cmd(), cwd=self.dir, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
deadline = time.time() + 10
while time.time() < deadline:
try:
socket.create_connection(("127.0.0.1", PORT), timeout=1).close()
return self
except OSError:
time.sleep(0.05)
raise RuntimeError("nginx did not start")
def stop(self):
subprocess.run(self._cmd("-s", "stop"), cwd=self.dir, capture_output=True)
if self.proc:
try:
self.proc.wait(timeout=10)
except subprocess.TimeoutExpired:
self.proc.kill()
def __enter__(self):
return self.start()
def __exit__(self, *exc):
self.stop()
def access_log(self):
path = self.dir / "logs" / "access.log"
return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
def error_log(self):
return (self.dir / "logs" / "error.log").read_text(encoding="utf-8", errors="replace")
def get(path="/", headers=None, source=None, port=PORT, timeout=15):
"""One GET on a fresh connection. Returns (status, headers, seconds, body)."""
t0 = time.perf_counter()
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=timeout,
source_address=(source, 0) if source else None)
try:
conn.request("GET", path, headers={"Connection": "close", **(headers or {})})
resp = conn.getresponse()
body = resp.read()
return resp.status, dict(resp.getheaders()), time.perf_counter() - t0, body
finally:
conn.close()
def burst(n, path="/", source=None, headers=None):
"""n requests released at the same moment. Returns [(request number, status, seconds)] in finish order."""
gate, out = threading.Barrier(n), []
def one(i):
gate.wait()
status, _, secs, _ = get(path, {"X-Rid": f"b{i}", **(headers or {})}, source)
out.append((i, status, secs))
threads = [threading.Thread(target=one, args=(i,)) for i in range(n)]
for t in threads:
t.start()
for t in threads:
t.join()
return out
def play(events):
"""Open-loop traffic. events = [(seconds from start, path, headers, source)]; each one runs in its own thread."""
results, threads, start = [], [], time.perf_counter()
def one(ev):
_, path, headers, source = ev
try:
results.append((ev, get(path, headers, source)[0]))
except OSError as exc:
results.append((ev, repr(exc)))
for ev in sorted(events, key=lambda e: e[0]):
wait = ev[0] - (time.perf_counter() - start)
if wait > 0:
time.sleep(wait)
t = threading.Thread(target=one, args=(ev,))
t.start()
threads.append(t)
for t in threads:
t.join()
return results
def arrival_ms(row):
"""When nginx first saw the request, in ms: the log time minus the request time."""
return round(float(row["t"]) * 1000) - round(float(row["rt"]) * 1000)
if __name__ == "__main__":
print(subprocess.run([str(EXE), "-v"], capture_output=True, text=True).stderr.strip())
with Nginx("smoke", "server { listen 8081; location / { try_files /ok.txt =404; } }"):
status, _, _, body = get("/")
print("it answers:", status, body.decode())
The access log is the important part. Three of its fields do the heavy lifting in this tutorial: $msec is the time the request was logged, $request_time is how long nginx spent on it, and $limit_req_status records what the limiter decided. Subtract the second from the first and you get the moment nginx first saw the request, which is the time the limiter used. The frame also sets root html; and creates a one-line file ok.txt; that file is the “application” we are protecting, and Step 2 explains why it is a file and not a one-line answer.
python rl_nginx.py
nginx version: nginx/1.30.8
it answers: 200 ok
Check: the first line says nginx/1.30.8 and the second says 200 ok. If nginx does not start, the usual causes are another program on port 8081 or security software quarantining nginx.exe; the error log is runs/smoke/logs/error.log.
Step 2: Your first limit, and the trap that makes it do nothing
The smallest useful limit takes two directives. limit_req_zone $binary_remote_addr zone=perip:1m rate=5r/s; creates the zone: the key is the client address in its compact binary form, the zone is named perip and gets one megabyte of memory, and the rate is five requests per second. limit_req zone=perip; then switches the limit on inside a location. In rate_only.py below I run it twice. The first location answers with return 200 "ok", which is a common way to make a quick test page. The second serves a file with try_files. Each gets twelve requests from one client, about 60 milliseconds apart.
# rate_only.py
"""rate_only.py: limit_req with a rate and no burst. Twelve requests, 60 ms apart, from one client."""
import time
from rl_model import Limit, Zone, decide
from rl_nginx import Nginx, arrival_ms, get
CONF = """
limit_req_zone $binary_remote_addr zone=perip:1m rate=5r/s;
server {
listen 8081;
EXTRA
location /return {
limit_req zone=perip;
return 200 "ok";
}
location /file {
limit_req zone=perip;
try_files /ok.txt =404;
}
}
"""
def run(name, path, extra="", source=None):
with Nginx(name, CONF.replace("EXTRA", extra)) as ngx:
start = time.perf_counter()
codes = []
for i in range(12):
time.sleep(max(0, start + i * 0.060 - time.perf_counter()))
codes.append(get(path, {"X-Rid": str(i)}, source)[0])
rows = sorted(ngx.access_log(), key=lambda r: int(r["rid"]))
return codes, rows
codes, rows = run("step1r", "/return")
print("limit_req next to return: 200 responses:", codes.count(200), "of 12; $limit_req_status values:", sorted({r["lim"] for r in rows}))
codes, rows = run("step1a", "/file")
zone = Zone(5)
limits = [Limit(zone)]
t0 = arrival_ms(rows[0])
print()
print("request arrived_ms http nginx says model says")
for i, row in enumerate(rows):
now = arrival_ms(row)
model = decide(limits, [row["ip"]], now)[0]
print(f"{i:>7} {now - t0:>10} {codes[i]:>4} {row['lim']:<10} {model}")
print()
print("rejected with the default status:", sorted({c for c in codes if c != 200}))
codes429, _ = run("step1b", "/file", "limit_req_status 429;")
print("rejected with limit_req_status 429:", sorted({c for c in codes429 if c != 200}))
python rate_only.py
limit_req next to return: 200 responses: 12 of 12; $limit_req_status values: ['']
request arrived_ms http nginx says model says
0 0 200 PASSED PASSED
1 65 503 REJECTED REJECTED
2 129 503 REJECTED REJECTED
3 177 503 REJECTED REJECTED
4 241 200 PASSED PASSED
5 305 503 REJECTED REJECTED
6 369 503 REJECTED REJECTED
7 417 503 REJECTED REJECTED
8 481 200 PASSED PASSED
9 546 503 REJECTED REJECTED
10 610 503 REJECTED REJECTED
11 658 503 REJECTED REJECTED
rejected with the default status: [503]
rejected with limit_req_status 429: [429]
Why the first line says nothing was limited
Read the first line first. Twelve requests, twelve successes, and the $limit_req_status that nginx logged for them is an empty string, which means the limiter never looked at them. The reason is the order in which nginx runs its processing stages, which it calls phases. The rewrite module, which owns return, hooks into the server-rewrite and rewrite phases (lines 279 and 286 of ngx_http_rewrite_module.c in the same tag). The limiter registers in the later preaccess phase (line 1094 of its own source file, again in that tag). The documentation for return says what it does: “Stops processing and returns the specified code to a client.” Nothing after the rewrite phase runs, and that includes the limit.
The practical rule: whenever a limit seems to be ignored, check that the location ends in a real handler such as proxy_pass, fastcgi_pass, a static file or, as here, try_files. It is the reason every example in this tutorial serves a one-line file instead of using return.
What 5r/s really means
The table is the real behaviour. Requests 0, 4 and 8 get through; everything else is refused. rate=5r/s does not mean “five requests any time you like within a second”. It means one request every 200 milliseconds, because with no burst nothing is allowed to be ahead of the rate. Request 1 arrives 65 ms after request 0, the bucket has drained only 0.325 of a request, so it is refused. Request 4 arrives 241 ms after request 0, the bucket has drained 1.2 requests, so it passes. Notice that requests 1 to 3 were refused and still request 4 got in: the refused requests were not charged, exactly as the source code promised.
The last column is a model of nginx’s algorithm that you will write in Step 4. For now just notice that it agrees with nginx on every row. The last two lines of output show the status code: without limit_req_status nginx refuses with 503 Service Unavailable, which tells clients and your monitoring that your server is broken rather than that the client is too fast. With limit_req_status 429; it answers 429 Too Many Requests, which is the honest answer, so always set it.
Check: you should see 200 only for requests 0, 4 and 8 (the arrival times will differ by a few milliseconds on your machine; the pattern will not). Common mistake: testing with return and concluding that the limiter “doesn’t work”.
Step 3: Allow bursts with burst, nodelay and delay
Real traffic comes in clumps. A browser loading a page fires a dozen requests within a tenth of a second, and a phone app syncing after you open it may send fifteen at once. A limit with no burst would refuse most of them. The burst parameter is the room you give: how many requests a client may be ahead of the rate. What happens to a request inside that room is decided by two more parameters.
By default the request is delayed: nginx holds it back so that the stream leaves at exactly the configured rate. With nodelay the request is served immediately, but it still uses up room in the bucket. With delay=N the first N requests above the rate are served immediately and the rest are delayed; the documentation puts it this way: “Default value is zero, i.e. all excessive requests are delayed.” The script below releases ten requests at the same moment against three locations that differ only in these parameters, then runs a second experiment on the refill.
# burst_modes.py
"""burst_modes.py: burst, nodelay and delay=N. Ten requests arrive at the same moment from one client."""
import time
from rl_model import Limit, Zone, decide
from rl_nginx import Nginx, arrival_ms, burst
CONF = """
limit_req_zone $binary_remote_addr zone=za:1m rate=5r/s;
limit_req_zone $binary_remote_addr zone=zb:1m rate=5r/s;
limit_req_zone $binary_remote_addr zone=zc:1m rate=5r/s;
server {
listen 8081;
limit_req_status 429;
location /burst { limit_req zone=za burst=5; try_files /ok.txt =404; }
location /nodelay { limit_req zone=zb burst=5 nodelay; try_files /ok.txt =404; }
location /delay2 { limit_req zone=zc burst=5 delay=2; try_files /ok.txt =404; }
}
"""
SETTINGS = {"/burst": "burst=5", "/nodelay": "burst=5 nodelay", "/delay2": "burst=5 delay=2"}
with Nginx("step2", CONF) as ngx:
print("setting passed delayed rejected finish times of the 200 responses (ms)")
for n, (path, label) in enumerate(SETTINGS.items()):
res = burst(10, path, source=f"127.0.0.{10 + n}")
rows = [r for r in ngx.access_log() if r["uri"] == path]
count = {s: sum(r["lim"] == s for r in rows) for s in ("PASSED", "DELAYED", "REJECTED")}
done = sorted(round(secs * 1000) for _, status, secs in res if status == 200)
print(f"{label:<18} {count['PASSED']:>6} {count['DELAYED']:>7} {count['REJECTED']:>8} {done}")
print()
print("burst=5 nodelay: ten requests, a pause, ten more requests (a new client each time)")
print("pause_ms accepted_in_second_burst model_says")
for n, pause in enumerate((0, 200, 600, 1000, 1200)):
client = f"127.0.0.{30 + n}"
burst(10, "/nodelay", source=client)
time.sleep(pause / 1000)
burst(10, "/nodelay", source=client)
rows = sorted((r for r in ngx.access_log() if r["ip"] == client),
key=lambda r: (arrival_ms(r), r["lim"] == "REJECTED"))
zone = Zone(5)
limits = [Limit(zone, burst=5, nodelay=True)]
first = arrival_ms(rows[0])
got = sum(r["lim"] != "REJECTED" for r in rows[10:])
model = [decide(limits, [client], arrival_ms(r))[0] for r in rows]
print(f"{pause:>8} {got:>24} {sum(m != 'REJECTED' for m in model[10:]):>10}")
python burst_modes.py
setting passed delayed rejected finish times of the 200 responses (ms)
burst=5 1 5 4 [17, 225, 418, 628, 821, 1030]
burst=5 nodelay 6 0 4 [7, 8, 8, 9, 10, 11]
burst=5 delay=2 3 3 4 [7, 8, 8, 208, 417, 610]
burst=5 nodelay: ten requests, a pause, ten more requests (a new client each time)
pause_ms accepted_in_second_burst model_says
0 0 0
200 1 1
600 3 3
1000 5 5
1200 6 6
In all three settings exactly six of the ten requests are accepted and four are refused, because the first request costs nothing and the next five fill the burst; the seventh would be six requests ahead, over the burst of five. The settings differ only in when the six are served. With burst=5 alone one request goes through at once and the other five are queued, finishing about 200 milliseconds apart (the last at about a second). With nodelay all six finish within about ten milliseconds. With delay=2 three go at once and three wait about 200, 400 and 600 milliseconds.
The second table shows that a burst is a bucket that refills at the rate. After the client has used all six slots, 200 ms later it gets one slot back, 600 ms later three, a second later five, and after 1,200 ms the whole bucket is full again. In general a bucket with burst B refills completely in (B + 1) divided by the rate seconds. The model’s answer sits beside nginx’s in the table and matches in every row.
Which one should you choose?
Use nodelay with a burst sized for a legitimate clump when the clients are people or apps with timeouts, such as a web page or an API. A delayed request keeps its connection open and the user waits with it: at five requests per second a burst of 20 would hold the last request for four seconds, which is longer than many API clients are willing to wait. Use the default queue when you are protecting a backend that cannot take a clump and the clients are patient, such as a batch importer. delay=N sits in between: let the first N through at full speed and stretch the rest. Whatever you choose, the burst is the number to think about; the next steps show how to size it from your own traffic.
Check: six accepted and four refused in every row, finish times that match the pattern above, and a refill table of 0, 1, 3, 5, 6 (model and nginx identical). Common mistake: setting burst without understanding that, with no nodelay, every request above the rate is slowed down; users experience that as a slow site, not as a limit.
Step 4: Check your understanding with a short model
You now have three descriptions of the same behaviour: the documentation, the source code and your measurements. The way to know you have understood them is to make the computer predict the measurements. The model below is a direct translation of the source you saw earlier: one record per key holding the excess and the time of the last accepted request, the same integer arithmetic (// on non-negative numbers is C’s integer division), and the same two phases for a request that passes several limits at once, a check phase that refuses without changing anything and a charge phase that updates every zone.
# rl_model.py
"""rl_model.py: nginx's limit_req algorithm in plain Python.
Everything is an integer, as in ngx_http_limit_req_module.c (nginx 1.30.8): one request is 1000 units
("excess" counts thousandths of a request) and times are milliseconds.
"""
class Zone:
"""limit_req_zone ... rate=5r/s (per="s") or rate=30r/m (per="m"). One state per key."""
def __init__(self, rate, per="s"):
self.rate = rate * 1000 // (60 if per == "m" else 1) # units refilled per second
self.state = {} # key -> [excess, last_ms]
class Limit:
"""limit_req zone=... burst=N [nodelay | delay=M]"""
def __init__(self, zone, burst=0, nodelay=False, delay=0):
self.zone = zone
self.burst = burst * 1000
self.delay = self.burst if nodelay else delay * 1000
def decide(limits, keys, now):
"""One request at time `now` (ms). keys[i] is the key for limits[i]; "" means 'not limited by this one'.
Returns ("PASSED" | "DELAYED" | "REJECTED", delay in ms)."""
fresh = []
for lim, key in zip(limits, keys):
if key == "":
fresh.append(None)
continue
z = lim.zone
excess_before, last = z.state.get(key, (None, None))
if excess_before is None: # a key nginx has not seen: it starts empty
excess = 0
else:
excess = max(0, excess_before - z.rate * max(0, now - last) // 1000 + 1000)
if excess > lim.burst: # over the burst: refuse, and do not charge anyone
return "REJECTED", 0
fresh.append(excess)
delay_ms = 0
for lim, key, excess in zip(limits, keys, fresh):
if excess is None:
continue
lim.zone.state[key] = [excess, now]
if excess > lim.delay:
delay_ms = max(delay_ms, (excess - lim.delay) * 1000 // lim.zone.rate)
return ("DELAYED" if delay_ms else "PASSED"), delay_ms
if __name__ == "__main__":
z = Zone(5)
lim = [Limit(z, burst=5, nodelay=True)]
print([decide(lim, ["a"], 0)[0] for _ in range(8)])
The check script sends 492 requests from eight clients over twelve seconds to five locations: a plain 5r/s limit, a delayed burst of 10, nodelay with a burst of 10, a 30r/m limit with burst=3 delay=1 (to test minutes), and a location with two limits at once, a per-client one and a whole-server one. The traffic has clumps of one to eight requests within a few milliseconds, so every branch is exercised. Afterwards it replays nginx’s own log through the model, request by request in arrival order, and counts the requests on which the model and nginx disagree.
# check_model.py
"""check_model.py: does rl_model.py make the same decisions as nginx? Random traffic against five limits."""
import random
from rl_model import Limit, Zone, decide
from rl_nginx import Nginx, arrival_ms, play
CONF = """
limit_req_zone $binary_remote_addr zone=a:1m rate=5r/s;
limit_req_zone $binary_remote_addr zone=b:1m rate=5r/s;
limit_req_zone $binary_remote_addr zone=c:1m rate=5r/s;
limit_req_zone $binary_remote_addr zone=d:1m rate=30r/m;
limit_req_zone $binary_remote_addr zone=e:1m rate=5r/s;
limit_req_zone $server_name zone=all:1m rate=20r/s;
server {
listen 8081;
server_name lab.test;
location /a { limit_req zone=a; try_files /ok.txt =404; }
location /b { limit_req zone=b burst=10; try_files /ok.txt =404; }
location /c { limit_req zone=c burst=10 nodelay; try_files /ok.txt =404; }
location /d { limit_req zone=d burst=3 delay=1; try_files /ok.txt =404; }
location /e { limit_req zone=e burst=5 nodelay;
limit_req zone=all burst=20; try_files /ok.txt =404; }
}
"""
# the same five limits in the model: (location, [(zone name, burst, nodelay, delay)], key per limit)
SPEC = {
"/a": [("a", 0, False, 0)], "/b": [("b", 10, False, 0)], "/c": [("c", 10, True, 0)],
"/d": [("d", 3, False, 1)], "/e": [("e", 5, True, 0), ("all", 20, False, 0)],
}
RATES = {"a": (5, "s"), "b": (5, "s"), "c": (5, "s"), "d": (30, "m"), "e": (5, "s"), "all": (20, "s")}
rng = random.Random(7)
events = []
for client in range(1, 9): # eight clients, 127.0.0.1 to 127.0.0.8
rate = rng.choice([0.5, 1, 2, 4]) # "clumps" per second
t = rng.random()
while t < 12:
for _ in range(rng.choice([1, 1, 2, 4, 8])): # a clump is several requests within a few ms
path = rng.choice(list(SPEC)) + f"/{len(events)}"
events.append((t + rng.random() * 0.004, path, {"X-Rid": str(len(events))}, f"127.0.0.{client}"))
t += rng.expovariate(rate)
with Nginx("step3", CONF) as ngx:
play(events)
rows = ngx.access_log()
print(f"{len(rows)} requests sent from 8 clients in 12 seconds")
print("location limits requests PASSED DELAYED REJECTED disagreements mean delay error (ms)")
order = {"PASSED": 0, "DELAYED": 1, "REJECTED": 2}
total_bad = 0
zones = {name: Zone(*RATES[name]) for name in RATES}
for loc, spec in SPEC.items():
mine = sorted((r for r in rows if r["uri"].startswith(loc + "/")), key=lambda r: (arrival_ms(r), order[r["lim"]]))
limits = [Limit(zones[z], burst, nodelay, delay) for z, burst, nodelay, delay in spec]
bad, errs = 0, []
for r in mine:
keys = [r["ip"] if name != "all" else "srv" for name, *_ in spec]
status, delay = decide(limits, keys, arrival_ms(r))
if status != r["lim"]:
bad += 1
elif status == "DELAYED":
errs.append(abs(delay - float(r["rt"]) * 1000))
total_bad += bad
n = {s: sum(r["lim"] == s for r in mine) for s in order}
label = "+".join(f"{z}:{b}{'n' if nd else ''}{'d' + str(d) if d else ''}" for z, b, nd, d in spec)
err = f"{sum(errs) / len(errs):.1f}" if errs else "-"
print(f"{loc:<9} {label:<20} {len(mine):>8} {n['PASSED']:>7} {n['DELAYED']:>8} {n['REJECTED']:>9} {bad:>14} {err:>21}")
print(f"\nmodel and nginx disagree on {total_bad} of {len(rows)} requests")
python check_model.py
492 requests sent from 8 clients in 12 seconds
location limits requests PASSED DELAYED REJECTED disagreements mean delay error (ms)
/a a:0 107 65 0 42 0 -
/b b:10 113 49 64 0 0 7.2
/c c:10n 94 94 0 0 0 -
/d d:3d1 90 31 20 39 0 5.9
/e e:5n+all:20 88 42 46 0 0 8.5
model and nginx disagree on 0 of 492 requests
In the limits column the letter is the zone, the number is the burst, n means nodelay and d1 means delay=1. The model and nginx disagree on none of the 492 requests, including the delayed ones and the two-limit location. For delayed requests the last column compares the delay the model predicts with the time nginx actually took; the two agree to within about ten milliseconds on average, which I put down to this Windows build’s timer granularity (I did not investigate further).
A mistake that taught me something
My first run of this script disagreed on 48 of the 492 requests, all of them in the two-limit location. I had keyed the whole-server zone on $server_name and the server block had no server_name directive, so the key was an empty string. The documentation had warned me: “Requests with an empty key value are not accounted.” The model assumed the key existed; nginx quietly never limited anything in that zone. Adding server_name lab.test; fixed it. Keep this in mind for any key you build from a variable: if the variable can be empty, those requests are not limited at all.
Step 5: Count the right client behind a proxy or CDN
Everything so far keyed on the address of the connection. That is only the client’s address when the client connects to nginx directly. Behind a load balancer or a CDN, every connection comes from the proxy, so all visitors share one key: one noisy visitor then spends everybody’s budget. The proxy passes the real address along in a header, usually X-Forwarded-For, and nginx’s real-IP module can swap it in. It is easy to get wrong in both directions, so the script below tries six configurations against five kinds of client.
Two directives matter. set_real_ip_from “Defines trusted addresses that are known to send correct replacement addresses.” real_ip_header names the header to read. When a header holds several addresses, real_ip_recursive decides which one wins: if it is off, the address is replaced by “the last address sent in the request header field defined by the real_ip_header directive”; if it is on, by “the last non-trusted address sent in the request header field.” In the lab, 127.0.0.2 plays the single proxy in rows A to D. In rows E and F a second proxy, 127.0.0.3, sits between it and nginx and the header it sends reads “visitor, 127.0.0.2”. 127.0.0.1 plays someone who reaches nginx directly. The five columns are an honest user who sends six requests while a neighbour behind the same proxy floods, the neighbour’s 40 requests, an attacker behind the proxy who forges the left end of the header (the proxy appends the real address on the right), an attacker who reaches nginx directly and sends a forged header, and one who sends no header at all. Every cell counts how many requests were accepted.
# real_ip_matrix.py
"""real_ip_matrix.py: which key stops a flood behind a proxy or CDN? Six configurations, five kinds of client."""
import random
import threading
import time
from rl_nginx import Nginx, get
SERVER = """
limit_req_zone KEY zone=perclient:1m rate=5r/s;
server {
listen 8081;
limit_req_status 429;
REALIP
location / { limit_req zone=perclient burst=5 nodelay; try_files /ok.txt =404; }
}
"""
ADDR = "$binary_remote_addr"
ONE_HOP = "set_real_ip_from 127.0.0.2; real_ip_header X-Forwarded-For;"
TWO_HOPS = "set_real_ip_from 127.0.0.2; set_real_ip_from 127.0.0.3; real_ip_header X-Forwarded-For;"
CONFIGS = [ # name, key, real_ip lines, does the client path have two proxies?
("A key = peer address, nothing else", ADDR, "", False),
("B key = $http_x_forwarded_for", "$http_x_forwarded_for", "", False),
("C trust every peer (0.0.0.0/0)", ADDR, "set_real_ip_from 0.0.0.0/0; real_ip_header X-Forwarded-For;", False),
("D trust only the proxy", ADDR, ONE_HOP, False),
("E two proxies, recursive off", ADDR, TWO_HOPS, True),
("F two proxies, real_ip_recursive on", ADDR, TWO_HOPS + " real_ip_recursive on;", True),
]
rng = random.Random(3)
def fake():
return ".".join(str(rng.randrange(1, 250)) for _ in range(4))
def fire(n, source, xff, gap=0.0):
"""n requests from `source`; xff() builds the X-Forwarded-For value (None = send no header)."""
ok = 0
for _ in range(n):
value = xff()
status = get("/", {"X-Forwarded-For": value} if value else {}, source)[0]
ok += status == 200
time.sleep(gap)
return ok
def scenarios(two_hops):
proxy = "127.0.0.3" if two_hops else "127.0.0.2" # the machine that talks to nginx
behind = (lambda who: f"{who}, 127.0.0.2") if two_hops else (lambda who: who) # what the last proxy sends
res = {}
def honest():
res["honest"] = fire(6, proxy, lambda: behind("203.0.113.10"), gap=0.25)
def neighbour():
res["neighbour"] = fire(40, proxy, lambda: behind("203.0.113.99"), gap=0.03)
threads = [threading.Thread(target=honest), threading.Thread(target=neighbour)]
[t.start() for t in threads]
[t.join() for t in threads]
# an attacker behind the proxy forges the left end of the header; the proxy appends the real address
res["forged"] = fire(40, proxy, lambda: behind(f"{fake()}, 198.51.100.7"))
# an attacker that reaches nginx directly (not through the proxy)
res["direct"] = fire(40, "127.0.0.1", lambda: fake())
res["bare"] = fire(40, "127.0.0.4", lambda: None)
return res
print(f"{'configuration':<38} honest(6) neighbour(40) forged_via_proxy(40) direct_forged(40) direct_bare(40)")
for name, key, realip, two in CONFIGS:
conf = SERVER.replace("KEY", key).replace("REALIP", realip)
with Nginx("step4", conf):
r = scenarios(two)
print(f"{name:<38} {r['honest']:>9} {r['neighbour']:>13} {r['forged']:>21} {r['direct']:>17} {r['bare']:>15}")
python real_ip_matrix.py
configuration honest(6) neighbour(40) forged_via_proxy(40) direct_forged(40) direct_bare(40)
A key = peer address, nothing else 1 13 0 6 6
B key = $http_x_forwarded_for 6 15 40 40 40
C trust every peer (0.0.0.0/0) 6 15 9 40 9
D trust only the proxy 6 15 9 9 9
E two proxies, recursive off 1 14 3 9 9
F two proxies, real_ip_recursive on 6 15 9 9 9
Read the table row by row. A keys on the connection address and ignores the header: the honest user gets one request of six through, because the neighbour has drained the bucket they share. B uses the header itself as the key, which is a tempting shortcut: the attacker rotates the header and all three attacker columns show 40 of 40 accepted, and the request with no header at all has an empty key, which is never limited. C trusts every peer: it works behind the proxy but a direct attacker who sends a forged header gets 40 of 40 through. D trusts only the proxy and is correct for one hop: the honest user gets six of six, and every attacker is held to about nine (six at once plus a few refilled during the run). E shows what happens with two proxies when real_ip_recursive is off: nginx takes the last address in the header, which belongs to the outer proxy and not to the visitor, so everyone shares a key again and the honest user is back to one of six. F turns recursion on, lists both proxies as trusted, and gets everything right.
The rule that follows: trust exactly the addresses of the proxies you operate (or your CDN’s published ranges), never 0.0.0.0/0; turn real_ip_recursive on when more than one trusted hop sits in front of nginx; never use a client-supplied header as a key; and check with your CDN which header carries the client address, because some use their own header rather than X-Forwarded-For.
Check: after you apply the configuration, send a request through your proxy and look at the address in the access log; it must be the visitor’s, not the proxy’s. Common mistake: trusting a whole private range “to be safe” when nginx is also reachable from other machines in that range.
Step 6: Group IPv6 clients by network, not by address
An IPv4 address is scarce; an IPv6 network is not. A customer’s network normally gets a /64 or a larger block, and a /64 is the standard IPv6 subnet, which holds 264 addresses, and every device in it can pick new ones freely. A limit keyed on the single address gives that customer 264 buckets. The fix is to key on the first 64 bits. nginx has no bit arithmetic, but it prints $remote_addr in a predictable text form, and a map with regular expressions can cut that text down to the /64. The file below does it; it is the only place in this tutorial with long regular expressions, and the script after it tests it against thousands of addresses.
# net_key.conf: one key per IPv4 address and per IPv6 /64, from the text nginx prints in $remote_addr
map $remote_addr $ip_key {
"~^::ffff:(?<v4>[\d.]+)$" $v4;
"~^(?<p>(?:[\da-f]+:){4})" $p;
"~^(?<a>[\da-f]+)::(?<d>[\da-f]+):[\da-f]+:[\da-f]+:[\da-f]+:[\da-f]+$" "$a:0:0:$d:";
"~^::(?<d>[\da-f]+):[\da-f]+:[\da-f]+:[\da-f]+:[\da-f]+$" "0:0:0:$d:";
"~^::(?<d>[\da-f]+):(?<e>[\da-f]+):[\da-f]+:[\da-f]+:[\da-f]+:[\da-f]+$" "0:0:$d:$e:";
"~^(?<a>[\da-f]+)::" "$a:0:0:0:";
"~^(?<a>[\da-f]+:[\da-f]+)::" "$a:0:0:";
"~^(?<a>[\da-f]+:[\da-f]+:[\da-f]+)::" "$a:0:";
"~^::" "0:0:0:0:";
default $remote_addr;
}
The rules are in order, first match wins. The first rule turns an IPv4 address written as an IPv6 one (::ffff:192.0.2.9) back into the IPv4 address; without it every such client would fall into the all-zero network and share one bucket. The second takes the first four groups when they are all written out. Rules three to five handle the three shapes where the zeros that nginx writes as :: swallow part of the first 64 bits yet a later group is still part of the network. Rules six to nine handle :: after one, two or three groups, or at the very start. Anything else, including IPv4, is used as it is.
Audit the key against what nginx really prints
The script sends 40 addresses from one /64 to a per-address key and to the /64 key, then 40 users from 40 different /64 networks, then prints what nginx writes into $remote_addr for a few spellings. The last part is the audit: 2,100 requests from 56 random networks, in which every group is zero about half the time so that every compressed shape appears, counting networks that end up with more than one key (a hole in the defence) and keys shared by several networks (innocent users throttled together). It also runs a first attempt with only three rules, to show why the other six exist.
# ipv6_keys.py
"""ipv6_keys.py: one IPv6 /64 holds 2**64 addresses. Key the limit on the /64 and audit the key against nginx's own text."""
import ipaddress
import random
from rl_nginx import Nginx, get
CONF = r"""
include net_key.conf; # the full rule set: defines $ip_key
map $remote_addr $first_try { # a first attempt with only three rules
"~^(?<p>(?:[\da-f]+:){4})" $p;
"~^(?<a>[\da-f]+)::" "$a:0:0:0:";
"~^(?<a>[\da-f]+:[\da-f]+)::" "$a:0:0:";
default $remote_addr;
}
limit_req_zone $binary_remote_addr zone=peraddr:1m rate=5r/s;
limit_req_zone $ip_key zone=pernet:1m rate=5r/s;
server {
listen 8081;
set_real_ip_from 127.0.0.2;
real_ip_header X-Forwarded-For;
limit_req_status 429;
location /peraddr { limit_req zone=peraddr burst=5 nodelay; try_files /ok.txt =404; }
location /pernet { limit_req zone=pernet burst=5 nodelay; try_files /ok.txt =404; }
location /probe { try_files /ok.txt =404; }
}
"""
rng = random.Random(11)
def via_proxy(path, address):
return get(path, {"X-Forwarded-For": str(address)}, source="127.0.0.2")[0]
def groups_to_int(groups):
return int.from_bytes(b"".join(g.to_bytes(2, "big") for g in groups), "big")
def holey(n):
"""n random 16-bit groups, about half of them zero, so every compressed text shape shows up."""
return [rng.getrandbits(16) if rng.random() < 0.5 else 0 for _ in range(n)]
with Nginx("ipv6", CONF, fields=',"first":"$first_try","key":"$ip_key"', includes=["net_key.conf"]) as ngx:
# 1. one /64, 40 different addresses in it, against the per-address key and the /64 key
net = ipaddress.IPv6Network("2001:db8:0:1::/64")
one = [net[0] + rng.getrandbits(64) for _ in range(40)]
per_addr = sum(via_proxy("/peraddr", a) == 200 for a in one)
per_net = sum(via_proxy("/pernet", a) == 200 for a in one)
# 2. 40 users on 40 different /64 networks must not share a bucket
many = [ipaddress.IPv6Address((0x20010DB8 << 96) | ((0x100 + i) << 64) | rng.getrandbits(64)) for i in range(40)]
spread = sum(via_proxy("/pernet", a) == 200 for a in many)
print(f"40 addresses from ONE /64: per-address key {per_addr} accepted, /64 key {per_net} accepted")
print(f"40 addresses from 40 /64s: /64 key {spread} accepted")
# 3. what nginx prints for $remote_addr, and the key the map derives from it
print()
print("sent in X-Forwarded-For nginx $remote_addr key")
samples = ["2001:0db8:0000:0001:0000:0000:0000:0005", "2001:db8:0:1:aaaa:bbbb:cccc:dddd", "2001:db8:0:0:0:0:0:1",
"2001:db8:1:0:5::9", "fd00:0:0:5:a:b:c:d", "::ffff:192.0.2.9", "::1", "192.0.2.77"]
start = len(ngx.access_log())
for s in samples:
get("/probe", {"X-Forwarded-For": s}, source="127.0.0.2")
for s, r in zip(samples, ngx.access_log()[start:]):
print(f"{s:<44} {r['ip']:<44} {r['key']}")
# 4. audit: 60 random /64 networks, 35 random addresses in each, groups zero about half the time
start = len(ngx.access_log())
truth = []
for _ in range(60):
prefix = holey(4)
for _ in range(35):
truth.append(tuple(prefix))
via_proxy("/probe", ipaddress.IPv6Address(groups_to_int(prefix + holey(4))))
rows = ngx.access_log()[start:]
print()
print(f"audit: {len(rows)} requests from {len(set(truth))} different /64 networks")
for label, field in (("first attempt (3 rules)", "first"), ("net_key.conf (full rule set)", "key")):
by_net, by_key = {}, {}
for net_id, row in zip(truth, rows):
by_net.setdefault(net_id, set()).add(row[field])
by_key.setdefault(row[field], set()).add(net_id)
split = sum(len(k) > 1 for k in by_net.values())
merged = sum(len(n) > 1 for n in by_key.values())
print(f" {label:<30} /64 networks split over several keys: {split:>2} keys shared by several /64 networks: {merged:>2}")
python ipv6_keys.py
40 addresses from ONE /64: per-address key 40 accepted, /64 key 6 accepted
40 addresses from 40 /64s: /64 key 40 accepted
sent in X-Forwarded-For nginx $remote_addr key
2001:0db8:0000:0001:0000:0000:0000:0005 2001:db8:0:1::5 2001:db8:0:1:
2001:db8:0:1:aaaa:bbbb:cccc:dddd 2001:db8:0:1:aaaa:bbbb:cccc:dddd 2001:db8:0:1:
2001:db8:0:0:0:0:0:1 2001:db8::1 2001:db8:0:0:
2001:db8:1:0:5::9 2001:db8:1:0:5::9 2001:db8:1:0:
fd00:0:0:5:a:b:c:d fd00::5:a:b:c:d fd00:0:0:5:
::ffff:192.0.2.9 ::ffff:192.0.2.9 192.0.2.9
::1 ::1 0:0:0:0:
192.0.2.77 192.0.2.77 192.0.2.77
audit: 2100 requests from 56 different /64 networks
first attempt (3 rules) /64 networks split over several keys: 31 keys shared by several /64 networks: 0
net_key.conf (full rule set) /64 networks split over several keys: 0 keys shared by several /64 networks: 0
The first two lines are the point: 40 addresses in one network get all 40 requests through a per-address key but only six through the /64 key, while 40 users on 40 different networks are not disturbed. The sample table shows how nginx writes addresses: it drops leading zeros and compresses a run of zero groups into ::, but it does not compress a single zero group (2001:db8:1:0:5::9 keeps its 0), which is why the rules key on the text it actually prints rather than on the text a client sends. In the audit, the three-rule first attempt split 31 of the 56 networks across more than one key, so an attacker could pick up a second bucket by choosing addresses of a different shape. The full rule set had no split networks and no shared keys.
Check: the audit must end with 0 and 0 for the full rule set. Common mistake: stopping at the three obvious rules, which pass casual testing and quietly leave part of the network unprotected. The first rule matters if a dual-stack socket reports IPv4 clients in the ::ffff: form; I tested the rule with the text nginx prints for such an address, not with a dual-stack socket.
Step 7: Choose the numbers from your own log, then roll out in dry-run mode
Five requests per second and a burst of twenty: where did those numbers come from? They should come from your traffic. The two scripts below give you a workflow you can repeat on your own access log. First limit_req_dry_run on; lets nginx evaluate the limit without enforcing it; the documentation: “In this mode, requests processing rate is not limited, however, in the shared memory zone, the number of excessive requests is accounted as usual.” Every request still gets its answer, but the log records what would have happened in $limit_req_status as REJECTED_DRY_RUN or DELAYED_DRY_RUN. Second, because the log holds the arrival time of every request, the model from Step 4 can replay it for any other setting, so you can compare many candidates without touching the server.
The traffic generator plays a made-up 20 seconds: six browsers that load a page plus eleven assets within 120 milliseconds, two dashboards polling twice a second, a phone app that sends fifteen calls at once every five seconds, a scraper at about 28 requests a second and a password-guessing script at 12 requests a second against /login. The tuner reads the log and prints the share of requests that would be rejected, overall and per kind of client.
# rl_traffic.py
"""rl_traffic.py: play 20 seconds of made-up traffic against nginx with limit_req and save the access log.
python rl_traffic.py --site 5r/s:10 --login 30r/m:5 --dry-run --out dry.log
"""
import argparse
import pathlib
import random
import shutil
from rl_nginx import Nginx, play
CONF = """
limit_req_zone $binary_remote_addr zone=site:1m rate=SITE_RATE;
limit_req_zone $binary_remote_addr zone=login:1m rate=LOGIN_RATE;
server {
listen 8081;
limit_req_status 429;
limit_req_dry_run DRY;
location /login { limit_req zone=login burst=LOGIN_BURST nodelay; try_files /ok.txt =404; }
location / { limit_req zone=site burst=SITE_BURST nodelay; try_files /ok.txt =404; }
}
"""
def traffic(seed=1, seconds=20):
"""A made-up day: browsers, pollers, a phone app, a scraper and a password-guessing script."""
rng, events = random.Random(seed), []
def add(t, path, cls, host):
events.append((t, path, {"X-Class": cls}, f"127.0.0.{host}"))
for host in range(11, 17): # six browsers: a page plus 11 assets within 120 ms
t = rng.uniform(0, 4)
while t < seconds:
add(t, "/page", "browser", host)
for k in range(11):
add(t + rng.uniform(0.005, 0.12), f"/static/{k}.js", "browser", host)
t += rng.uniform(3, 6)
for host in (21, 22): # two dashboards polling /api/status twice a second
t = rng.uniform(0, 0.5)
while t < seconds:
add(t, "/api/status", "poller", host)
t += rng.uniform(0.4, 0.6)
t = 2.0 # a phone app that syncs 15 calls at once every 5 seconds
while t < seconds:
for _ in range(15):
add(t + rng.uniform(0, 0.05), "/api/sync", "app", 51)
t += 5
for host, path, cls, rate in ((31, "/api/items", "scraper", 30), (41, "/login", "guesser", 12)):
t = rng.random()
while t < seconds: # Poisson arrivals at `rate` requests a second
add(t, path, cls, host)
t += rng.expovariate(rate)
return events
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("--site", default="5r/s:10")
ap.add_argument("--login", default="30r/m:5")
ap.add_argument("--dry-run", action="store_true")
ap.add_argument("--seed", type=int, default=1)
ap.add_argument("--out", default="traffic.log")
a = ap.parse_args()
(site_rate, site_burst), (login_rate, login_burst) = a.site.split(":"), a.login.split(":")
conf = (CONF.replace("SITE_RATE", site_rate).replace("SITE_BURST", site_burst)
.replace("LOGIN_RATE", login_rate).replace("LOGIN_BURST", login_burst)
.replace("DRY", "on" if a.dry_run else "off"))
with Nginx("traffic", conf) as ngx:
play(traffic(a.seed))
shutil.copy(ngx.dir / "logs" / "access.log", pathlib.Path(a.out))
print(f"{len(open(a.out).readlines())} requests logged to {a.out}")
# rl_tune.py
"""rl_tune.py: what would limit_req do to the traffic in this access log?
python rl_tune.py dry.log --skip /login --check 5r/s:10 model versus nginx's own dry-run verdicts
python rl_tune.py dry.log --skip /login what-if table for a list of settings
python rl_tune.py enforced.log --skip /login --measured what nginx really did, in the same table
Settings are RATE:BURST (nodelay), for example 10r/s:20 or 30r/m:5. The log is JSON lines as in rl_nginx.py.
"""
import argparse
import json
from rl_model import Limit, Zone, decide
CLASSES = ("browser", "poller", "app", "scraper", "guesser")
DEFAULTS = ["5r/s:0", "5r/s:10", "5r/s:20", "10r/s:20", "10r/s:40", "20r/s:40"]
VERDICT = {"PASSED": "PASSED", "DELAYED_DRY_RUN": "DELAYED", "REJECTED_DRY_RUN": "REJECTED",
"DELAYED": "DELAYED", "REJECTED": "REJECTED"}
def parse(spec):
rate, _, burst = spec.partition(":")
count, _, per = rate.partition("r/")
return int(count), per or "s", int(burst or 0)
def load(path, only=None, skip=None):
rows = []
for line in open(path, encoding="utf-8"):
row = json.loads(line)
row["at"] = round(float(row["t"]) * 1000) - round(float(row["rt"]) * 1000) # arrival, not completion
if (only and not row["uri"].startswith(only)) or (skip and row["uri"].startswith(skip)):
continue
rows.append(row)
return sorted(rows, key=lambda r: r["at"])
def replay(rows, spec, key="ip"):
count, per, burst = parse(spec)
limit = Limit(Zone(count, per), burst, nodelay=True)
return [decide([limit], [row[key]], row["at"])[0] for row in rows]
def table(rows, verdicts, label):
cells = []
for cls in CLASSES:
mine = [v for r, v in zip(rows, verdicts) if r["cls"] == cls]
cells.append(f"{100 * mine.count('REJECTED') / len(mine):5.1f}%" if mine else " -")
total = 100 * verdicts.count("REJECTED") / len(verdicts)
print(f"{label:<12} {total:5.1f}% " + " ".join(f"{c:>8}" for c in cells))
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("log")
ap.add_argument("--only")
ap.add_argument("--skip")
ap.add_argument("--check", metavar="SETTING")
ap.add_argument("--measured", action="store_true")
ap.add_argument("--try", nargs="+", dest="settings", default=DEFAULTS)
a = ap.parse_args()
rows = load(a.log, a.only, a.skip)
if a.check:
model = replay(rows, a.check)
logged = [VERDICT.get(r["lim"], r["lim"]) for r in rows]
agree = sum(m == v for m, v in zip(model, logged))
print(f"{a.check}: the model agrees with nginx on {agree} of {len(rows)} requests")
raise SystemExit(0 if agree == len(rows) else 1)
print(f"{'setting':<12} {'all':>6} " + " ".join(f"{c:>8}" for c in CLASSES) + " (share of requests rejected)")
counts = [sum(r["cls"] == c for r in rows) for c in CLASSES]
print(f"{'requests':<12} {len(rows):>6} " + " ".join(f"{n or '-':>8}" for n in counts))
if a.measured:
table(rows, [VERDICT.get(r["lim"], r["lim"]) for r in rows], "measured")
else:
for spec in a.settings:
table(rows, replay(rows, spec), spec)
Record a dry run
To use the tuner on a real server, add $msec, $request_time, the client address and $request_uri to a JSON log_format like the one in rl_nginx.py; the cls label exists only in the lab, so group by address or path instead. Start with a first guess, 5r/s with a burst of 10 for the site and 30r/m with a burst of 5 for /login, in dry-run mode:
python rl_traffic.py --site 5r/s:10 --login 30r/m:5 --dry-run --out dry.log
1251 requests logged to dry.log
Check the model against nginx’s own dry-run verdicts
Before trusting any what-if number, check that the model reproduces what nginx logged for the setting that was actually running:
python rl_tune.py dry.log --skip /login --check 5r/s:10
5r/s:10: the model agrees with nginx on 1009 of 1009 requests
python rl_tune.py dry.log --only /login --check 30r/m:5
30r/m:5: the model agrees with nginx on 242 of 242 requests
The model agrees with nginx on every one of the 1,251 requests. That is what makes the next table trustworthy.
Ask what-if questions
The site as a whole
python rl_tune.py dry.log --skip /login
setting all browser poller app scraper guesser (share of requests rejected)
requests 1009 312 81 60 556 -
5r/s:0 80.8% 91.7% 0.0% 93.3% 85.1% -
5r/s:10 48.5% 8.3% 0.0% 26.7% 80.4% -
5r/s:20 43.3% 0.0% 0.0% 0.0% 78.6% -
10r/s:20 33.5% 0.0% 0.0% 0.0% 60.8% -
10r/s:40 31.5% 0.0% 0.0% 0.0% 57.2% -
20r/s:40 12.0% 0.0% 0.0% 0.0% 21.8% -
The settings read as rate and burst, so 5r/s:0 is five per second with no burst. The first row is the Step 2 limit applied to real-looking traffic: it would refuse 91.7% of the browser requests and 93.3% of the app’s, which means broken pages and a broken app. Adding a burst of 10 helps but still refuses 8.3% of browser requests (the last assets of a page load) and 26.7% of the app’s fifteen-call syncs. A burst of 20 covers both: browsers, dashboards and the app lose nothing, while the scraper still loses 78.6% of its requests. You can check that against arithmetic: the scraper sends 556 requests in 20 seconds, the limit lets through about 5 × 20 + 20 = 120, and the other 436 are refused, which is 78.4%. Raising the rate to 10 or 20 per second spares more of the scraper than you want.
The login page gets a stricter limit of its own
python rl_tune.py dry.log --only /login --try 30r/m:0 30r/m:5 60r/m:5 60r/m:10 120r/m:10
setting all browser poller app scraper guesser (share of requests rejected)
requests 242 - - - - 242
30r/m:0 95.9% - - - - 95.9%
30r/m:5 93.8% - - - - 93.8%
60r/m:5 89.7% - - - - 89.7%
60r/m:10 87.6% - - - - 87.6%
120r/m:10 79.3% - - - - 79.3%
Only the password guesser reaches /login in this traffic, so the other columns are empty. A person logs in once or twice, so thirty per minute with a burst of five costs them nothing while the guesser loses 93.8% of its attempts. Your real log will have real users on /login; run the same table on it before choosing.
Enforce and compare
Now run the same schedule again with the chosen settings and no --dry-run, so nginx really refuses, and print what happened next to what the model predicted from the dry-run log:
python rl_traffic.py --site 5r/s:20 --login 30r/m:5 --out enforced.log
1251 requests logged to enforced.log
python rl_tune.py dry.log --skip /login --try 5r/s:20
setting all browser poller app scraper guesser (share of requests rejected)
requests 1009 312 81 60 556 -
5r/s:20 43.3% 0.0% 0.0% 0.0% 78.6% -
python rl_tune.py enforced.log --skip /login --measured
setting all browser poller app scraper guesser (share of requests rejected)
requests 1009 312 81 60 556 -
measured 43.3% 0.0% 0.0% 0.0% 78.6% -
python rl_tune.py dry.log --only /login --try 30r/m:5
setting all browser poller app scraper guesser (share of requests rejected)
requests 242 - - - - 242
30r/m:5 93.8% - - - - 93.8%
python rl_tune.py enforced.log --only /login --measured
setting all browser poller app scraper guesser (share of requests rejected)
requests 242 - - - - 242
measured 93.8% - - - - 93.8%
Prediction and measurement agree to the decimal. Be honest about why: the second run replays the same random schedule, so the arrivals are almost identical, and the model assumes that clients behave the same when refused. Real clients retry, back off or give up, so a real rollout will wobble around the prediction. That is the reason for the order of work: log, what-if, dry run on live traffic, enforce, then keep watching the share of REJECTED in the access log.
Check: the model agrees with nginx’s dry-run verdicts on every request, and the setting you choose rejects none of the clients you care about. Common mistake: sizing the burst from average traffic. The average hides the clumps; the log shows them.
Step 8: Answer the client properly and let monitors through
A refused client should learn that it was throttled and when to come back. The configuration below does that with a named location: error_page 429 = @slow_down; sends every 429 to a block that returns a small JSON body and a Retry-After header. It also keeps an uptime monitor out of the limit. The geo block marks 127.0.0.5 as exempt, the map turns that mark into an empty key, and, as you saw in Steps 4 and 5, an empty key is never limited. The script prints what a rejected client sees, what the exempt monitor sees, and the two kinds of line the limiter writes to the error log.
# respond.py
"""respond.py: a useful 429 answer, an exempt address, and what the error log records."""
import re
import threading
from rl_nginx import Nginx, get
CONF = """
geo $exempt {
default 0;
127.0.0.5 1; # the uptime monitor
}
map $exempt $limit_key {
0 $binary_remote_addr;
1 ""; # an empty key is never limited
}
limit_req_zone $limit_key zone=api:1m rate=5r/s;
server {
listen 8081;
limit_req_status 429;
limit_req_log_level warn;
error_page 429 = @slow_down;
location / {
limit_req zone=api burst=5;
try_files /ok.txt =404;
}
location @slow_down {
default_type application/json;
add_header Retry-After 1 always;
return 429 '{"error":"rate_limited"}';
}
}
"""
def at_once(n, source):
"""n requests released together; returns every full response."""
gate, out = threading.Barrier(n), []
def one():
gate.wait()
out.append(get("/", source=source))
threads = [threading.Thread(target=one) for _ in range(n)]
[t.start() for t in threads]
[t.join() for t in threads]
return out
with Nginx("step7", CONF, level="notice") as ngx:
res = at_once(12, "127.0.0.4")
codes = [r[0] for r in res]
print(f"12 requests at once from 127.0.0.4: {codes.count(200)} answered 200, {codes.count(429)} answered 429")
status, headers, _, body = next(r for r in res if r[0] == 429)
print(f"a rejected request: HTTP {status}, Retry-After: {headers.get('Retry-After')}, "
f"Content-Type: {headers.get('Content-Type')}, body: {body.decode()}")
res = at_once(30, "127.0.0.5")
print("30 requests at once from the exempt 127.0.0.5:", [r[0] for r in res].count(200), "answered 200")
rows = [r for r in ngx.access_log() if r["ip"] == "127.0.0.5"]
print("their $limit_req_status values:", sorted({r["lim"] for r in rows}))
print()
seen = set()
for line in ngx.error_log().splitlines():
m = re.search(r"\[(warn|notice)\] \d+#\d+: \*\d+ (delaying|limiting) requests?(, excess: [\d.]+),? by zone \"(\w+)\", client: ([\d.]+)", line)
if m and m.group(2) not in seen:
seen.add(m.group(2))
print(f"[{m.group(1)}] {m.group(2)} request{m.group(3)} by zone \"{m.group(4)}\", client: {m.group(5)}")
# the same configuration without the "always" flag: add_header skips 4xx answers
with Nginx("respond2", CONF.replace("add_header Retry-After 1 always;", "add_header Retry-After 1;")):
status, headers, _, _ = next(r for r in at_once(12, "127.0.0.4") if r[0] == 429)
print(f"\nwithout the always flag: HTTP {status}, Retry-After header present: {'Retry-After' in headers}")
python respond.py
12 requests at once from 127.0.0.4: 6 answered 200, 6 answered 429
a rejected request: HTTP 429, Retry-After: 1, Content-Type: application/json, body: {"error":"rate_limited"}
30 requests at once from the exempt 127.0.0.5: 30 answered 200
their $limit_req_status values: ['']
[notice] delaying request, excess: 1.000 by zone "api", client: 127.0.0.4
[warn] limiting request, excess: 6.000 by zone "api", client: 127.0.0.4
without the always flag: HTTP 429, Retry-After header present: False
Twelve simultaneous requests against burst=5 give one immediate success, five delayed ones that also end in 200 and six refusals. The rejected request carries a 429, Retry-After: 1 and a JSON body. The monitor’s thirty simultaneous requests all succeed and their $limit_req_status is empty, because they were never counted. The error log distinguishes the two outcomes: delays are logged one level below refusals (the documentation says so, and the lab shows notice against warn), and the number after “excess” is how many requests the client is ahead of the rate, so 6.000 here is the burst of five plus the request that overflowed it.
The last line of output is a trap. add_header only adds a header to success and redirect responses; the documentation lists the codes (200, 201, 204, 206, 301, 302, 303, 304, 307 and 308) and adds that with the always parameter “the header field will be added regardless of the response code.” Leave always out and your 429 silently loses its Retry-After, as the last line shows. A static Retry-After is a hint, not a promise: pick a value that covers your slowest zone. In the finished policy below it is 2 seconds, because the login zone refills one slot every two seconds.
Step 9: Size the zone so it does not forget
The zone is fixed-size memory, and the documentation tells you what happens when it fills: “If the zone storage is exhausted, the least recently used state is removed.” A removed state means that client starts again with an empty bucket, which is harmless for a quiet client and a gift to a throttled one. The script below makes it concrete: it throttles one key, pushes a growing number of other new keys through the zone, asks the first key again, and bisects to find how many other keys it takes to make the zone forget. It does this for a binary key and a text key, in a deliberately small zone of 128 kilobytes.
# zone_size.py
"""zone_size.py: how many keys fit in a zone, and what a flood of new keys does to a throttled client."""
import http.client
import threading
from rl_nginx import PORT, Nginx
CONF = """
limit_req_zone $binary_remote_addr zone=bin:128k rate=1r/m;
limit_req_zone $remote_addr zone=txt:128k rate=1r/m;
server {
listen 8081;
set_real_ip_from 127.0.0.1;
real_ip_header X-Forwarded-For;
limit_req_status 429;
location /bin { limit_req zone=bin; try_files /ok.txt =404; }
location /txt { limit_req zone=txt; try_files /ok.txt =404; }
}
"""
counter = [0]
def new_keys(n):
out = []
for _ in range(n):
counter[0] += 1
c = counter[0]
out.append(f"10.{(c >> 16) & 255}.{(c >> 8) & 255}.{c & 255}")
return out
def hit(conn, path, key):
conn.request("GET", path, headers={"X-Forwarded-For": key})
resp = conn.getresponse()
resp.read()
return resp.status
def flood(path, keys, workers=4):
def work(chunk):
conn = http.client.HTTPConnection("127.0.0.1", PORT)
for key in chunk:
hit(conn, path, key)
conn.close()
threads = [threading.Thread(target=work, args=(keys[i::workers],)) for i in range(workers)]
[t.start() for t in threads]
[t.join() for t in threads]
def still_throttled(path, flood_size):
"""Throttle one key, push `flood_size` other new keys through the zone, ask again."""
conn = http.client.HTTPConnection("127.0.0.1", PORT)
key = new_keys(1)[0]
assert hit(conn, path, key) == 200 and hit(conn, path, key) == 429 # known, and throttled
flood(path, new_keys(flood_size))
answer = hit(conn, path, key)
conn.close()
return answer == 429
def capacity(path):
lo, hi = 1, 8192
while hi - lo > 1:
mid = (lo + hi) // 2
lo, hi = (mid, hi) if still_throttled(path, mid) else (lo, mid)
return hi
with Nginx("step8", CONF) as ngx:
for path, label in (("/bin", "$binary_remote_addr"), ("/txt", "$remote_addr (text)")):
n = capacity(path)
print(f"zone of 128k keyed on {label:<20} forgets a throttled key after {n} other new keys "
f"(about {131072 / n:.0f} bytes per state)")
print("a throttled key, then a flood of 4000 other keys, then the throttled key again:")
print(" still throttled:", still_throttled("/bin", 4000))
python zone_size.py
zone of 128k keyed on $binary_remote_addr forgets a throttled key after 1889 other new keys (about 69 bytes per state)
zone of 128k keyed on $remote_addr (text) forgets a throttled key after 1889 other new keys (about 69 bytes per state)
a throttled key, then a flood of 4000 other keys, then the throttled key again:
still throttled: False
The throttled key is forgotten after about 1,900 other new keys in a 128k zone, about 69 bytes per state, a little more than the documented 64, presumably because the zone also spends some memory on its own bookkeeping. That is consistent with the documentation for a 32-bit build: “The stored state always occupies 64 bytes on 32-bit platforms and 128 bytes on 64-bit platforms. One megabyte zone can keep about 16 thousand 64-byte states or about 8 thousand 128-byte states.” On a 64-bit Linux server expect roughly half as many states per megabyte (about 8,000 by the documentation’s figure), and fewer again for long text keys, which I did not measure. Size a zone for the number of distinct keys you expect in a busy minute, with generous headroom, and remember that a flood of rotated or spoofed addresses is precisely what pushes states out, including the state of a client you are throttling. In this lab the text key ($remote_addr) cost the same as the binary key; that is for IPv4 text, and I did not measure longer IPv6 keys.
For comparison, the limit_conn module documents the opposite behaviour: “If the zone storage is exhausted, the server will return the error to all further requests.” A full connection zone refuses newcomers instead of forgetting old keys, so give it room too.
Step 10: Rate is not concurrency, so add limit_conn for expensive endpoints
limit_req limits how often requests start. It says nothing about how many are running at the same time. If your backend takes a second per request, a client allowed five requests a second has five running at any moment, and if the backend slows down to two and a half seconds, about twelve. That is Little’s law from queueing theory: the average number of requests in the system equals the arrival rate multiplied by the average time each one spends there. limit_conn is the directive for the other number. The documentation: “A connection is counted only if it has a request being processed by the server and the whole request header has already been read.” And for HTTP/2 and HTTP/3: “each concurrent request is considered a separate connection.”
The stand-in backend below takes one second per request by default and remembers the highest number of requests it handled at once since you last asked. The script asks it two questions. First, fifteen requests arrive together: with only limit_req burst=20 nodelay and with limit_conn conn 3 added. Second, a steady five requests a second for six seconds against a backend that takes one second and then two and a half.
# slow_app.py
"""slow_app.py: a stand-in backend. Each request takes d seconds (default 1) and the server remembers its peak concurrency."""
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse
LOCK = threading.Lock()
STATE = {"now": 0, "peak": 0}
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
url = urlparse(self.path)
if url.path == "/peak": # read and reset the peak
with LOCK:
body = str(STATE["peak"]).encode()
STATE["peak"] = STATE["now"]
else:
with LOCK:
STATE["now"] += 1
STATE["peak"] = max(STATE["peak"], STATE["now"])
time.sleep(float(parse_qs(url.query).get("d", ["1"])[0]))
with LOCK:
STATE["now"] -= 1
body = b"done"
self.send_response(200)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
def serve(port=9001):
server = ThreadingHTTPServer(("127.0.0.1", port), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server
if __name__ == "__main__":
serve()
threading.Event().wait()
# conn_vs_rate.py
"""conn_vs_rate.py: limit_req caps the rate of requests, not how many are in flight. limit_conn caps the second."""
import threading
import time
import slow_app
from rl_nginx import Nginx, burst, get
CONF = """
limit_req_zone $binary_remote_addr zone=rate:1m rate=5r/s;
limit_conn_zone $binary_remote_addr zone=conn:1m;
server {
listen 8081;
limit_req_status 429;
limit_conn_status 429;
location /rate { limit_req zone=rate burst=20 nodelay;
proxy_pass http://127.0.0.1:9001; }
location /both { limit_req zone=rate burst=20 nodelay;
limit_conn conn 3;
proxy_pass http://127.0.0.1:9001; }
}
"""
def peak():
return int(get("/peak", port=9001)[3])
def steady(path, source, seconds, delay):
"""5 requests a second for `seconds`, each needing `delay` seconds from the backend."""
threads = []
for i in range(int(seconds * 5)):
t = threading.Thread(target=get, args=(f"{path}?d={delay}", None, source))
t.start()
threads.append(t)
time.sleep(0.2)
[t.join() for t in threads]
slow_app.serve()
with Nginx("step9", CONF):
print("fifteen requests arrive together, the backend needs 1 s for each:")
print("setting answered 200 answered 429 peak requests in the backend")
for path, label, source in (("/rate", "limit_req only", "127.0.0.6"), ("/both", "limit_req + limit_conn 3", "127.0.0.7")):
peak()
res = burst(15, path, source=source)
codes = [s for _, s, _ in res]
print(f"{label:<24} {codes.count(200):>9} {codes.count(429):>13} {peak():>18}")
print()
print("a steady 5 requests a second for 6 s (never rejected), as the backend slows down:")
print("backend time per request peak requests in the backend")
for delay, source in ((1, "127.0.0.8"), (2.5, "127.0.0.9")):
peak()
steady("/rate", source, 6, delay)
print(f"{delay:>22} s {peak():>26}")
python conn_vs_rate.py
fifteen requests arrive together, the backend needs 1 s for each:
setting answered 200 answered 429 peak requests in the backend
limit_req only 15 0 15
limit_req + limit_conn 3 3 12 3
a steady 5 requests a second for 6 s (never rejected), as the backend slows down:
backend time per request peak requests in the backend
1 s 6
2.5 s 13
Without limit_conn, all fifteen simultaneous requests pass the rate limit (they fit in the burst) and fifteen reach the backend at once. With limit_conn conn 3 three get through, twelve are refused immediately and the backend never sees more than three. The steady stream shows Little’s law at work: five a second against a one-second backend peaks at six requests in flight, and when the backend slows to two and a half seconds the peak is thirteen, with no request ever refused by the rate limit. Put a limit_conn on login, search, report and export endpoints, size it to the number of concurrent requests one legitimate client can plausibly need, and let limit_req handle the rate. For limits inside the application, our post on backpressure and load shedding covers the matching idea.
Step 11: Put it together and test it
The policy file
Everything you have learned fits in one file. policy.conf is the finished policy: the exempt monitor, the IPv6-aware key, a 5r/s site zone with a burst of 20 (the Step 7 choice), a 30r/m login zone with a burst of 5, trust in exactly one proxy, a 429 with Retry-After and JSON, and dry-run switched off. The line try_files /ok.txt =404; stands for your real handler, and the zone sizes are ones you should revisit with Step 9 in mind. Remember the inheritance rule from the documentation: “These directives are inherited from the previous configuration level if and only if there are no limit_req directives defined on the current level.” A location that declares its own limit_req does not also get the server’s.
# policy.conf: the finished policy. Everything in this file goes inside the http { } block.
geo $exempt {
default 0;
127.0.0.5 1; # the uptime monitor
}
include net_key.conf; # defines $ip_key: one key per IPv4 address and per IPv6 /64
map $exempt $client_key {
0 $ip_key;
1 ""; # an empty key is never limited
}
limit_req_zone $client_key zone=site:2m rate=5r/s;
limit_req_zone $client_key zone=login:1m rate=30r/m;
server {
listen 8081;
set_real_ip_from 127.0.0.2; # the proxy or CDN in front of nginx
real_ip_header X-Forwarded-For;
limit_req_status 429;
limit_req_log_level warn;
limit_req_dry_run off;
error_page 429 = @rate_limited;
location /login {
limit_req zone=login burst=5 nodelay;
try_files /ok.txt =404; # in a real site: proxy_pass, fastcgi_pass or a static file
}
location / {
limit_req zone=site burst=20 nodelay;
try_files /ok.txt =404;
}
location @rate_limited {
default_type application/json;
add_header Retry-After 2 always;
return 429 '{"error":"rate_limited"}';
}
}
Tests that state each promise
A configuration like this is easy to break with a one-word edit, and nothing will tell you. So give it tests. Each test below states one promise of the policy and checks it against a real nginx: a burst is served at once, the bucket refills at the configured rate, a rejection is a 429 with the right headers and body, login is stricter and refills slowly, the monitor is never limited, clients behind the proxy have their own buckets, forged headers do not help, and IPv6 rotation does not escape. Each test uses its own client address so tests cannot spend each other’s budget.
# test_policy.py
"""test_policy.py: the rate-limit policy as executable checks. POLICY=other.conf runs them against another file."""
import ipaddress
import json
import os
import pathlib
import random
import re
import threading
import time
import pytest
from rl_nginx import Nginx, get
POLICY = pathlib.Path(os.environ.get("POLICY", "policy.conf"))
PROXY = "127.0.0.2" # the address that policy.conf trusts to tell the truth in X-Forwarded-For
rng = random.Random(5)
@pytest.fixture(scope="module")
def ngx():
with Nginx("policy", POLICY.read_text(encoding="utf-8"), includes=["net_key.conf"]) as server:
yield server
def at_once(n, path="/", source=None, headers=None):
"""n requests released together. Returns [(status, headers, seconds, body)]."""
gate, out = threading.Barrier(n), []
def one():
gate.wait()
out.append(get(path, headers, source))
threads = [threading.Thread(target=one) for _ in range(n)]
[t.start() for t in threads]
[t.join() for t in threads]
return out
def one_by_one(n, source, header):
"""n quick requests in a row; header(i) is the X-Forwarded-For value of request i. Returns the number of 200s."""
return sum(get("/", {"X-Forwarded-For": header(i)}, source)[0] == 200 for i in range(n))
def ok(results):
return sum(r[0] == 200 for r in results)
def test_a_burst_is_served_at_once(ngx):
res = at_once(30, source="127.0.0.21")
assert 21 <= ok(res) <= 22 # one request plus burst=20
assert max(r[2] for r in res if r[0] == 200) < 1.0 # nodelay: nobody waits
def test_the_bucket_refills_at_the_configured_rate(ngx):
at_once(30, source="127.0.0.22")
time.sleep(1.0)
assert 4 <= ok(at_once(30, source="127.0.0.22")) <= 8 # about 5 a second
def test_a_rejection_is_a_429_with_retry_after_and_json(ngx):
status, headers, _, body = next(r for r in at_once(30, source="127.0.0.23") if r[0] != 200)
assert status == 429
assert int(headers["Retry-After"]) >= 1
assert headers["Content-Type"].startswith("application/json")
assert json.loads(body) == {"error": "rate_limited"}
def test_login_is_stricter(ngx):
assert 6 <= ok(at_once(12, "/login", "127.0.0.24")) <= 7
def test_login_refills_slowly(ngx):
at_once(12, "/login", "127.0.0.25")
time.sleep(2.2)
assert 1 <= ok(at_once(12, "/login", "127.0.0.25")) <= 2 # 30 a minute is one every two seconds
def test_the_monitor_is_never_limited(ngx):
assert ok(at_once(60, source="127.0.0.5")) == 60
def test_clients_behind_the_proxy_have_their_own_buckets(ngx):
at_once(30, source=PROXY, headers={"X-Forwarded-For": "203.0.113.50"})
assert ok(at_once(5, source=PROXY, headers={"X-Forwarded-For": "203.0.113.51"})) == 5
def test_a_forged_header_from_an_untrusted_peer_is_ignored(ngx):
fake = lambda i: f"{rng.randrange(1, 250)}.{rng.randrange(256)}.{rng.randrange(256)}.{i + 1}"
assert one_by_one(40, "127.0.0.26", fake) <= 25
def test_the_forged_left_end_of_the_header_is_ignored(ngx):
fake = lambda i: f"10.{rng.randrange(256)}.{rng.randrange(256)}.{i + 1}, 198.51.100.77"
assert one_by_one(40, PROXY, fake) <= 25
def test_one_ipv6_network_is_one_bucket(ngx):
net = ipaddress.IPv6Network("2001:db8:77:1::/64")
assert one_by_one(40, PROXY, lambda i: str(net[0] + rng.getrandbits(64))) <= 25
def test_different_ipv6_networks_do_not_share_a_bucket(ngx):
addr = lambda i: str(ipaddress.IPv6Address((0x20010DB8 << 96) | ((0x500 + i) << 64) | rng.getrandbits(64)))
assert one_by_one(40, PROXY, addr) >= 38
python -m pytest -q test_policy.py
........... [100%]
11 passed in 7.18s
Break it on purpose
Passing tests only mean something if they can fail. The last script breaks the policy in sixteen plausible ways, such as removing nodelay, trusting every peer, keying on the header, dropping the IPv6 rules, leaving dry run on, or replacing the handler with return, and runs the whole suite against each broken copy. A mistake counts as caught when at least one test fails.
# mutants.py
"""mutants.py: break policy.conf in sixteen plausible ways and check that test_policy.py notices each one."""
import os
import pathlib
import re
import subprocess
import sys
BASE = pathlib.Path("policy.conf").read_text(encoding="utf-8")
MUTANTS = [
("site zone: nodelay removed", [("limit_req zone=site burst=20 nodelay;", "limit_req zone=site burst=20;")]),
("site zone: burst 20 -> 5", [("zone=site burst=20", "zone=site burst=5")]),
("site zone: rate 5r/s -> 500r/s", [("zone=site:2m rate=5r/s", "zone=site:2m rate=500r/s")]),
("real_ip: trust every peer", [("set_real_ip_from 127.0.0.2;", "set_real_ip_from 0.0.0.0/0;")]),
("real_ip: both lines removed", [(" set_real_ip_from 127.0.0.2; # the proxy or CDN in front of nginx\n", ""),
(" real_ip_header X-Forwarded-For;\n", "")]),
("key: the X-Forwarded-For header", [("0 $ip_key;", "0 $http_x_forwarded_for;")]),
("key: a variable that is empty ($server_name)", [("0 $ip_key;", "0 $server_name;")]),
("key: IPv6 rules dropped", [("include net_key.conf;", "map $remote_addr $ip_key { default $remote_addr; }\n#")]),
("exempt: the monitor is not exempt", [("127.0.0.5 1;", "127.0.0.5 0;")]),
("exempt: everyone is exempt", [("default 0;", "default 1;")]),
("status: limit_req_status removed", [(" limit_req_status 429;\n", "")]),
("answer: Retry-After removed", [(" add_header Retry-After 2 always;\n", "")]),
("rollout: dry run left on", [("limit_req_dry_run off;", "limit_req_dry_run on;")]),
("handler: return instead of a real handler", [("limit_req zone=site burst=20 nodelay;\n try_files /ok.txt =404;",
"limit_req zone=site burst=20 nodelay;\n return 200 \"ok\";")]),
("login: uses the site zone", [("limit_req zone=login burst=5 nodelay;", "limit_req zone=site burst=5 nodelay;")]),
("login: limit removed", [(" limit_req zone=login burst=5 nodelay;\n", "")]),
]
def run_tests(path):
env = {**os.environ, "POLICY": str(path), "COLUMNS": "200"}
proc = subprocess.run([sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", "test_policy.py"],
capture_output=True, text=True, env=env)
count = re.search(r"(\d+) failed", proc.stdout)
first = re.search(r"FAILED test_policy.py::(\w+)", proc.stdout)
return proc.returncode, int(count.group(1)) if count else 0, first.group(1) if first else None
pathlib.Path("mutants").mkdir(exist_ok=True)
code, _, _ = run_tests("policy.conf")
print(f"the real policy: {'all tests pass' if code == 0 else 'TESTS FAIL'}")
caught = 0
for n, (name, edits) in enumerate(MUTANTS, 1):
text = BASE
for old, new in edits:
assert text.count(old) == 1, (name, old)
text = text.replace(old, new)
path = pathlib.Path("mutants") / f"{n:02}.conf"
path.write_text(text, encoding="utf-8", newline="\n")
code, failed, first = run_tests(path)
caught += failed > 0
verdict = f"caught: {failed} of 11 tests fail" if failed else ("NOT CAUGHT" if code == 0 else "broken config")
print(f"{n:>2} {name:<46} {verdict}")
print(f"{caught} of {len(MUTANTS)} mistakes caught")
python mutants.py
the real policy: all tests pass
1 site zone: nodelay removed caught: 5 of 11 tests fail
2 site zone: burst 20 -> 5 caught: 1 of 11 tests fail
3 site zone: rate 5r/s -> 500r/s caught: 6 of 11 tests fail
4 real_ip: trust every peer caught: 1 of 11 tests fail
5 real_ip: both lines removed caught: 2 of 11 tests fail
6 key: the X-Forwarded-For header caught: 8 of 11 tests fail
7 key: a variable that is empty ($server_name) caught: 8 of 11 tests fail
8 key: IPv6 rules dropped caught: 1 of 11 tests fail
9 exempt: the monitor is not exempt caught: 1 of 11 tests fail
10 exempt: everyone is exempt caught: 8 of 11 tests fail
11 status: limit_req_status removed caught: 1 of 11 tests fail
12 answer: Retry-After removed caught: 1 of 11 tests fail
13 rollout: dry run left on caught: 8 of 11 tests fail
14 handler: return instead of a real handler caught: 6 of 11 tests fail
15 login: uses the site zone caught: 1 of 11 tests fail
16 login: limit removed caught: 2 of 11 tests fail
16 of 16 mistakes caught
All sixteen are caught. Seven of them are caught by exactly one test (a burst of 5 instead of 20, trusting every peer, the dropped IPv6 rules, the monitor, the status code, the missing Retry-After and the login zone swap), so none of those tests is redundant: delete one and a whole kind of mistake slips through unnoticed. Put the tests in your deployment pipeline, run them whenever the policy file changes, and run nginx -t on the real configuration as well.
Confirm the whole thing works end to end
Before you copy any of this to a real server, walk through this list. The test suite passes against the policy file, and the mutation run catches every planted mistake. The model agrees with nginx on a dry-run log from your own traffic, and the setting you chose rejects none of the clients you care about. nginx -t passes on the production configuration, and the location you limit ends in a real handler (proxy_pass, fastcgi_pass, a file), not return. The address in your access log is the visitor’s, not the proxy’s. The zone is sized for a busy minute with headroom, and the expensive endpoints also have a limit_conn. After you switch from dry run to enforcement, count REJECTED in the access log for a day and compare it with the what-if table; your rollback is one line, limit_req_dry_run on;, followed by a reload.
Where to go next
Three directions are worth your time. Limit by something other than the address once you know who the client is: after authentication, an API key or user ID is a better key than an IP address, because a whole office or mobile carrier can sit behind one address, but only use a value the client cannot forge. Move volumetric protection to the edge: nginx can refuse requests cheaply, but a flood that fills your network link never reaches it, so use your CDN or provider for that layer. And watch the limiter: alert when the share of 429 responses jumps, using the alerting pattern from our post on burn-rate alerts with promtool. For the other end of an nginx-in-front-of-an-app setup, the posts on random 502 errors from the keep-alive race and on Cache-Control in FastAPI and nginx use the same lab style. Finally, the nginx documentation lists a variable rate (from 1.31.3) and zone synchronization across servers as features of the commercial subscription; neither is available in the open-source module used here.
Sources
Everything above comes from the nginx documentation and source plus the measurements in this lab. The module pages: ngx_http_limit_req_module, ngx_http_limit_conn_module, ngx_http_realip_module, ngx_http_rewrite_module (for return) and ngx_http_headers_module (for add_header). The platform note is on nginx for Windows. The algorithm is in ngx_http_limit_req_module.c at the release-1.30.8 tag, and the queueing result is on Wikipedia’s Little’s law page.








No Comment! Be the first one.