TExcelTAD
Home › System Design › Rate Limiting Algorithms

Rate Limiting Algorithms

A rate limiter caps how many requests a client may make in a period: 100 requests per minute per API key, 5 login attempts per hour per account, 1,000 messages per second per tenant. It protects services from overload and abuse, keeps one noisy customer from hurting the others, and enforces paid quotas. Rejected requests get 429 Too Many Requests, ideally with a Retry-After header.

There are five classic algorithms. They all answer the same question, may this request go through now?, with different trade-offs in memory, accuracy and burst behaviour. All examples below use a simulated clock (now in seconds), so they are deterministic.

Fixed window counter

Count requests per calendar window (for example per minute: 12:00:00-12:00:59). Simple and tiny (one counter per client), but a client can send a full quota at the end of one window and another at the start of the next, twice the limit within a second or two.

python · try it yourself
class FixedWindow:
    def __init__(self, limit, window):
        self.limit, self.window = limit, window
        self.current_window, self.count = None, 0

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

limiter = FixedWindow(limit=5, window=60)
times = [58, 58.5, 59, 59.2, 59.5, 60.1, 60.3, 60.5, 60.7, 61, 61.2]
allowed = [t for t in times if limiter.allow(t)]
print(f"allowed {len(allowed)} of {len(times)} requests within {times[-1] - times[0]:.1f} s:")
print(allowed)
allowed 10 of 11 requests within 3.2 s:
[58, 58.5, 59, 59.2, 59.5, 60.1, 60.3, 60.5, 60.7, 61]

Ten requests in about three seconds although the limit is "5 per minute": that's the boundary burst problem.

Sliding window log

Keep a timestamp for every accepted request and count those in the last window seconds. Exact, but memory grows with the limit (one entry per request), which is costly for large quotas.

python · try it yourself
from collections import deque

class SlidingLog:
    def __init__(self, limit, window):
        self.limit, self.window, self.log = limit, window, deque()

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

limiter = SlidingLog(limit=5, window=60)
times = [58, 58.5, 59, 59.2, 59.5, 60.1, 60.3, 117, 118.2, 119]
for t in times:
    print(f"t={t:6.1f} {'allow' if limiter.allow(t) else 'REJECT'}  (in log: {len(limiter.log)})")
t=  58.0 allow  (in log: 1)
t=  58.5 allow  (in log: 2)
t=  59.0 allow  (in log: 3)
t=  59.2 allow  (in log: 4)
t=  59.5 allow  (in log: 5)
t=  60.1 REJECT  (in log: 5)
t=  60.3 REJECT  (in log: 5)
t= 117.0 REJECT  (in log: 5)
t= 118.2 allow  (in log: 5)
t= 119.0 allow  (in log: 4)

Sliding window counter

A clever approximation: keep only the counts of the current and previous fixed windows, and weight the previous one by how much of it still overlaps the sliding window. Two counters per client, and in practice very close to exact.

python · try it yourself
class SlidingCounter:
    def __init__(self, limit, window):
        self.limit, self.window = limit, window
        self.counts = {}                           # window index -> count

    def allow(self, now):
        w = int(now // self.window)
        elapsed = (now % self.window) / self.window
        previous = self.counts.get(w - 1, 0)
        current = self.counts.get(w, 0)
        estimate = previous * (1 - elapsed) + current
        if estimate < self.limit:
            self.counts[w] = current + 1
            return True, estimate
        return False, estimate

limiter = SlidingCounter(limit=5, window=60)
for t in [58, 58.5, 59, 59.2, 59.5, 60.1, 60.3, 90, 100, 110, 115]:
    ok, est = limiter.allow(t)
    print(f"t={t:5.1f} estimate {est:4.2f} -> {'allow' if ok else 'REJECT'}")
t= 58.0 estimate 0.00 -> allow
t= 58.5 estimate 1.00 -> allow
t= 59.0 estimate 2.00 -> allow
t= 59.2 estimate 3.00 -> allow
t= 59.5 estimate 4.00 -> allow
t= 60.1 estimate 4.99 -> allow
t= 60.3 estimate 5.97 -> REJECT
t= 90.0 estimate 3.50 -> allow
t=100.0 estimate 3.67 -> allow
t=110.0 estimate 3.83 -> allow
t=115.0 estimate 4.42 -> allow

At t=60.1 the previous window's 5 requests still count almost fully (estimate 4.99, just under the limit, so one request slips through), and at t=60.3 the estimate of 5.97 blocks the boundary burst. By t=90 half of the previous window has "slid out" and requests are allowed again. Cloudflare reported that this approximation was wrong for only 0.003% of requests in production.

Token bucket

A bucket holds up to capacity tokens and refills at rate tokens per second. Each request takes one token; with no tokens, the request is rejected. The capacity allows short bursts, while the refill rate sets the long-term average. It's the most widely used algorithm (AWS API Gateway, Stripe, NGINX's burst).

