Course contentsShow
← System Design
Lesson 1797 of 1,91943. Real-World System: Rate Limiter ServiceFree lesson

Sliding Window Counter with Redis

Build memory-efficient sliding window counters by combining current and previous window data with weighted calculation.

Sliding Window Counter with Redis

You'll learn how to build a memory-efficient sliding window rate limiter by blending data from two time windows.

The Core Idea

The Sliding Window Log stores every individual request timestamp—accurate but memory-hungry. The Sliding Window Counter achieves similar accuracy with far less memory by keeping only two counters: one for the current window and one for the previous window. When a request arrives mid-window, you calculate a weighted overlap between windows to estimate how many requests fall within the sliding time range.

How It Works

Imagine your rate limit is 100 requests per minute. At 10:00:30 (halfway through the current minute):

  • Previous window (9:59–10:00): 80 requests
  • Current window (10:00–10:01): 20 requests so far

To decide if a new request is allowed, calculate:

overlap_weight = (60 - 30) / 60 = 0.5  # 30 seconds into the minute
estimated_count = (80 × 0.5) + 20 = 60 requests

If 60 < 100, allow the request and increment the current window counter.

Redis Implementation Pattern

Use two keys with expiration:

  • rate:user123:current → counter for this minute (expires in 1 minute)
  • rate:user123:previous → previous minute's count

When the minute rolls over, the "current" becomes "previous" automatically through key renaming or by reading both and calculating the overlap.

This approach uses O(1) memory per user instead of O(N) for every request, while maintaining ~99% accuracy of the full sliding window log.

Key Takeaway:
Sliding Window Counter combines current and previous window counts with time-weighted calculation to achieve near-log accuracy at fixed memory cost—ideal for high-scale rate limiting in Redis.