DEV Community

Anurag Goel
Anurag Goel

Posted on Originally published at algosimplified.dev

Rate Limiter System Design and Algorithms

This article first appeared on AlgoSimplified. That URL is canonical. The full lesson has the exercises and a short quiz; this is a shorter cut of the same design.

There is a full system-design lesson for this, rather than an LLD one. The Redis course also has a smaller sliding-window and token-bucket section; the design below is the HLD case study.

The problem

Design a service that limits how many requests a client can make, for example 100 requests per minute per API key. It protects services from abuse and overload, enforces pricing tiers, and keeps one noisy customer from hurting the rest.

A reasonable set of requirements:

  • Limit by a key (user id, API key, IP) with per-rule limits (/login: 5/min per IP; API: 1,000/min per key).
  • Reject excess requests with 429 Too Many Requests and a Retry-After header.
  • Low added latency (a millisecond or two), and correct behaviour across many API servers.
  • If the limiter itself fails, fail open (let traffic through) rather than taking the whole API down, for most endpoints.

It belongs in an API gateway or in middleware, consulting a shared store (Redis) so all servers agree on the counts. Client-side limits are a courtesy, not enforcement.

The algorithms

Fixed window counter. Count requests per key per calendar minute. Simple and cheap. The flaw is at the boundary: a client can send 100 requests at 0:59 and 100 at 1:00, which is 200 in two seconds.

Sliding window log. Store each request's timestamp and count those in the last 60 seconds. Exact, but memory grows with traffic.

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 rolling window. Nearly exact, with two counters per key.

Token bucket. A bucket holds up to capacity tokens and refills at rate per second; each request takes one. This allows short bursts up to capacity while enforcing the average rate, which is what many cloud APIs do.

Leaky bucket. Requests enter a queue drained at a fixed rate, which smooths the outflow completely. A good fit when the downstream can only take a steady stream.

The two implementations below are the ones I use most often, run with a fake clock so the output is deterministic:

"""Two rate limiters: token bucket and sliding-window counter."""
import time


class TokenBucket:
    """Allows bursts up to `capacity`, refills at `rate` tokens per second."""

    def __init__(self, capacity: int, rate: float, now=time.monotonic):
        self.capacity, self.rate, self.now = capacity, rate, now
        self.tokens = float(capacity)
        self.last = now()

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


class SlidingWindowCounter:
    """Approximates a rolling window using the current and previous fixed windows."""

    def __init__(self, limit: int, window: float, now=time.monotonic):
        self.limit, self.window, self.now = limit, window, now
        self.current_start = 0.0
        self.current = self.previous = 0

    def allow(self) -> bool:
        t = self.now()
        start = t - (t % self.window)
        if start != self.current_start:
            # moved into a new window; previous only counts if it was the adjacent one
            self.previous = self.current if start - self.current_start == self.window else 0
            self.current, self.current_start = 0, start
        overlap = 1 - (t - start) / self.window  # fraction of previous window still in view
        estimated = self.previous * overlap + self.current
        if estimated < self.limit:
            self.current += 1
            return True
        return False


class FakeClock:
    def __init__(self):
        self.t = 0.0

    def __call__(self):
        return self.t


if __name__ == "__main__":
    clock = FakeClock()
    bucket = TokenBucket(capacity=5, rate=1, now=clock)
    burst = [bucket.allow() for _ in range(7)]
    print("token bucket, 7 instant requests:", burst)
    clock.t += 2
    print("after 2 s:", [bucket.allow() for _ in range(3)])

    clock = FakeClock()
    sw = SlidingWindowCounter(limit=10, window=60, now=clock)
    clock.t = 50
    print("sliding window, 10 at t=50s:", sum(sw.allow() for _ in range(10)), "allowed")
    clock.t = 70  # new window; 10/60 of it elapsed, so ~83% of last window still counts
    print("12 more at t=70s:", sum(sw.allow() for _ in range(12)), "allowed")
Enter fullscreen mode Exit fullscreen mode
token bucket, 7 instant requests: [True, True, True, True, True, False, False]
after 2 s: [True, True, False]
sliding window, 10 at t=50s: 10 allowed
12 more at t=70s: 2 allowed
Enter fullscreen mode Exit fullscreen mode

The bucket allows a burst of 5, then refills 2 tokens in 2 seconds. The sliding window remembers that 10 requests happened 20 seconds ago in the previous window and only admits 2 more, which is how it avoids the fixed-window boundary burst.

Distributed design

client -> load balancer -> API gateway (limiter middleware) -> services
                                |
                                v
                         Redis cluster (counters, sharded by key)
                                ^
                         rules config (loaded and cached by gateways)
Enter fullscreen mode Exit fullscreen mode

The check and update in Redis must be atomic. Otherwise two gateways read "99", both allow, and the count becomes 101. Two options that work:

  • INCR key then EXPIRE key 60 for fixed windows (INCR is atomic; set the expiry when the value is 1).
  • A Lua script that reads, computes and writes the token bucket in one step on the Redis server.

Each check is one round trip (around 0.5 ms in the same data centre). Shard counters across Redis nodes by key.

When one Redis call per request starts to hurt:

  • Local pre-aggregation: each gateway keeps a small local budget and syncs with Redis every few hundred milliseconds. Slightly less accurate, with far fewer Redis calls.
  • Multi-region: keep limits per region (the simplest option), or sync asynchronously and accept slight over-admission.
  • Hot keys: one very large customer can get a dedicated Redis shard.

Failure handling

  • If Redis is unreachable, fail open (with an alarm) for ordinary APIs; fail closed for security-sensitive ones like login or password reset.
  • Return headers so clients can back off cleanly: X-RateLimit-Limit, X-RateLimit-Remaining, Retry-After.
  • Log rejected requests. A spike of 429s is an early signal of abuse or a buggy client.

The full rate limiter lesson also has exercises (a sliding-window log, the Redis Lua token bucket, tiered limits) and a short quiz. It is part of the free System Design course.

Top comments (0)