← Back to System Design, page 2

system-design-0021 · Medium fresher

Explain the common rate limiting algorithms: fixed window, sliding window log, sliding window counter, token bucket and leaky bucket.

Fixed window counts requests per clock window and is simple but allows bursts at window edges. Sliding window log stores every timestamp and is exact but memory heavy. Sliding window counter blends two fixed windows for a cheap approximation. Token bucket allows bursts up to a capacity and then a steady refill rate; leaky bucket smooths output to a constant rate.

Full answer

Why limit

Rate limiting caps how many requests a client can make in a period. It protects services from overload and abuse (password guessing, scraping), and enforces fair use or paid tiers. A typical rule: 100 requests per minute per API key; 5 login attempts per minute per account.

Fixed window counter

Keep a counter per key per window (user:7:2026-12-04T10:15). Increment; reject when it exceeds the limit. Cheap: one counter per key. Problem: a user can send 100 requests at 10:15:59 and another 100 at 10:16:00, which is 200 in two seconds.

Sliding window log

Store the timestamp of every request (a Redis sorted set). On each request, remove timestamps older than 60 seconds, count the rest, allow if under the limit. Exact, but memory grows with the limit: 100 timestamps per user.

Sliding window counter

Keep counts for the current and previous fixed windows and weight the previous one by how much of it still overlaps the last 60 seconds:

estimate = current + previous x (1 - elapsed_fraction_of_current_window)

If the previous minute had 80 requests, the current has 30, and we are 25% into the current minute: 30 + 80 x 0.75 = 90, under a limit of 100. Two counters per key and close to exact.

Token bucket

A bucket holds up to capacity tokens and refills at rate tokens per second. Each request takes one token; with no tokens, reject. It allows short bursts (up to capacity) while enforcing an average rate. Used by many API gateways and cloud providers.

Run with Python 3.13, fixed timestamps so the result is the same every run:

python
class TokenBucket:
    def __init__(self, capacity, refill_per_sec):
        self.capacity = capacity
        self.rate = refill_per_sec
        self.tokens = capacity
        self.last = 0.0

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

bucket = TokenBucket(capacity=5, refill_per_sec=1)   # bursts of 5, then 1/s
times = [0, 0, 0, 0, 0, 0, 0.5, 1.0, 1.0, 3.0]
print([bucket.allow(t) for t in times])

Output:

[True, True, True, True, True, False, False, True, False, True]

Five requests at time 0 drain the bucket, the sixth is rejected, and from then on one token returns each second.

Leaky bucket

Requests enter a fixed-size queue that drains at a constant rate. Output is perfectly smooth, which suits protecting a fragile downstream (an SMS provider that accepts 10 messages per second). Bursts wait or are dropped when the queue is full.

Choosing

Token bucket for most public APIs (bursts are normal for real clients). Sliding window counter when you want a simple "N per minute" rule without edge bursts. Leaky bucket when the downstream needs a steady rate.

By level

Fresher: Explain fixed window and token bucket clearly with a small example, and why limits protect a service. Showing the window-edge burst with numbers is a strong fresher answer.

Mid: Compare all algorithms on accuracy, memory and burst behaviour, compute a sliding window estimate, and choose by use case. Expect a correct sliding window estimate calculation.

Senior: Discuss distributed enforcement, atomicity, clock issues, multi-tier limits, response headers, and how limits interact with retries and load shedding. It should cover how limits are enforced across many gateways.

Key points

  • Fixed window is cheap but allows double bursts at window edges
  • Sliding log is exact but stores every timestamp
  • Sliding window counter approximates with two counters
  • Token bucket allows bursts up to capacity and enforces an average rate
  • Leaky bucket produces a smooth constant output rate

Common mistakes

  • Confusing token bucket with leaky bucket
  • Ignoring the window boundary burst in fixed windows
  • Storing a timestamp log for very high limits
  • Not saying which key the limit applies to (user, IP, API key)

Follow-ups

  • How would you implement token bucket atomically in Redis?
  • How should the API tell a client it was limited?
  • How would you rate limit across 50 gateway servers?

Tips

  • Define the rule and the key first
  • Show the window-edge burst with numbers
  • Pick one algorithm for the stated use case and say why

Evaluation rubric

  • Correct description of all five algorithms
  • Identifies the fixed window edge problem
  • Explains burst behaviour of token bucket
  • Matches algorithm to use case