/ blog/redis-sliding-window-rate-limiting
blog / redis-sliding-window-rate-limiting / overview.md

Distributed Rate Limiting using Redis Sliding Windows

Fixed-window rate limiting has a fatal flaw. Here is how to implement a precise sliding window using Redis Sorted Sets.

Fixed window rate limiting (e.g. 100 requests per minute) is easy, but vulnerable to bursts. If a user sends 100 requests at 12:00:59 and 100 requests at 12:01:01, they processed 200 requests in 2 seconds.

Sliding Window with Redis ZSETs: Instead of a simple counter, store each request's timestamp in a Redis Sorted Set (ZSET).

  1. Remove all elements from the set older than 1 minute (ZREMRANGEBYSCORE).
  2. Count the remaining elements in the set (ZCARD).
  3. If the count exceeds the limit, reject the request.
  4. If not, add the current timestamp to the set (ZADD).

This ensures that at any given rolling 60-second window, the limit is strictly enforced. It is O(N) where N is the number of requests in the window, which is highly performant in Redis.

Tags

backendredisarchitecture
0
0