python · try it yourself
class TokenBucket:
    def __init__(self, capacity, rate):
        self.capacity, self.rate = capacity, rate
        self.tokens, self.last = capacity, 0.0

    def allow(self, now):
        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

bucket = TokenBucket(capacity=4, rate=1)          # bursts of 4, then 1 request/s
times = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 1.5, 1.6, 2.6, 5.0, 5.1, 5.2, 5.3, 5.4]
for t in times:
    ok = bucket.allow(t)
    print(f"t={t:3.1f} {'allow ' if ok else 'REJECT'} tokens left {bucket.tokens:4.2f}")
t=0.0 allow  tokens left 3.00
t=0.1 allow  tokens left 2.10
t=0.2 allow  tokens left 1.20
t=0.3 allow  tokens left 0.30
t=0.4 REJECT tokens left 0.40
t=0.5 REJECT tokens left 0.50
t=1.5 allow  tokens left 0.50
t=1.6 REJECT tokens left 0.60
t=2.6 allow  tokens left 0.60
t=5.0 allow  tokens left 2.00
t=5.1 allow  tokens left 1.10
t=5.2 allow  tokens left 0.20
t=5.3 REJECT tokens left 0.30
t=5.4 REJECT tokens left 0.40

The first four requests drain the burst capacity, then requests are allowed about once per second. After a quiet period (t=2.6 to 5.0) the bucket has refilled and allows another burst.

Leaky bucket

The leaky bucket is a queue that drains at a constant rate. Requests join the queue if there is room and are processed at a steady pace; excess requests overflow. Unlike the token bucket it smooths bursts into a constant output rate, which suits work that must be paced (sending to a partner API, writing to a slow disk).

python · try it yourself
class LeakyBucket:
    def __init__(self, capacity, leak_per_s):
        self.capacity, self.interval = capacity, 1 / leak_per_s
        self.queue_end = 0.0                       # when the last queued request will be processed

    def submit(self, now):
        start = max(now, self.queue_end)
        queued_ahead = (start - now) / self.interval
        if queued_ahead >= self.capacity:
            return None                            # bucket overflows
        self.queue_end = start + self.interval
        return start

bucket = LeakyBucket(capacity=3, leak_per_s=2)     # process one request every 0.5 s
for t in [0, 0, 0, 0, 0, 1.0, 3.0]:
    when = bucket.submit(t)
    print(f"arrive {t:3.1f} -> " + (f"processed at {when:3.1f}" if when is not None else "dropped (overflow)"))
arrive 0.0 -> processed at 0.0
arrive 0.0 -> processed at 0.5
arrive 0.0 -> processed at 1.0
arrive 0.0 -> dropped (overflow)
arrive 0.0 -> dropped (overflow)
arrive 1.0 -> processed at 1.5
arrive 3.0 -> processed at 3.0

Five requests arrive at once; three are queued and released 0.5 s apart, two overflow. The output is perfectly smooth, at the cost of added waiting time.

Choosing an algorithm

Algorithm Memory per client Bursts Accuracy Notes
Fixed window 1 counter Up to 2x at window edges Low at boundaries Easiest; fine for coarse daily quotas
Sliding window log 1 timestamp per request No Exact Expensive for large limits
Sliding window counter 2 counters Smoothed Approximate, very close Great default for "N per minute"
Token bucket Tokens + timestamp Yes, up to capacity Exact average rate Most popular for APIs
Leaky bucket Queue position Smoothed into constant rate Exact Adds latency; good for pacing

Note: On a single server these fit in a dictionary. Across many servers the state must be shared (usually in Redis, updated atomically with a Lua script) or approximated locally. That's the subject of the case study Design a Rate Limiter.

Test yourself

What is the main weakness of a fixed window counter?

  1. It needs a lot of memory
  2. Clients can send up to twice the limit around a window boundary
  3. It can't reject requests
  4. It requires a queue

Which algorithm allows short bursts while enforcing an average rate?

  1. Leaky bucket
  2. Token bucket
  3. Sliding window log
  4. None of them

Why might you prefer a leaky bucket over a token bucket?

  1. It uses less memory
  2. It produces a smooth, constant output rate
  3. It never drops requests
  4. It allows larger bursts