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. This is lesson 3 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, and your progress syncs across the web and the CoddyKit app. The Lua Academy course includes 4 lessons in total.
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.
Learn Lua with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 40
- Lessons
- 159
Frequently Asked Questions
Is the “Rate Limiting with Lua” lesson free?
Yes — any 3 lessons of the Lua Academy learning path, including “Rate Limiting with Lua”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Lua Academy course includes 4 lessons in total.
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, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.
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