← Back to Home

🚦 Rate Limiting Algorithms

Fixed window, sliding log, sliding window counter, token bucket and leaky bucket on a live timeline, measured side by side, plus an atomic Redis limiter that survives concurrency.

Every public API has a rate limiter, whether its authors planned one or not. If you don't build one, your database becomes the rate limiter, by falling over. Rate limiting protects services from abusive clients, runaway scripts, retry storms and plain success, and it's how APIs enforce fair use between customers on different plans.

There are five classic algorithms, and they behave differently in ways that matter: one of them lets through twice the limit you configured. This tutorial lets you play with all five on a live timeline, then shows tested implementations in Python and an atomic Redis version that works across many servers.

What a Rate Limiter Decides

A rate limiter answers one question for every request: allow or reject? It's configured with a rule like "10 requests per minute per API key" and keeps a little state per key.

   request (key = API key, user ID, or IP)
        │
        ▼
   ┌─────────────────────┐   allow ──▶ handle the request normally
   │   rate limiter      │
   │   state per key     │   reject ─▶ HTTP 429 Too Many Requests
   └─────────────────────┘             Retry-After: 6

The algorithms differ in three ways:

Question Why it matters
Is the limit exact? Some algorithms can let through more than the limit in a short span
Are bursts allowed? A user opening a dashboard fires 20 requests at once. Should that work?
How much memory per key? With 10 million API keys, 16 bytes versus 1 KB per key is the difference between 160 MB and 10 GB

Try All Five

The playground uses a limit of 5 requests per 5 seconds (or a bucket of 5 refilling at 1 per second). Send single requests, fire bursts, or switch on random traffic, then switch algorithms and compare. Green dots are accepted and red dots rejected. The dashed blue lines are window boundaries, and the shaded area is the sliding window.

Experiments:

  1. Fixed window, at the boundary. Wait until the cursor is just before a dashed line, click Burst ×8, then click it again right after the line. You get about 10 accepted in a second, double the limit.
  2. Token bucket, after a quiet spell. Let it sit for 5 seconds, then burst: 5 accepted at once, then one per second. Bursts are allowed by design.
  3. Sliding window counter vs sliding log. Run random traffic on each. They behave almost identically, but one stores 2 numbers and the other stores every timestamp.

Fixed Window

The simplest algorithm: one counter per key per window, such as per calendar minute.

