LLD: Design a Rate Limiter (Classes and Strategies)

System Design · Low-Level Design · Intermediate · 25 min

Write the classes behind a rate limiter: fixed window, sliding log and token bucket as interchangeable strategies, a factory that gives each user their own limiter, and a clear answer to 'what happens when two threads call allow() at once?'.

Every user has their own small jar of tokens on a shelf. A tap drips one token into each jar every few seconds, but a jar can only hold so many. Each request takes one token out. Empty jar: please wait.

The idea in everyday words

A theme-park ride lets people on in groups. Fixed window: 'up to 20 people per 10-minute slot, the slot starts on the clock'. Sliding log: the guard writes down when each rider got on and lets you in only if fewer than 20 got on in the last 10 minutes. Token bucket: the guard has a stack of wristbands that is refilled slowly; a group can rush in while wristbands last, then everyone waits for new ones.

From the big picture to classes

In the high-level lesson on queues and rate limiting you placed the limiter in front of the API (at the gateway, backed by a shared store). The LLD question zooms in: write the limiter itself.

Requirements to agree on:

  • Limit per user (or per API key, per IP). One noisy user must not use up everyone else's budget.
  • allow(user, now) answers yes or no. A "no" becomes HTTP 429 Too Many Requests, ideally with a Retry-After header.
  • The algorithm is configurable: fixed window, sliding log or token bucket, chosen when the limiter is built.
  • now is passed in (not read from the clock inside), so tests are deterministic.

Entities: RateLimiter (the front door), one algorithm object per user, and the algorithms themselves. Three algorithms with the same question (allow(now)) and different rules is a textbook Strategy. Building "a new limiter object for this user" from a name is a Factory.

Three algorithms, one interface

With limit = 3 and window = 10 seconds:

Algorithm State it keeps Rule Good at Weak at
Fixed window current window number and a count windows are 0-9, 10-19, ...; at most 3 per window tiny memory, simple a burst at the edge: 3 at t=9 and 3 at t=10 means 6 in 2 seconds
Sliding log the times of recent allowed requests at most 3 allowed in (now - 10, now] exact memory grows with the limit (one timestamp per request)
Token bucket tokens and the last refill time capacity 3, one token every 10 s; a request spends a token allows short bursts, smooth average rate two numbers to tune

Two details that make or break the code:

  1. Sliding log boundary. A request exactly window seconds old has left the window: drop timestamps with ts <= now - window. And log only allowed requests; otherwise a user who keeps retrying while blocked stays blocked forever.
  2. Token bucket refill. Add (now - last) // every tokens, cap at capacity, and move last forward by gained * every, not to now. Setting last = now throws away the part of an interval that already passed, so tokens arrive later and later.
tokens, last, every, cap = 0, 0, 10, 3
for now in [15, 20]:
    gained = (now - last) // every
    tokens, last = min(cap, tokens + gained), last + gained * every
    print(f"t={now}: +{gained} token(s), last refill counted up to t={last}")

Class design

RateLimiter
 ├─ make(now) -> Algorithm           (factory, chosen once from "fixed" | "sliding" | "token")
 ├─ per_user: user -> Algorithm      (each user has their own state)
 └─ allow(user, now) -> bool

Algorithm (interface)  { allow(now) -> bool }
 ├─ FixedWindow   { limit, window, current, count }
 ├─ SlidingLog    { limit, window, log: queue of times }
 └─ TokenBucket   { capacity, every, tokens, last }
  • RateLimiter never asks "which algorithm am I?". It looks up the user's object and calls allow(now). Adding a "sliding window counter" algorithm is one new class and one entry in the factory table.
  • An unknown algorithm name fails fast when the limiter is built (raise an error), not on the first request in production.
  • Per-user objects are created lazily, on the user's first request. A token bucket created then starts full, so a new user can make a small burst straight away.
  • Memory: a million users means a million small objects. In "Go deeper" we evict idle ones.

Thread safety, in words

A real server calls allow() from many threads at once. Look at the token bucket's core:

if self.tokens > 0:      # 1. check
    self.tokens -= 1     # 2. act

Two threads for the same user, 1 token left. Both run line 1, both see 1, both run line 2. Two requests allowed, tokens = -1. This is a check-then-act race, the most common concurrency bug in LLD rounds.

Ways to fix it, from simple to scalable:

Fix How Trade-off
One global lock wrap allow in a mutex correct, but every user waits for every other user
One lock per user (or lock striping: 64 locks, user hashed to one) lock only that user's object users no longer block each other; the usual answer
Atomic operations compare-and-set on the token count, retry on conflict lock-free and fast; harder to read
Single writer one thread owns each user's state; others send it messages no locks at all; needs a queue

Creating the per-user object is a race too: two threads see "no limiter for this user" and both create one. Use a concurrent map's "get or create atomically" (computeIfAbsent in Java, setdefault under a lock in Python).

