Sliding Window Log in Redis
You'll learn how to implement precise request-level rate limiting by storing and querying individual request timestamps in Redis sorted sets.
The Core Idea
A sliding window log maintains the exact timestamp of every request within the time window. Unlike approximate algorithms (like token bucket or fixed window counters), this approach provides perfect accuracy by storing each request as a scored entry in a Redis sorted set, where the score is the timestamp.
When a new request arrives, you:
- Remove all entries older than the window (e.g.,
current_time - 60 seconds) - Count remaining entries
- If count < limit, allow the request and add its timestamp
- Otherwise, reject it
Why Sorted Sets?
Redis sorted sets (ZSET) are perfect for this because they:
- Store members with scores (timestamps)
- Support efficient range operations (
ZREMRANGEBYSCOREto prune old entries) - Provide
ZCOUNTto count entries in a time range - Guarantee atomic operations when wrapped in Lua scripts
Precision vs Cost
This method is perfectly accurate—every request is tracked individually, and the window truly "slides" with each new request. However, the trade-off is memory: you store one entry per request within the window. For a 1000 req/min limit, you might store ~1000 timestamps per user. For millions of users, this becomes expensive.
When to Use It
Choose sliding window log when you need:
- Maximum accuracy in rate enforcement
- Compliance with strict SLAs
- Predictable rate limiting without edge case bursts
Key Takeaway: Sliding window log in Redis uses sorted sets to store individual request timestamps, providing perfectly accurate rate limiting at the cost of higher memory usage—ideal when precision matters more than scale efficiency.