class FixedWindow:
    """Count requests per calendar window (e.g. per minute). Reset at each boundary."""
    def __init__(self, limit, window):
        self.limit, self.window = limit, window
        self.current, self.count = None, 0

    def allow(self, now):
        w = int(now // self.window)
        if w != self.current:
            self.current, self.count = w, 0
        if self.count < self.limit:
            self.count += 1
            return True
        return False

Strengths: trivial to implement, one integer per key, and in Redis it's just INCR plus EXPIRE.

The flaw is the boundary burst. The limit applies per calendar window, not per any 60 seconds:

          window 0:00–0:59                    window 1:00–1:59
   ├──────────────────────────────────────┼──────────────────────────────────────┤
                                     ●●●●●●●●●●│●●●●●●●●●●
                                    10 at 0:59 │ 10 at 1:00
                                               │
                    20 requests in about 1 second, with a "10 per minute" limit

Sliding Log

Store the timestamp of every accepted request, and count how many are within the last window:

class SlidingLog:
    """Remember the timestamp of every accepted request in the last window. Exact, but O(limit) memory."""
    def __init__(self, limit, window):
        self.limit, self.window = limit, window
        self.log = deque()

    def allow(self, now):
        while self.log and self.log[0] <= now - self.window:
            self.log.popleft()
        if len(self.log) < self.limit:
            self.log.append(now)
            return True
        return False

Strengths: exact. No 60-second span ever contains more than the limit.

Weakness: memory. A limit of 1,000 per hour stores up to 1,000 timestamps per key. In Redis it's usually a sorted set (ZADD, ZREMRANGEBYSCORE, ZCARD), which works well for small limits and gets expensive for large ones.

Sliding Window Counter

A clever approximation of the sliding log, using two counters. Assume the previous window's requests were spread evenly, and count the fraction of it that still overlaps the sliding window:

class SlidingWindowCounter:
    """Two counters (this window, previous window), weighted by overlap. O(1) memory, close to exact."""
    def __init__(self, limit, window):
        self.limit, self.window = limit, window
        self.current, self.count, self.prev_count = None, 0, 0

    def allow(self, now):
        w = int(now // self.window)
        if w != self.current:
            self.prev_count = self.count if self.current == w - 1 else 0
            self.current, self.count = w, 0
        elapsed = (now % self.window) / self.window          # fraction of current window passed
        estimate = self.prev_count * (1 - elapsed) + self.count
        if estimate < self.limit:
            self.count += 1
            return True
        return False
         previous window (8 requests)       current window (3 so far)
   ├────────────────────────────────────┼────────────────────────────────────┤
                       ├──────────── sliding 60 s ───────────┤
                       ▲ 75% of previous still overlaps      ▲ now, 25% into current

   estimate = 8 × 0.75 + 3 = 9   →   allowed if 9 < limit

Strengths: constant memory (two integers), close to exact. Cloudflare reported that, across 400 million requests, this approximation wrongly allowed or limited only 0.003% of them. It's the default choice for many API gateways.

Token Bucket

Picture a bucket holding up to capacity tokens. Tokens drip in at a fixed rate. Each request takes one; no token, no request.

class TokenBucket:
    """Bucket holds up to `capacity` tokens, refilled at `rate` per second. Each request costs one token."""
    def __init__(self, capacity, rate):
        self.capacity, self.rate = capacity, rate
        self.tokens, self.last = capacity, None

    def allow(self, now):
        if self.last is not None:
            self.tokens = min(self.capacity, self.tokens + (now - self.last) * self.rate)
        self.last = now
        if self.tokens >= 1:
            self.tokens -= 1
            return True
        return False

Notice there's no timer. Refilling is computed lazily from the time since the last request, so the state is just two numbers: tokens and last.

Two knobs, two meanings:

That separation is why token buckets are everywhere: AWS API Gateway, Stripe, GitHub, network routers and the Linux kernel's traffic shaping all use them. Real clients are bursty, and a token bucket lets them be, within bounds.

Leaky Bucket

The mirror image: requests pour into a bucket (a queue) that leaks at a constant rate. If the bucket is full, new requests overflow and are rejected.

class LeakyBucket:
    """Queue of size `capacity`, drained at a constant `rate` per second. Smooths output; rejects when full."""
    def __init__(self, capacity, rate):
        self.capacity, self.rate = capacity, rate
        self.level, self.last = 0.0, None

    def allow(self, now):
        if self.last is not None:
            self.level = max(0.0, self.level - (now - self.last) * self.rate)
        self.last = now
        if self.level + 1 <= self.capacity:
            self.level += 1          # the request waits in the queue; it leaves at `rate`
            return True
        return False

The difference from a token bucket is what comes out. A token bucket lets a burst through immediately. A leaky bucket that really queues requests releases them evenly spaced, protecting a fragile backend from bursts entirely. nginx's limit_req is a leaky bucket:

# 10 requests per second per client IP, allow a queue of 20
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;

server {
    location /api/ {
        limit_req zone=api burst=20 nodelay;   # nodelay: serve queued requests at once,
        limit_req_status 429;                  # but still count them against the rate
    }
}

With nodelay, nginx behaves much like a token bucket of size 20. Without it, excess requests are delayed to match the rate exactly.

Measuring the Differences

Theory is nice, but let's measure. These experiments run all five Python classes above with "10 requests per minute" (bucket capacity 10, refilling 10 per minute).

Experiment 1: the boundary burst. 10 requests at t = 59 s, then 10 more at t = 60 s:

Experiment 1: 10 requests at t=59s, then 10 at t=60s (limit 10/minute)
  fixed window               accepted 10 + 10 = 20 in ~1 second
  sliding log                accepted 10 +  0 = 10 in ~1 second
  sliding window counter     accepted 10 +  1 = 11 in ~1 second
  token bucket (10, 1/6 s)   accepted 10 +  0 = 10 in ~1 second
  leaky bucket (10, 1/6 s)   accepted 10 +  0 = 10 in ~1 second

The fixed window doubles the limit. The sliding window counter lets one extra through: just after the boundary, the weighted estimate is 9.998, a hair under 10. That's the price of approximating.

Experiment 2: an hour of bursty random traffic (8,306 requests, arriving in bursts of 1–8). The real question is the worst case: what's the most requests accepted in any 60-second span?

Experiment 2: bursty random traffic for 1 hour; max accepted in ANY 60 s window
  fixed window               total accepted  607 / 8306, worst 60 s window: 20
  sliding log                total accepted  586 / 8306, worst 60 s window: 10
  sliding window counter     total accepted  596 / 8306, worst 60 s window: 12
  token bucket (10, 1/6 s)   total accepted  610 / 8306, worst 60 s window: 19
  leaky bucket (10, 1/6 s)   total accepted  610 / 8306, worst 60 s window: 19

All five accept about 600 per hour, which is the 10-per-minute average. But the worst minute ranges from 10 to 20. The token bucket's 19 isn't a bug. A full bucket (10) plus a minute of refill (10) adds up to capacity + rate × window. If a downstream system truly can't take more than 10 in any minute, use a sliding log, or size the bucket and rate together.

Algorithm Worst case in any window Bursts Memory per key Typical use
Fixed window 2 × limit At boundaries (accidentally) 1 counter Simple quotas, daily limits
Sliding log Exactly the limit Up to the limit One timestamp per request Low limits needing exactness
Sliding window counter About the limit Up to the limit 2 counters API gateways, general purpose
Token bucket capacity + rate × window Up to capacity, by design 2 numbers Public APIs, network shaping
Leaky bucket rate × window (+ queue) Smoothed away 2 numbers (+ queue) Protecting fragile backends, nginx

Rate Limiting Across Many Servers

One process with an in-memory dict is easy. But your API runs on 20 servers behind a load balancer, and a user's requests land on all of them. Per-server limits would let through 20× the limit. You need shared state, usually Redis.

The race condition

The obvious approach (read the count, decide, write it back) has the same lost-update bug as in Transactions and Isolation Levels. Here are 100 concurrent requests against a limit of 10:

def allow_naive(user, capacity=10):
    """Read, decide in Python, write back: a race between GET and SET."""
    key = f"naive:{user}"
    used = int(r.get(key) or 0)
    time.sleep(0.001)                       # any real network round trip lands here
    if used < capacity:
        r.set(key, used + 1)
        return True
    return False
100 concurrent requests against a limit of 10:
  naive GET + SET : 100 allowed
  atomic Lua      : 10 allowed

All 100 got through. Twenty threads read used = 0 before anyone wrote. A second run allowed 94. The limiter only works when nothing happens at the same time, which is exactly when it isn't needed.

The fix: one atomic operation

Redis runs a Lua script atomically: no other command can run in the middle of it. Here's a complete token bucket as one script:

local key      = KEYS[1]
local capacity = tonumber(ARGV[1])
local rate     = tonumber(ARGV[2])        -- tokens per second
local now      = tonumber(ARGV[3])        -- seconds, from the caller
local cost     = tonumber(ARGV[4])

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 + math.max(0, now - ts) * rate)
local allowed = 0
if tokens >= cost then
  tokens = tokens - cost
  allowed = 1
end
redis.call('HSET', key, 'tokens', tokens, 'ts', now)
redis.call('EXPIRE', key, math.ceil(capacity / rate) * 2)
return allowed

And calling it from Python:

import time
import redis

r = redis.Redis()
bucket = r.register_script(TOKEN_BUCKET_LUA)       # the Lua source above

def allow(user, capacity=10, rate=1.0):
    return bucket(keys=[f"rl:{user}"], args=[capacity, rate, time.time(), 1]) == 1

Details that matter in production:

Telling Clients They've Been Limited

A good rate limiter is also good API design. Reject with HTTP 429 Too Many Requests, and tell the client what to do:

HTTP/1.1 429 Too Many Requests
Content-Type: application/json
Retry-After: 6
RateLimit-Limit: 10
RateLimit-Remaining: 0
RateLimit-Reset: 6

{"error": "rate_limited", "message": "10 requests per minute. Retry in 6 seconds."}
Header Meaning
Retry-After Seconds to wait (standard HTTP, understood by many clients)
RateLimit-Limit / -Remaining / -Reset Quota, what's left, and seconds until reset (IETF draft; GitHub and others use X-RateLimit-* versions)

Send the RateLimit-* headers on successful responses too, so well-behaved clients can slow down before hitting the limit.

On the client side

Clients should respect Retry-After, and otherwise retry with exponential backoff plus jitter. Without jitter, every client that was rejected at the same moment retries at the same moment, and the thundering herd repeats:

import random, time

def call_with_backoff(do_request, max_attempts=6, base=0.5, cap=30):
    for attempt in range(max_attempts):
        resp = do_request()
        if resp.status_code != 429:
            return resp
        retry_after = resp.headers.get("Retry-After")
        delay = float(retry_after) if retry_after else random.uniform(0, min(cap, base * 2 ** attempt))
        time.sleep(delay)                   # "full jitter": random between 0 and the backoff cap
    return resp

Design Checklist

  1. What's the key? API key for paying customers, user ID for logged-in users, IP address for anonymous traffic (careful: many users can share an IP behind NAT, and attackers rotate IPs).
  2. Which algorithm? A token bucket for user-facing APIs (it allows natural bursts), a sliding window counter when you need "N per window" semantics, a leaky bucket in front of fragile systems.
  3. Several layers. A coarse per-IP limit at the edge (nginx, CDN, WAF), per-customer limits in the API gateway, and per-endpoint limits on expensive operations such as search, exports and login attempts.
  4. Different costs. Charge expensive requests more tokens (the cost argument in the Lua script).
  5. Fail open or closed, decided in advance, not during an incident.
  6. Observe it. Count 429s per key and per endpoint. A sudden jump means either an attack or a client bug, and both are worth knowing about.

The one idea to keep: every rate limiter has a long-term rate and a burst size, even if it doesn't name them. Choose both deliberately, enforce them atomically, and tell clients clearly when they've hit the limit.

Copied to clipboard!