rate_limit

The `rate_limit` directive controls the rate of requests processed by an NGINX server by using Redis for backing storage and management.

Syntaxrate_limit key requests=number period=size [burst=number] [rate_limit_prefix=prefix] [rate_limit_pass=upstream];
Defaultnone
Contexthttp, server, location
Arguments1-4

Description

The rate_limit directive enables rate limiting of requests to NGINX based on keys defined through geo, map, or other means. By integrating with a Redis backend, it provides capabilities to manage and enforce limits on a per-key basis, which can represent user IP addresses or any other identifier related to a request. This directive can be configured in different contexts such as HTTP, server, or location blocks and takes between 1 to 4 arguments, enabling flexible configurations for controlling traffic rates.

There are several parameters that can be specified with the rate_limit directive: the key representing the user or identifier for whom the limits apply, the number of allowed requests (requests), the defined period for which those requests are counted (period), and an optional burst parameter (burst) that specifies how many extra requests can be allowed in a short time frame before the limit is enforced. The directive maintains state and tracks usage across these configured keys in Redis, making it a powerful tool for protecting resources from abuse and controlling traffic more effectively.

If a key exceeds its limit, the directive can respond with a specified status code, typically 429 (Too Many Requests), which informs clients of the rate limiting enforcement. This allows improved control of API and web service usage patterns, providing both server protection and improved user experience.

Config Example

location = /limit {
    rate_limit $limit_key requests=15 period=1m burst=20;
    rate_limit_pass redis;
}

Ensure Redis is properly configured and reachable by NGINX to avoid unexpected errors.

Test with real traffic to avoid over-limiting legitimate users, particularly with the burst parameter.

Keys used in rate limiting must be carefully defined to avoid collisions or unintended limits on requests.

← Back to all directives