Rate Limiting with Lua
Implement sliding window rate limiters atomically in Redis Lua.
Rate Limiting with Lua is a free Lua Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Redis for Rate Limiting?
Redis provides atomic operations, in-memory speed, and shared state across multiple application servers — making it ideal for distributed rate limiting.
Simple Fixed Window Counter
Count requests per time window using INCR and EXPIRE.
EVAL "
local key = KEYS[1]
local limit = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local count = redis.call('INCR', key)
if count == 1 then
redis.call('EXPIRE', key, window)
end
if count > limit then
return 0 -- rejected
end
return 1 -- allowed
" 1 rate:user:123 100 60Sliding Window with Sorted Sets
A more accurate rate limiter uses a sorted set keyed by timestamp. Remove old entries, add the current request, and count the set size.
EVAL "
local key = KEYS[1]
local now = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local limit = tonumber(ARGV[3])
redis.call('ZREMRANGEBYSCORE', key, 0, now - window * 1000)
redis.call('ZADD', key, now, now .. math.random())
redis.call('EXPIRE', key, window)
local count = redis.call('ZCARD', key)
if count > limit then return 0 end
return 1
" 1 slidingRate:user:123 1706000000000 60 100Token Bucket Algorithm
A token bucket allows bursting while maintaining an average rate. Refill tokens over time; each request consumes one token.
Leaky Bucket Algorithm
The leaky bucket enforces a strict constant rate. Requests are queued (the bucket) and processed at a fixed drain rate. Overflow is rejected.
Per-User and Per-IP Limits
Key the rate limiter by user ID, API key, or IP address: rate:{userId}, rate:{ip}, rate:{apiKey}.
Tiered Rate Limits
Apply different limits based on user tier (free vs. pro). Check the user's tier before choosing which limit to enforce.
EVAL "
local tier = redis.call('HGET', 'user:tier', ARGV[1])
local limit = tier == 'pro' and 10000 or 1000
-- ... rest of rate limit check
" 0 "userId123"Returning Headers
Return the remaining request count and reset time from the script so the application can set X-RateLimit headers in the HTTP response.
return {allowed, limit - count, resetTime}Distributed Atomic Guarantee
Since the entire rate limit check is in a single EVAL script, it is atomic across all application server instances sharing the Redis cluster.
Redis Cluster Note
In Redis Cluster mode, all KEYS used in a script must hash to the same slot. Use hash tags: rate:{user123}:requests to force co-location.
Monitoring Rate Limits
Log rejected requests with user/IP info. Set up alerts when rejection rates spike (indicates attack or misconfiguration).
Rate Limiting Question
Why is a Redis Lua script better for rate limiting than application-side counters?
Recap: Rate Limiting with Lua
Implement rate limiters in Redis Lua using INCR+EXPIRE (fixed window) or sorted sets (sliding window). The atomic script guarantees correctness across distributed app servers. Return remaining quota for HTTP headers.
Frequently asked questions
Is the “Rate Limiting with Lua” lesson free?
Yes — the full text of “Rate Limiting with Lua” is free to read here on the web, and the Lua Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Lua Academy course, upgrade to CoddyKit PRO.
What will I learn in “Rate Limiting with Lua”?
Implement sliding window rate limiters atomically in Redis Lua. You practise Lua Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Lua Academy?
No prior experience is required. Lua Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Rate Limiting with Lua” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Lua Academy lesson?
Yes. Every Lua Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- EVAL and Redis Lua Environment
- Atomic Operations and Transactions
- Rate Limiting with Lua
- SCRIPT LOAD and EVALSHA