Menu

Tutorials

Nginx Rate Limiting and Caching for REST APIs: Step-by-Step Guide

Table of contents (6 sections)

Public REST APIs face bursty client retries, misconfigured cron jobs, aggressive scrapers, and sudden traffic spikes every day. Pushing every unthrottled or repetitive read request straight through to your Node.js, Go, or Python backend wastes CPU cycles, exhausts database connection pools, and degrades latency for legitimate users.

Putting Nginx in front of your application gives you two high-leverage defenses before a single byte hits application memory: leaky-bucket rate limiting and short-lived proxy microcaching. In this tutorial, you will configure limit_req_zone with proper HTTP 429 status codes, cache read-heavy endpoints safely using proxy_cache_path, preserve real client IP addresses behind CDNs, and verify every rule with nginx -t and curl.

How Nginx Leaky-Bucket Rate Limiting Works Under Traffic Spikes

Unlike naive fixed-window counters that allow double traffic across minute boundaries, Nginx enforces request pacing using the leaky bucket algorithm via the ngx_http_limit_req_module documentation. Imagine a bucket with a fixed capacity (burst) that drains at a steady constant rate (rate). Incoming requests pour water into the bucket; if the bucket overflows, excess requests are rejected immediately.

This distinction matters in real APIs. A single-page dashboard loading on a developer’s browser often fires five or six concurrent API calls within 50 milliseconds, then stays quiet for ten seconds. A strict 10r/s limit without a burst queue would reject legitimate parallel requests spaced less than 100 milliseconds apart, even though the client’s average rate is well below 10 requests per second.

Directive or ParameterScopeOperational Effect
limit_req_zonehttp blockAllocates shared memory zone and defines key + steady drain rate
limit_req … burst=Nhttp, server, locationQueues up to N excess requests above the steady rate
nodelaylimit_req optionForwards queued burst requests immediately while still consuming bucket slots
delay=Mlimit_req optionForwards first M burst requests immediately and throttles remaining ones
limit_req_status 429http, server, locationReturns HTTP 429 Too Many Requests instead of default 503

Configuring limit_req_zone, burst, nodelay, and Custom 429 Status

Rate limiting zones live inside the http context (typically /etc/nginx/nginx.conf or a dedicated file inside /etc/nginx/conf.d/rate-limits.conf), while the enforcement directives belong inside your server or location blocks. Always size your shared memory zone sensibly: 10 megabytes holds roughly 160,000 IPv4 state entries, which is plenty for most API gateways.

Notice that Nginx defaults to returning HTTP 503 Service Temporarily Unavailable when rejecting rate-limited traffic. For REST APIs, explicitly set limit_req_status 429; so API clients and SDKs recognize a throttling response and apply exponential backoff rather than treating the failure as an upstream outage.

nginx# /etc/nginx/conf.d/api-rate-limit.conf (included inside http block)
limit_req_zone $binary_remote_addr zone=api_ip_limit:10m rate=10r/s;
limit_req_zone $http_authorization zone=api_token_limit:10m rate=30r/s;
 
# Cache storage zone for proxy microcaching
proxy_cache_path /var/cache/nginx/api levels=1:2 keys_zone=api_cache:20m max_size=512m inactive=10m use_temp_path=off;

Defining two separate zones gives you layered protection. Unauthenticated endpoints or login routes can enforce api_ip_limit keyed by $binary_remote_addr, while authenticated API routes can also key off an API key header or bearer token so corporate offices sharing a single NAT IP do not throttle one another unfairly.

If you are dealing with active volumetric abuse or bot floods on an existing deployment, pair these Nginx rate limits with the mitigation steps in Step-by-Step Guide: How to Identify and Fix a DDOS Attack on Your WordPress Site.

Adding Proxy Microcaching for Read-Heavy API Endpoints

Even a short cache TTL of 5 to 30 seconds (often called microcaching) transforms backend resilience for read-heavy endpoints such as public catalog listings, feature flags, health summaries, or reference data. Using the directives in the ngx_http_proxy_module documentation, Nginx can absorb thousands of identical GET requests per second from RAM and page cache while forwarding only a single cache-refresh request to your backend.

Ethernet network switch routing HTTP requests to upstream servers
Network switching layer sitting ahead of Nginx reverse proxy and upstream API instances. Image: Raysonho @ Open Grid Scheduler (CC0), via Wikimedia Commons.

