Intermediate LevelREST APIs & Web Services
How do you implement a Sliding Window Log Rate Limiter using Redis sorted sets (ZSET)?
❓ Interview Prompt: Explain Sliding Window Log rate limiting algorithm, Redis `ZSET`, `ZREMRANGEBYSCORE`, `ZADD`, `ZCARD`, and atomic Lua script execution.
Implementing exact Sliding Window Log rate limiting using Redis Sorted Sets ('ZSET'):
Execution Steps (Redis Lua Script):
1
Use client IP or user ID as Redis ZSET key: 'ratelimit:usr_42'.
2
Clean Stale Logs: Remove log entries older than window threshold: 'ZREMRANGEBYSCORE key 0 (now - windowMs)'.
3
Count Active Requests: Get current set cardinality: 'ZCARD key'.
4
If count >= limit $\rightarrow$ Reject request ('429'). Otherwise $\rightarrow$ Add current request timestamp: 'ZADD key now now' and grant access!
Code Implementation Example
typescript
const slidingWindowLua = '
local key = KEYS[1]
local now = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local limit = tonumber(ARGV[3])
local clearBefore = now - window
redis.call('ZREMRANGEBYSCORE', key, 0, clearBefore)
local currentRequests = redis.call('ZCARD', key)
if currentRequests >= limit then
return 0
else
redis.call('ZADD', key, now, now)
return 1
end
';💡Redis Lua script executing sliding window log rate limiting.
🎯 Interview Key Takeaway
Use Redis ZSET sorted sets to execute accurate Sliding Window Log rate limiting across distributed API nodes.
#Sliding Window#Redis ZSET#Rate Limiting#Intermediate
Back to all REST APIs & Web Services Questions→