Sliding Log: Exact Timestamps for Precise Counting
When You Need Perfect Accuracy
Sliding counters approximate. What if you need exact counts for billing, compliance, or security audits? Store every individual request timestamp. This is the sliding log approach: instead of counting, maintain a complete record and count matching timestamps on each request. The trade-off is significantly higher memory usage for guaranteed precision.
How Sliding Log Works
For each user, maintain a list of timestamps for all requests. When a new request arrives: (1) remove timestamps older than your window (e.g., 60 seconds), (2) count remaining, (3) if under limit, add current timestamp and allow, (4) if at or over limit, reject with 429. Use Redis sorted sets with timestamps as scores: ZREMRANGEBYSCORE key 0 (now - window), ZCARD key, ZADD key now now.
Memory Implications
If a user is allowed 1,000 requests/minute and each timestamp is 8 bytes, that is 8 KB per user at peak. With 100,000 active users, that is 800 MB for rate limiting state. Compare to sliding counter at 16 bytes per user. Sliding log uses 500x more memory. This is why sliding log is reserved for high value use cases where accuracy justifies the cost.
Processing Cost
Each request requires O(k) time where k is requests in the window. With Redis sorted sets, cleanup is O(log n + m) where m is entries removed, counting is O(log n). Still fast but more expensive than O(1) counter increment. For very high rate limits (10,000+/sec), this overhead is significant.
When to Use Sliding Log
Use sliding log when: exact counts are required for billing or compliance, rate limits are low enough that memory is acceptable, audit trail of individual requests is valuable, or you need to answer questions like "show me all requests in the last hour." For most API rate limiting where approximate fairness is the goal, sliding window counter is more practical.