Intermediate LevelSystem Design & Architecture
How do you design a Distributed Rate Limiter using Redis Lua Scripts?
β Interview Prompt: Explain Distributed Rate Limiting, Sliding Window Log vs Counter, atomic Redis Lua scripts, and API Gateway integration.
Enforcing rate limits across a cluster of API Gateway nodes requires a shared distributed cache (Redis):
Atomic Redis Lua Execution:
Checking and incrementing request counters must happen atomically to prevent race conditions across gateway replicas. Executing a Redis Lua Script guarantees that counter evaluation runs atomically on the Redis server!
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])
redis.call('ZREMRANGEBYSCORE', key, 0, now - window)
local current = redis.call('ZCARD', key)
if current < limit then
redis.call('ZADD', key, now, now)
return 1
end
return 0
';π‘Atomic Sliding Window Rate Limiter Lua Script for Redis.
π― Interview Key Takeaway
Use atomic Redis Lua scripts to execute sliding window rate limiting across distributed API Gateway nodes without race conditions.
#System Design#Rate Limiter#Redis Lua#Distributed Systems#Intermediate
Back to all System Design & Architecture Questionsβ