limit_req_zone and limit_req in Nginx - Time & Space Complexity
When nginx limits request rates, it must track and check each request against stored data.
We want to understand how the time to process requests grows as more requests come in.
Analyze the time complexity of the following nginx configuration snippet.
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
server {
location / {
limit_req zone=one burst=5;
proxy_pass http://backend;
}
}
This code limits requests per IP address to 1 request per second with some burst allowance.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking and updating the request count for each IP in the shared memory zone.
- How many times: Once per incoming request.
Each request triggers a lookup and update in a fixed-size memory zone keyed by IP.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 lookups and updates |
| 100 | 100 lookups and updates |
| 1000 | 1000 lookups and updates |
Pattern observation: The work grows linearly with the number of requests.
Time Complexity: O(n)
This means the time to process requests grows directly with the number of requests.
[X] Wrong: "The request limiting happens instantly no matter how many requests come in."
[OK] Correct: Each request requires a lookup and update in memory, so more requests mean more work.
Understanding how nginx handles request limiting helps you reason about performance under load, a useful skill in real-world server management.
What if we increased the burst size? How would the time complexity change?