Two directives make API microcaching safe in production: proxy_cache_lock on; prevents cache stampedes by allowing only one request through to the upstream when a cache key expires, and proxy_cache_use_stale serves slightly stale cached data if your upstream briefly times out or restarts during a deploy.

nginx# /etc/nginx/sites-available/api.example.com.conf
server {
    listen 443 ssl http2;
    server_name api.example.com;
 
    # Return standard 429 Too Many Requests when rate limit trips
    limit_req_status 429;
 
    # Strict rate limit for authentication endpoints
    location = /v1/auth/token {
        limit_req zone=api_ip_limit burst=5 nodelay;
        proxy_pass http://127.0.0.1:4000;
        include proxy_params;
    }
 
    # Microcached public read endpoints
    location /v1/public/ {
        limit_req zone=api_ip_limit burst=20 delay=10;
 
        proxy_cache api_cache;
        proxy_cache_key "$scheme$request_method$host$request_uri";
        proxy_cache_methods GET HEAD;
        proxy_cache_valid 200 15s;
        proxy_cache_valid 404 5s;
        proxy_cache_lock on;
        proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
        add_header X-Cache-Status $upstream_cache_status always;
 
        proxy_pass http://127.0.0.1:4000;
        include proxy_params;
    }
 
    # Uncached authenticated API routes (bypass cache when Authorization header is present)
    location /v1/ {
        limit_req zone=api_token_limit burst=40 nodelay;
        proxy_no_cache $http_authorization;
        proxy_cache_bypass $http_authorization;
        proxy_pass http://127.0.0.1:4000;
        include proxy_params;
    }
}

Avoiding Accidental User Data Leaks in Proxy Cache

Never enable proxy_cache globally across endpoints that return per-user responses unless the cache key explicitly isolates user identity or cookies are stripped. Keeping cached routes scoped to an explicit /v1/public/ location and adding proxy_no_cache $http_authorization; on private routes ensures private payloads are never written to shared cache storage.

If you package Nginx inside containers alongside a frontend build, check our guide on Ultra-Lightweight Multi-Stage Dockerfile for React and Nginx: Drop from 1GB to 25MB to keep your container footprint minimal.

Forwarding Real Client IPs Safely Behind CDNs and Load Balancers

A classic rate-limiting mistake occurs when Nginx sits behind Cloudflare, an AWS Application Load Balancer, or a Kubernetes ingress controller. Without restoring the real client IP, $binary_remote_addr records the proxy or CDN edge IP rather than the caller’s IP. As a result, one noisy user can trigger the rate limit for every user sharing that edge node.

To fix this securely, configure Nginx’s ngx_http_realip_module so it only trusts X-Forwarded-For or CF-Connecting-IP from your known load balancer or CDN CIDR ranges, never from arbitrary internet clients who can spoof headers.

nginx# Trust only private load balancer subnet when extracting client IP
set_real_ip_from 10.0.0.0/8;
real_ip_header X-Forwarded-For;
real_ip_recursive on;

Testing Nginx Configurations and Verifying Headers with curl

Before reloading Nginx, always test syntax and file paths with nginx -t, confirm your cache directory exists with writable permissions for the www-data or nginx worker user, and inspect live HTTP responses with curl.

bash# Create cache directory and validate configuration syntax
sudo mkdir -p /var/cache/nginx/api
sudo chown -R www-data:www-data /var/cache/nginx/api
sudo nginx -t
sudo systemctl reload nginx
 
# Verify cache MISS followed by HIT
curl -sI https://api.example.com/v1/public/status | grep -i x-cache-status
curl -sI https://api.example.com/v1/public/status | grep -i x-cache-status
 
# Trigger burst and verify 429 responses appear cleanly
for i in $(seq 1 25); do
  curl -s -o /dev/null -w "%{http_code}\n" https://api.example.com/v1/auth/token
done

Always verify X-Cache-Status transitions from MISS to HIT and confirm 429 responses in staging before rolling rate limits out to production clients.

On the first request to /v1/public/status, X-Cache-Status reports MISS; subsequent requests within 15 seconds report HIT without touching your backend process. Meanwhile, rapid bursts against /v1/auth/token drain the burst=5 bucket and return clean 429 status codes, protecting your upstream API under load.

Featured image credit: ALMA (ESO/NAOJ/NRAO)/G. Filippi (CC BY 4.0), via Wikimedia Commons.