🔴 Redis Intermediate

How do you implement rate limiting in Redis?

Answer

A simple Redis rate limiter uses INCR and EXPIRE. For each request, INCR user:$id:requests:$minute atomically increments the count. On the first request of each minute, set EXPIRE user:$id:requests:$minute 60 to reset automatically. If the count exceeds the limit, reject the request. A more robust approach uses a Lua script to make the increment + TTL check atomic and avoid the race condition where a key might be incremented but EXPIRE never called. The Sliding Window Log pattern (using a Sorted Set with timestamps as scores and ZRANGEBYSCORE to count recent requests within the window) is more accurate but uses more memory. The Token Bucket / Leaky Bucket algorithms can also be implemented via Lua scripts for smooth rate control.