Across many servers the counters must live in a shared store (Redis-style INCR with an expiry, or a small script that does check-and-decrement atomically), because a lock in one process means nothing to another.

Go deeper: approximations, cleanup and clocks

  • Sliding window counter. Keep two fixed-window counts (previous and current) and estimate: current + previous * (time left in current window / window). Nearly as accurate as the log, with two numbers instead of a list. Many production limiters use it.
  • Leaky bucket. Requests join a queue that drains at a fixed rate: smooths traffic perfectly but adds waiting instead of rejecting.
  • Evicting idle users. Drop a user's object after it has been idle for longer than its window (or keep the map as an LRU with a size cap). A token bucket idle for capacity * every is full anyway, so recreating it later gives the same answer.
  • Monotonic clocks. Use a monotonic clock for now, never wall-clock time: a clock that jumps back an hour would make now - last negative.
  • Fail open or fail closed? If the shared counter store is down, do you allow everything (risk overload) or deny everything (outage)? Most public APIs fail open with a local fallback limit. Say which and why.
  • Cost-based limits. Some calls are heavier: let allow(user, now, cost) spend more than one token (LLM APIs limit tokens per minute this way).

Step by step

  1. A full bucket:

    Token bucket, capacity 3, one new token every 4 seconds. u1's first request at t=0 creates its bucket full (3 tokens) and spends one: allow, 2 left.

  2. A burst:

    t=1 allow (1 left), t=2 allow (0 left). t=3: (3 - 0) // 4 = 0 new tokens, bucket empty: deny.

  3. One token drips in:

    t=5: (5 - 0) // 4 = 1 new token, last moves to 4 (not 5). allow, 0 left.

  4. The remainder counts:

    t=8: (8 - 4) // 4 = 1 new token because last was 4. allow, 0 left, last = 8. Had we set last = 5 at t=5, this request would be denied.

  5. Too soon:

    t=9: (9 - 8) // 4 = 0 new tokens: deny. The bucket is empty again.

  6. A long pause is capped:

    t=20: (20 - 8) // 4 = 3 new tokens, capped at capacity 3. allow, 2 left. Results: allow, allow, allow, deny, allow, allow, deny, allow.

Code example

# Two threads for the same user, interleaved step by step (no real threads, so it is repeatable).
def run(interleaving, atomic):
    state = {"tokens": 1}
    seen, allowed = {}, []
    for thread, action in interleaving:
        if atomic and action == "check":          # check and act together, as if under a lock
            if state["tokens"] > 0:
                state["tokens"] -= 1
                allowed.append(thread)
        elif not atomic and action == "check":
            seen[thread] = state["tokens"] > 0     # read
        elif not atomic and action == "act" and seen[thread]:
            state["tokens"] -= 1                   # write, based on an old read
            allowed.append(thread)
    return allowed, state["tokens"]

steps = [("A", "check"), ("B", "check"), ("A", "act"), ("B", "act")]
print("no lock:  allowed", *run(steps, atomic=False))
print("with lock: allowed", *run(steps, atomic=True))

Complexity

  • Time: O(1) per request for fixed window and token bucket; amortised O(1) for the sliding log (each timestamp is removed once)
  • Space: O(U) for U users; the sliding log adds O(limit) timestamps per user

Interview tips

  • Start with the interface: allow(user, now) -> bool, and say that now is injected for testability.

  • Name the three algorithms with one strength and one weakness each, then implement them as Strategy classes behind that interface.

  • Show per-user isolation explicitly: a map from user to limiter object, created on first use by a factory.

  • Point at the check-then-act line and explain the race; offer per-user locks or lock striping, and an atomic script in a shared store for many servers.

  • Mention memory cleanup for idle users and the fail-open versus fail-closed choice if the shared store is down.

Challenge: Rate Limiter with Pluggable Algorithms

Write run_rate_limiter(algo, limit, window, ops). Each command is req <user> <t> (t is a whole number of seconds; times never go down). Return allow <user> or deny <user> for each command. Every user has their own limiter, created at their first request.

algo picks the algorithm:

  • "fixed": windows are aligned: [0, window), [window, 2*window), ... At most limit allowed requests per window.
  • "sliding": at most limit allowed requests in (t - window, t]. Denied requests are not remembered.
  • "token": a bucket with capacity limit that starts full when the user is first seen. One token is added every window seconds since the last refill (never above capacity, and the unused part of an interval is kept). Each allowed request spends one token.
  • Anything else: raise an error (Python ValueError, JavaScript throw).

Build it with one class per algorithm (each with allow(now)), and a RateLimiter that keeps a map from user to algorithm object.

Example (token bucket, capacity 3, one token every 4 s):

run_rate_limiter("token", 3, 4, ["req u1 0", "req u1 1", "req u1 2", "req u1 3", "req u1 5"])
  -> ["allow u1", "allow u1", "allow u1", "deny u1", "allow u1"]

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Low-Level Design

Previous: LLD: Design an Elevator System · Next: LLD: Design Splitwise (Expense Sharing)