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.
Previous
What is RedisBloom (Bloom Filter in Redis)?
Next
How does distributed locking work in Redis?
More Redis Questions
View all →- Intermediate What is Redis Cluster and how does it shard data?
- Intermediate What is the difference between Redis Sentinel and Redis Cluster?
- Intermediate How do MULTI and EXEC work in Redis transactions?
- Intermediate What is WATCH and optimistic locking in Redis?
- Intermediate What is Lua scripting in Redis and when should you use it?