Redis for Rate Limiting
What you'll learn: How to implement rate limiters using Redis counters, sliding windows, and atomic operations to control request rates at scale.
Why Redis for Rate Limiting?
Rate limiting protects your APIs from abuse by restricting how many requests a user can make in a time window (e.g., 100 requests per minute). Redis excels here because it's in-memory (fast), supports atomic operations (prevents race conditions), and handles expiration automatically (TTL cleans up old data).
Counter-Based Approach
The simplest method uses a counter key per user:
INCR user:123:requests
EXPIRE user:123:requests 60
Each request increments the counter. If it exceeds your limit, reject the request. The key expires after 60 seconds. Problem: this resets abruptly at the window boundary (all counters reset at once).
Sliding Window Log
Store timestamps of each request in a sorted set:
ZADD user:123:requests {currentTimestamp} {requestId}
ZREMRANGEBYSCORE user:123:requests 0 {timestamp-60seconds}
ZCARD user:123:requests
This removes old requests beyond the window and counts remaining ones. More accurate but uses more memory per user.
Sliding Window Counter (Hybrid)
Combine current and previous window counts with weighted averaging. Uses two counters and calculates: (previousCount * overlap%) + currentCount. Balances accuracy and efficiency.
Why Atomic Operations Matter
Redis's single-threaded model guarantees that commands like INCR, ZADD, and ZREMRANGEBYSCORE execute atomically. Multiple servers can safely rate-limit the same user without race conditions or double-counting.
Key Takeaway: Redis provides fast, atomic operations with automatic expiration, making it ideal for rate limiting through simple counters, precise sliding window logs, or hybrid approaches that balance accuracy with memory efficiency.