← Lessons

quiz vs the machine

Platinum1820

Databases

Redis as a Rate Limiter

Counting requests per window to throttle traffic.

5 min read · advanced · beat Platinum to climb

Why Redis

Rate limiting needs a fast, shared counter that many app servers can update atomically. Redis fits perfectly: in memory speed, atomic increments, and built in expiry.

Fixed Window Counter

The simplest scheme uses a key per user per time window:

  • Build a key like user 42 colon minute 1530.
  • INCR it on each request and read the count.
  • Set an expiry equal to the window so the key cleans itself up.
  • Reject the request when the count passes the limit.

This is cheap but has a boundary burst flaw: a client can send the full limit at the end of one window and again at the start of the next, briefly doubling the rate.

Sliding Window and Token Bucket

Smoother algorithms fix the boundary problem:

  • A sliding window stores timestamps in a sorted set, trims old ones with ZREMRANGEBYSCORE, and counts what remains.
  • A token bucket stores tokens and a last refill time, refilling over time and spending one per request.

Both involve several dependent operations, so they are usually implemented as a Lua script to stay atomic and avoid races between read and update.

Key idea

Redis rate limiters use atomic counters with expiry per window; fixed windows are simple but burst at boundaries, so sliding window or token bucket in Lua gives smoother limits.

Check yourself

Answer to earn rating on the learn ladder.

1. What flaw does a fixed window counter have?

2. Why implement a sliding window or token bucket limiter as a Lua script?

3. Why set an expiry on a fixed window counter key?