Learn Labs
Application Patterns

Rate Limiting

Fixed window, sliding log, sliding counter, and token bucket

Rate limiting protects APIs from abuse and from accidental overload: "100 requests per minute per API key." Redis is the standard place to keep the counters, because every app server must see the same count and the updates must be atomic.

labs/rate_limiter.py implements three algorithms with the same limit, 10 requests per 10 seconds, and fires 15 requests:

docker compose -f compose_prod.yaml run --rm labs python rate_limiter.py

fixed window  ✓✓✓✓✓✓✓✓✓✓✗✗✗✗✗   (10 allowed)
sliding log   ✓✓✓✓✓✓✓✓✓✓✗✗✗✗✗   (10 allowed)
token bucket  ✓✓✓✓✓✓✓✓✓✓✗✗✗✗✗   (10 allowed)

They agree on a burst. They differ at the edges and in cost.

Fixed window

One counter per user per time window. INCR it; if it's above the limit, reject.

def fixed_window(user: str) -> bool:
  key = f"rate:fixed:{user}:{int(time.time() // WINDOW)}"
  pipe = r.pipeline()
  pipe.incr(key)
  pipe.expire(key, WINDOW)
  count, _ = pipe.execute()
  return count <= LIMIT
  • Cost: one small key per user per window, O(1).
  • Flaw: the window boundary. 10 requests at 9.9s and 10 more at 10.1s are both allowed: 20 requests in 0.2 seconds, double the intended rate.
window boundary (10 s)requests1010fixed windowwindow 1: 10, allowedwindow 2: 10, allowedsliding 10 s20 within 10 s: 10 refusedtime (s) →

The pipeline sends INCR and EXPIRE in one round trip. redis-py's pipeline() also wraps them in MULTI/EXEC by default, so they're applied together. Sent as two separate commands, a client crash between them could leave a counter that never expires. Re-setting the TTL on every request is harmless here, because the window number is in the key name.

Sliding log

Record the timestamp of every request in a sorted set; count the ones inside the window.

def sliding_log(user: str) -> bool:
  key = f"rate:sliding:{user}"
  now = time.time()
  pipe = r.pipeline()
  pipe.zremrangebyscore(key, 0, now - WINDOW)   # drop requests older than the window
  pipe.zadd(key, {str(uuid.uuid4()): now})       # record this one
  pipe.zcard(key)                                # count what's left
  pipe.expire(key, WINDOW)
  _, _, count, _ = pipe.execute()
  return count <= LIMIT
  • Cost: one sorted-set entry per request in the window. Fine for 100 per minute; heavy for 10,000 per second.
  • Accuracy: exact. No boundary problem.
  • Note that rejected requests are still recorded. Some implementations remove the entry on rejection so a client that keeps retrying can recover; others keep it, which punishes hammering.

Sliding window counter

A cheap approximation of the sliding log: keep fixed-window counters, and weight the previous window by how much of it overlaps the sliding window.

# 40% of the way into the current window:
estimate = current_window_count + previous_window_count * (1 - 0.40)

Two small keys per user, O(1), and within a few percent of exact. This is what many API gateways use.

Token bucket

Each user has a bucket that holds up to capacity tokens and refills at rate per second. A request takes a token; no token, no request. It allows short bursts up to the capacity while enforcing a long-run average rate.

The refill-and-take must be atomic, or two concurrent requests could both see one token left and both proceed. So it runs as a Lua script on the server:

local state  = redis.call('HMGET', key, 'tokens', 'ts')
local tokens = tonumber(state[1]) or capacity
local ts     = tonumber(state[2]) or now

tokens = math.min(capacity, tokens + (now - ts) * rate)
local allowed = 0
if tokens >= 1 then
tokens = tokens - 1
allowed = 1
end
redis.call('HSET', key, 'tokens', tokens, 'ts', now)
redis.call('EXPIRE', key, math.ceil(capacity / rate) * 2)
return allowed

Lua scripts run atomically: no other command executes while the script does. More in Lua Scripting.

Comparison

AlgorithmMemory per userAccuracyBursts
Fixed window1 counterUp to 2x at edgesUnbounded at the edge
Sliding log1 entry per requestExactNone beyond the limit
Sliding counter2 counters~ExactSmoothed
Token bucket1 small hashExact averageUp to capacity, by design

Lab

  1. Run rate_limiter.py.
  2. Show the fixed-window edge problem: modify the script to send 10 requests just before a window boundary and 10 just after, and count how many are allowed within one second.
  3. Change the token bucket to capacity 20, rate 1/s. Fire 25 requests, wait 5 seconds, fire 10 more. How many of each batch pass?
  4. Implement the sliding window counter.

On this page