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

More REST APIs & Web Services Interview Questions

Beginner LevelREST APIs & Web Services

What is HTTP Method Idempotency and how do you implement Idempotency Keys for REST APIs?

Beginner LevelREST APIs & Web Services

What are standard HTTP Status Codes (200, 201, 204, 400, 401, 403, 404, 409, 429, 500, 503)?

Beginner LevelREST APIs & Web Services

What are HTTP Verbs (GET, POST, PUT, PATCH, DELETE) and when to use PUT vs PATCH?