QA
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→

More System Design & Architecture Interview Questions

Beginner LevelSystem Design & Architecture

Explain the CAP Theorem and PACELC Theorem with real-world database examples.

Beginner LevelSystem Design & Architecture

What is Vertical Scaling (Scale Up) vs Horizontal Scaling (Scale Out)?

Beginner LevelSystem Design & Architecture

How do Load Balancers distribute traffic (Round Robin, Least Connections, IP Hash)?