1001Ferramentas
🛑 Dev

NGINX Rate Limit Generator

Configure limit_req_zone and limit_req in NGINX to rate limit per IP. Includes configurable burst and nodelay.

Rate limiting in nginx without shutting out real users

nginx rate limiting works in two parts that live in different places in the file, and that is exactly where the configuration tends to fail. The directive defining the shared zone goes in the http block; the one applying the limit goes in server or location. Defining the zone and forgetting to apply it results in no limit at all — with no error whatsoever.

Fill in the zone name, the memory size, the rate and the burst and the page assembles both lines, each marked with where it belongs. The zone size is shared memory holding per-key state: one megabyte holds on the order of sixteen thousand addresses, so ten megabytes comfortably cover most sites.

The part that confuses most is the burst and nodelay pair. nginx uses a leaky bucket: the rate is constant and the burst is how much excess may queue. Without nodelay, excess requests are delayed until they fit the rate — the client waits. With nodelay, they pass immediately, as long as they fit within the burst. For human browsing, nodelay is usually right, because one page fires several requests at once and delaying them makes the site slow for no reason.

Frequently asked questions

Which key should I limit on?
The default is the client address in binary form, which uses less memory. Behind a CDN or load balancer that address belongs to the proxy and the limit would become global — there you need the forwarded header variable, and only after trusting it through real proxy configuration.
What happens when the limit is exceeded?
nginx answers 503 by default. It is worth switching to 429, the correct code for too many requests, using the limit status directive — and, where possible, adding a Retry-After so the client knows when to come back.
Does this protect against a denial-of-service attack?
Against abuse from a single client, it helps a great deal. Against a distributed attack, no: thousands of different origins stay under the individual limit while the combined effect gets through. For that the instrument is the network layer, ahead of the application server.

Related Tools