Per-Client API Rate Limiting in OpenResty with Lua

Rate limiting protects an API from scrapers, credential-stuffing scripts and runaway clients, and keeps one heavy user from degrading everyone else's latency. Doing it in the reverse proxy means rejected requests never reach your application servers.
Nginx's built-in limit_req covers simple per-IP limits well. When you need limits per API key, different limits per plan, or logic that looks at the request, OpenResty (Nginx with an embedded LuaJIT runtime) lets you write that logic in Lua. This guide builds a per-client limiter that is correct across worker processes, explains the two mistakes most examples make (non-atomic counters, and limiting the load balancer's IP instead of the client's), and is clear about what a proxy-level limiter can and can't defend against.
The Core Problem: Uncontrolled API Access
Imagine your meticulously crafted API endpoints, designed to serve legitimate users efficiently. Without robust rate limiting, these endpoints become vulnerable. Attackers can flood your servers with requests, attempting to:
- Exhaust Resources: Overwhelm your database, CPU, or memory, making your service unavailable.
- Scrape Data: Rapidly extract large volumes of data, potentially violating terms of service or intellectual property.
- Brute-Force Credentials: Repeatedly try combinations of usernames and passwords, leading to account compromises.
- Overload expensive endpoints: A modest number of requests to a search or report endpoint can saturate the database.
A limiter on your own server handles application-layer abuse. It doesn't stop a volumetric DDoS attack. If the attack saturates your network link or the server's connection capacity, the limiter never gets a chance to run. That protection comes from upstream: a CDN or DDoS-mitigation service, or your cloud provider's network-level protection.
If you only need per-IP limits, start with built-in limit_req, which needs no Lua:
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
location /api/ {
limit_req zone=api burst=20 nodelay;
limit_req_status 429;
proxy_pass http://app;
}Use Lua when the limit depends on something limit_req can't express easily, such as an API key's plan looked up at runtime.
Why OpenResty
OpenResty runs Lua code inside Nginx's request phases. For rate limiting, two features matter:
lua_shared_dict: a key-value store in shared memory, visible to all worker processes on the server, with atomic operations likeincr.- Cosocket APIs: non-blocking network calls (for example to Redis) that don't stall the worker while they wait.
Step-by-Step: Implementing Dynamic Rate Limiting
The limiter below uses a fixed window: each client gets N requests per window (for example, per minute), and the counter resets when the window ends.
Step 1: Install OpenResty
Follow the official installation instructions for your distribution. They add OpenResty's package repository with a signed keyring (apt-key is deprecated on current Debian and Ubuntu releases). For containers, the openresty/openresty Docker images are the quickest option.
Step 2: Configure Nginx Shared Memory Zone
In your nginx.conf (or an included file like /etc/openresty/nginx.conf), declare a shared memory dictionary. This is crucial for Lua scripts to store and retrieve rate limiting data across Nginx worker processes.
# /etc/openresty/nginx.conf or a site-specific config
http {
lua_shared_dict rate_limits 10m; # shared across all workers on this server
# If Nginx sits behind a load balancer or CDN, restore the real client IP.
# Only trust X-Forwarded-For from addresses you control.
set_real_ip_from 10.0.0.0/8;
real_ip_header X-Forwarded-For;
real_ip_recursive on;
# ... other http settings ...
server {
listen 80;
server_name api.example.com;
# ... other server settings ...
# Our API endpoint
location /api/v1/data {
# This is where our Lua script will be called
access_by_lua_file /etc/openresty/lua/rate_limit.lua;
proxy_pass http://your_upstream_application;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
}Step 3: Write the Lua Rate Limiting Logic
Create /etc/openresty/lua/rate_limit.lua:
-- /etc/openresty/lua/rate_limit.lua
local limits = ngx.shared.rate_limits
local WINDOW = 60 -- seconds
local LIMIT_ANON = 30 -- requests per window without an API key
local LIMIT_KEYED = 600 -- requests per window with an API key
-- Identify the client: API key if present, otherwise the client IP.
-- In production, validate the key before trusting it as an identity.
local api_key = ngx.var.http_x_api_key
local client, limit
if api_key and api_key ~= "" then
client, limit = "key:" .. api_key, LIMIT_KEYED
else
client, limit = "ip:" .. ngx.var.remote_addr, LIMIT_ANON
end
-- One counter per client per window, e.g. "ip:203.0.113.7:29012345"
local now = ngx.time()
local window_id = math.floor(now / WINDOW)
local key = client .. ":" .. window_id
-- incr() is atomic across workers. The 4th argument sets a TTL when the key
-- is created, so expired windows clean themselves up.
local count, err = limits:incr(key, 1, 0, WINDOW)
if not count then
-- Fail open: if the dict is full or broken, don't take the API down.
ngx.log(ngx.ERR, "rate limiter error: ", err)
return
end
local remaining = math.max(limit - count, 0)
ngx.header["X-RateLimit-Limit"] = limit
ngx.header["X-RateLimit-Remaining"] = remaining
if count > limit then
local reset_in = (window_id + 1) * WINDOW - now
ngx.header["Retry-After"] = reset_in
ngx.log(ngx.WARN, "rate limited ", client)
return ngx.exit(ngx.HTTP_TOO_MANY_REQUESTS)
endThree details matter here:
- Atomic counting: many examples read a value with
get(), change it in Lua, and write it back withset(). Two workers handling the same client at the same time can both read the old value, and the limit leaks.incr()with an initial value does the read and write as one operation. - Whole-second
Retry-After: the header must be an integer number of seconds (or an HTTP date).ngx.time()returns whole seconds, which keeps it valid. - Failing open: if the shared dict runs out of memory, the code logs and lets the request through, rather than rejecting all traffic.
A fixed window allows up to twice the limit across a window boundary (a burst at the end of one window, then another at the start of the next). If that matters, use the lua-resty-limit-traffic library that ships with OpenResty. Its resty.limit.req module implements a leaky bucket, the same algorithm as limit_req, with Lua-level control over keys.
Step 4: Integrate Lua into Nginx Location Block
The access_by_lua_file directive from Step 2 runs the script in Nginx's access phase for every request to that location. If the script calls ngx.exit(429), Nginx sends the response immediately. Otherwise the request continues to proxy_pass.
Step 5: Test Your Configuration
After saving nginx.conf and rate_limit.lua, check your Nginx configuration for syntax errors and then reload it:
sudo openresty -t # Test configuration
sudo openresty -s reload # Reload NginxSend more requests than the anonymous limit within a minute and print only the status codes:
for i in $(seq 1 40); do
curl -s -o /dev/null -w "%{http_code}\n" http://api.example.com/api/v1/data
done | sort | uniq -cYou should see 30 responses with 200 and 10 with 429. Repeat with -H "X-API-Key: test" to confirm the higher limit applies.
Advanced Considerations and Best Practices
Choose the Right Client Identity
Per-IP limits are unfair to many users sharing one address (offices, mobile carrier NAT) and easy to get around with many addresses. Where you can, limit authenticated clients by API key or user ID, and keep a stricter per-IP limit only for anonymous traffic and login endpoints. For login, also limit per username, since credential-stuffing tools spread attempts across many IPs.
💡 Tip: Return
X-RateLimit-Limit,X-RateLimit-RemainingandRetry-Afteron every response, as the script above does. Well-behaved clients use them to back off before hitting the limit, which reduces 429s for everyone.
Distributed Rate Limiting (Cross-Node)
lua_shared_dict is per server. Behind a load balancer with N servers, a client can get up to N times the limit. Often that's acceptable: divide the limit by N, or use sticky routing. If you need one global count, keep counters in Redis with lua-resty-redis (INCR plus EXPIRE, or a small Lua script run with EVAL so both happen atomically). Use a connection pool (set_keepalive) and decide whether to fail open or closed when Redis is unreachable.
Logging and Monitoring
Count 429 responses by client and endpoint in your access logs or metrics (for example with the nginx-lua-prometheus library). A sudden rise points to abuse. A steady trickle from known customers usually means the limit is too low for legitimate use.
Summary
- Use
limit_reqfor simple per-IP limits, and OpenResty with Lua when limits depend on API keys, plans or request details. - Count atomically with
shared_dict:incr(), never with separateget()andset()calls. - Limit the real client: configure
set_real_ip_frombehind load balancers, and prefer API keys or user IDs over IPs where possible. - Don't rely on it for DDoS protection. Volumetric attacks have to be absorbed upstream by a CDN or your provider's network protection.
