Lesson 18 / 19 · Case Studies

Design a Rate Limiter: Token Bucket, Sliding Window and Thread Safety

Rate limiter low-level design: fixed window, sliding log, sliding counter and token bucket as strategies, per-key locks, Retry-After, eviction, in Java and Python.

45-55 min intermediate Not completed

On this page · 13 sections
  1. The contract, before the classes
  2. Four algorithms, one question each
  3. Classes
  4. Patterns: what is here and what is not
  5. One lock per key
  6. The code
  7. What the simulated minute says
  8. The benchmark numbers
  9. Where interviewers take it next
  10. Mistakes worth avoiding
  11. Key takeaways
  12. Exercises
  13. Quiz

“Limit each client to 5 requests a second” sounds like one requirement. It is at least four, depending on what you count and when the count resets, and the four common algorithms give different answers on the same traffic. On the 60-second trace below, with the same “5 per second” setting, the strictest algorithm let no client exceed 5 in any one-second span, and the most popular one let 297 of 300 clients do it. Neither was broken. They enforce different contracts.

So the low-level design question has two parts. The structural part is short: the algorithm is a strategy, per-client state lives in a map, and every decision for one client is made under that client’s lock. The part that gets you hired is knowing which contract each algorithm enforces, and saying which one you would pick for an API, a login form and an SMS gateway.

The code is about 350 lines of Python and 310 of Java. The demos print identical output in both.

The contract, before the classes

What the limiter does:

  • try_acquire(key, now) answers allowed or refused for one request from one client (key is an API key, user id or IP).
  • A refusal says when to retry, which becomes the HTTP Retry-After header on a 429. An allowed request reports how many are left, for X-RateLimit-Remaining.
  • The limit and window, or capacity and refill rate, are configuration. Swapping the algorithm does not change the caller.
  • Safe for many threads. Two requests from the same client must never both take the last slot.
  • State for clients who have gone quiet is removed, so a crawler hitting you from 10 million IPs does not become 10 million map entries forever.

What it does not do here, and what I would say about each:

  • Limits shared across several servers. One process, in-memory. Across servers, the state moves to Redis with the check-and-update done atomically on the server side (a Lua script or a single INCR with expiry for a fixed window). That is a high-level design discussion; the strategy interface below does not change.
  • Several limits at once (per user and per endpoint and global). A follow-up below; the hard part is not consuming from the first limit when the second refuses.
  • Queuing excess requests instead of refusing them. That is traffic shaping (the leaky bucket used as a queue), and it belongs in a proxy, not in application code.
  • Weighted requests (an export costs 50, a read costs 1). One extra parameter, cost; mentioned in the exercises.

Time is an integer number of milliseconds passed in by the caller. Nothing inside reads the clock. That one decision is what makes every demo below exact and reproducible, and it is the first thing I would do in a real implementation too.

Four algorithms, one question each

AlgorithmState per keyWhat “5 per second” meansWeak spot
Fixed windowwindow start, countat most 5 in each calendar second (0-999 ms, 1000-1999 ms, …)10 in 100 ms across a boundary
Sliding logtimestamp of every allowed request in the last secondat most 5 in any 1000 ms spanmemory grows with the limit
Sliding window counterwindow start, this window’s count, last window’s countan estimate of the last 1000 ms, assuming last window’s requests were evenly spreadwrong when traffic is bursty
Token buckettokens, last refill timea burst of up to 5, then 5 per second sustainedallows up to about 2× in a rolling second, on purpose

Fixed window counts requests per calendar window. It is one integer and a timestamp, and it is what you get from Redis INCR plus EXPIRE. The boundary problem is real: 5 requests at 0.90 s and 5 more at 1.00 s are 10 requests in 100 ms, all allowed.

Sliding log keeps the timestamp of each allowed request and drops those older than the window. It is the only exact one. Its memory is O(limit) per key, which is nothing at 5 a second and a problem at 10,000 an hour.

Sliding window counter keeps two fixed-window counts and weights the previous one by how much of it still overlaps the last second: at 300 ms into the current window, 70% of last window’s count is assumed to still be in range. Three integers per key. It is exact when traffic is smooth and can be wrong in both directions when it is bursty, which the simulation shows.

Token bucket holds up to capacity tokens, refills at rate tokens a second, and a request takes one. It is the only one that separates “how big a burst” from “how fast sustained”, which is why AWS API Gateway and most cloud APIs describe their limits as a rate plus a burst. The tokens are stored in thousandths so that refill is integer arithmetic: a float bucket gives different answers in Python and Java after enough refills, and you do not want to debug that.

Leaky bucket, the one that usually gets named fifth, is a token bucket seen from the other side when used as a meter. Used as a queue, it is the traffic shaping I put out of scope.

Classes

  • RateLimiter (Limiter in Java): the facade. A map from key to entry, try_acquire, evict_idle.
  • Algorithm: the strategy interface. new_state(), acquire(state, now), size(state). The four algorithms implement it.
  • Per-key state: a small array or deque created by the algorithm. The algorithm object itself is immutable configuration shared by all keys.
  • Entry: the state, its lock, and when the key was last seen.
  • Decision: allowed, remaining, retry-after in milliseconds.
classDiagram
  class RateLimiter {
    +algorithm: Algorithm
    +try_acquire(key, now) Decision
    +evict_idle(now, idle_ms) int
    +keys() int
  }
  class Entry {
    +state
    +last_seen: int
    -lock
  }
  class Algorithm {
    <<interface>>
    +new_state() State
    +acquire(state, now) Decision
    +size(state) int
  }
  class Decision {
    +allowed: bool
    +remaining: int
    +retry_after_ms: int
  }
  class FixedWindow {
    +limit: int
    +window_ms: int
  }
  class SlidingLog {
    +limit: int
    +window_ms: int
  }
  class SlidingCounter {
    +limit: int
    +window_ms: int
  }
  class TokenBucket {
    +capacity: int
    +per_second: int
  }
  RateLimiter "1" *-- "*" Entry : by key
  RateLimiter --> Algorithm
  RateLimiter ..> Decision : returns
  Algorithm <|.. FixedWindow
  Algorithm <|.. SlidingLog
  Algorithm <|.. SlidingCounter
  Algorithm <|.. TokenBucket

Splitting the algorithm (config, shared) from the state (per key) is the decision that matters. The common alternative is a TokenBucket object per client that holds both its settings and its tokens. It works, but changing the limit for everyone means touching every object, and measuring memory per key means guessing what the object costs. Here a key costs exactly size(state) integers plus the entry.

Patterns: what is here and what is not

Strategy for the algorithm, because the four really are interchangeable behind acquire(state, now) → Decision and the choice is a business decision that changes: a free tier on a fixed window, a paid tier on a token bucket.

Factory method, small: new_state() lets each algorithm create the state it needs, so RateLimiter never knows whether a key holds two integers or a deque.

Facade: RateLimiter is the only thing callers touch. It owns the map, the per-key locks and eviction. The HTTP middleware that turns a Decision into a 429 with Retry-After wraps it; that wrapping is a decorator around your request handler, and it lives in the web layer.

Turned down:

  • A singleton limiter. An API usually has several (per IP at the edge, per API key in the app, a tight one on /login). Tests want a fresh one per case.
  • Template method across the algorithms. They share no steps. A base class with refill(), check() and consume() hooks forces a fixed window to pretend it refills.
  • State pattern for allowed/blocked. There is no lifecycle; each call is decided from numbers.
  • Observer for metrics. One counter increment in the middleware does the job.

One lock per key

Every algorithm here is a read-modify-write: read the count or the tokens, decide, write back. Two threads doing that for the same key at the same time can both read “1 token left” and both take it. To measure it, the benchmark gives a bucket of 1,000 tokens to 8 threads with 100,000 requests each and the clock frozen so nothing refills. Without the lock, Java allowed 1,496, 1,804 and 1,766 in three of five runs; the other two ran without overlap and got 1,000 by luck. Python allowed exactly 1,000 every time: the GIL rarely switches threads inside such a short function, which is how this bug passes local tests in Python and appears in production in Java or Go. With the lock, 1,000 every run in both.

The lock is per key, not one for the whole limiter. Clients never wait for each other; the only contention is a single client racing itself, which is exactly the race that needs the lock. In Java, ConcurrentHashMap.computeIfAbsent creates each entry once; Python uses a double-checked lookup under a map lock for the same reason. A lock-free alternative for the token bucket packs tokens and timestamp into one long and updates it with compare-and-set. It is faster under heavy contention on hot keys and harder to get right; mention it, do not write it in 45 minutes.

Eviction removes keys idle for at least idle_ms. That is only safe if idle_ms is at least the window (or the time to refill a bucket completely), because a key that comes back gets fresh state, which is a full allowance. Evicting after 100 ms on a one-minute limit is a free reset for anyone who pauses.

There is one race I chose to accept. A thread that fetched an entry just before the sweep removed it updates an orphan, and the next request creates a new entry, so one extra request can get through for that key. Preventing it means holding the map lock for every request, which costs more than one request every few minutes is worth. If an interviewer pushes, the fix is to mark entries dead under their own lock during the sweep and have try_acquire retry when it finds a dead one.

The code

Both files were run on the box this lesson was written on (Python 3.13.5, OpenJDK 21.0.13, 8 vCPUs). The default run prints byte-for-byte the same output in both languages; I ran each five times and compared. The simulation uses the same 64-bit LCG in both, so the trace is identical. --bench prints timings and the unlocked race, which vary by run. Files, expected-output.txt and bench-output.txt are in course-code/low-level-design/19/ in the course repository.

Before reading:

  • Every algorithm does integer arithmetic only. The sliding counter compares prev × (w − e) + (curr + 1) × w ≤ limit × w instead of dividing.
  • The retry hint for the sliding counter is the fiddly part. My first version told a client to come back at the start of the next window, and at that moment the previous window’s count still weighed 100%, so the retry was refused again. Demo 3 now retries exactly at the hint and 1 ms before it, for all four algorithms.
  • RateLimiter(..., locked=False) exists only so the benchmark can show the race.

Python

"""Rate limiter: fixed window, sliding log, sliding window counter and token bucket
behind one strategy interface, per-key state with per-key locks, idle-key eviction,
and a 60-second traffic simulation that measures how far each one overshoots.

Run: python3 ratelimiter.py          deterministic demos (same output as RateLimiter.java)
     python3 ratelimiter.py --bench  timings and the unlocked race
"""
from __future__ import annotations

import sys
import threading
import time
from collections import deque


class Decision:
    __slots__ = ("allowed", "remaining", "retry_after_ms")

    def __init__(self, allowed: bool, remaining: int, retry_after_ms: int):
        self.allowed, self.remaining, self.retry_after_ms = allowed, remaining, retry_after_ms

    def __str__(self):
        return f"ok, {self.remaining} left" if self.allowed else f"429, retry in {self.retry_after_ms} ms"


# ---------------- algorithms (Strategy) ----------------
# Each algorithm is stateless config. Per-key state lives in a small object it creates.
# Times are integer milliseconds passed in; nothing reads the wall clock.

class FixedWindow:
    name = "fixed window"

    def __init__(self, limit: int, window_ms: int):
        self.limit, self.w = limit, window_ms

    def new_state(self):
        return [0, 0]                                   # window start, count

    def acquire(self, s, now: int) -> Decision:
        start = now - now % self.w
        if start != s[0]:
            s[0], s[1] = start, 0
        if s[1] < self.limit:
            s[1] += 1
            return Decision(True, self.limit - s[1], 0)
        return Decision(False, 0, start + self.w - now)

    def size(self, s) -> int:
        return 2


class SlidingLog:
    name = "sliding log"

    def __init__(self, limit: int, window_ms: int):
        self.limit, self.w = limit, window_ms

    def new_state(self):
        return deque()                                  # timestamps of allowed requests

    def acquire(self, s, now: int) -> Decision:
        while s and s[0] <= now - self.w:
            s.popleft()
        if len(s) < self.limit:
            s.append(now)
            return Decision(True, self.limit - len(s), 0)
        return Decision(False, 0, s[0] + self.w - now)

    def size(self, s) -> int:
        return len(s)


def _first_fit(prev: int, spare: int, w: int) -> int:
    """Smallest offset e in a window with prev * (w - e) <= spare * w."""
    if prev == 0:
        return 0
    need = max(0, w - (spare * w) // prev)
    while prev * (w - need) > spare * w:
        need += 1
    return need


class SlidingCounter:
    """Weights the previous fixed window by how much of it still overlaps the last W ms."""
    name = "sliding counter"

    def __init__(self, limit: int, window_ms: int):
        self.limit, self.w = limit, window_ms

    def new_state(self):
        return [0, 0, 0]                                # window start, current count, previous count

    def acquire(self, s, now: int) -> Decision:
        w = self.w
        start = now - now % w
        if start == s[0] + w:
            s[0], s[1], s[2] = start, 0, s[1]
        elif start != s[0]:
            s[0], s[1], s[2] = start, 0, 0
        e = now - start
        # estimate = prev * (w - e) / w + curr; allow if estimate + 1 <= limit (integers only)
        if s[2] * (w - e) + (s[1] + 1) * w <= self.limit * w:
            s[1] += 1
            left = (self.limit * w - s[2] * (w - e) - s[1] * w) // w
            return Decision(True, left, 0)
        spare = self.limit - s[1] - 1
        if spare >= 0:                                  # fits later in this window, once prev decays
            need = _first_fit(s[2], spare, w)
            if need < w:
                return Decision(False, 0, need - e)
        # otherwise wait for the next window, where today's count becomes "previous"
        return Decision(False, 0, start + w - now + _first_fit(s[1], self.limit - 1, w))

    def size(self, s) -> int:
        return 3


class TokenBucket:
    """Tokens are stored in thousandths so refill stays exact integer arithmetic."""
    name = "token bucket"

    def __init__(self, capacity: int, per_second: int):
        self.cap, self.rate = capacity, per_second      # rate in tokens/s = thousandths per ms

    def new_state(self):
        return [self.cap * 1000, None]                  # milli-tokens, last refill time

    def acquire(self, s, now: int) -> Decision:
        if s[1] is not None and now > s[1]:
            s[0] = min(self.cap * 1000, s[0] + (now - s[1]) * self.rate)
        if s[1] is None or now > s[1]:
            s[1] = now
        if s[0] >= 1000:
            s[0] -= 1000
            return Decision(True, s[0] // 1000, 0)
        if self.rate == 0:
            return Decision(False, 0, -1)
        return Decision(False, 0, -(-(1000 - s[0]) // self.rate))

    def size(self, s) -> int:
        return 2


# ---------------- the limiter (Facade) ----------------

class _Entry:
    __slots__ = ("state", "lock", "last_seen")

    def __init__(self, state, now):
        self.state, self.lock, self.last_seen = state, threading.Lock(), now


class RateLimiter:
    """One algorithm, one state object and one lock per key. Keys never contend with each other."""

    def __init__(self, algorithm, locked: bool = True):
        self.algo = algorithm
        self.locked = locked
        self._entries: dict[str, _Entry] = {}
        self._map_lock = threading.Lock()

    def try_acquire(self, key: str, now: int) -> Decision:
        e = self._entries.get(key)
        if e is None:
            with self._map_lock:
                e = self._entries.get(key)
                if e is None:
                    e = self._entries[key] = _Entry(self.algo.new_state(), now)
        if not self.locked:
            e.last_seen = now
            return self.algo.acquire(e.state, now)
        with e.lock:
            e.last_seen = max(e.last_seen, now)
            return self.algo.acquire(e.state, now)

    def evict_idle(self, now: int, idle_ms: int) -> int:
        """Drop keys not seen for idle_ms. Safe only if idle_ms >= the window or a full refill."""
        with self._map_lock:
            dead = [k for k, e in self._entries.items() if e.last_seen <= now - idle_ms]
            for k in dead:
                del self._entries[k]
            return len(dead)

    def keys(self) -> int:
        return len(self._entries)

    def stored_ints(self) -> int:
        return sum(self.algo.size(e.state) for e in self._entries.values())


def all_algorithms(limit=5, window_ms=1000):
    return [FixedWindow(limit, window_ms), SlidingLog(limit, window_ms),
            SlidingCounter(limit, window_ms), TokenBucket(limit, limit * 1000 // window_ms)]


# ---------------- demos ----------------

def max_in_window(times: list[int], w: int) -> int:
    best, i = 0, 0
    for j, t in enumerate(times):
        while times[i] <= t - w:
            i += 1
        best = max(best, j - i + 1)
    return best


def demo_boundary():
    print("1) Limit 5 per second. 10 requests at t=900..990 ms and 10 at t=1000..1090 ms")
    times = [900 + 10 * i for i in range(10)] + [1000 + 10 * i for i in range(10)]
    for algo in all_algorithms():
        rl = RateLimiter(algo)
        ok = [t for t in times if rl.try_acquire("alice", t).allowed]
        print(f"  {algo.name:<16} allowed {len(ok):>2}, most in any 1000 ms: {max_in_window(ok, 1000):>2}, at {ok}")


def demo_bucket():
    print("\n2) Token bucket, capacity 10, refill 2/s: a burst of 14 at t=0, then one every 250 ms")
    rl = RateLimiter(TokenBucket(10, 2))
    burst = [rl.try_acquire("app-7", 0) for _ in range(14)]
    print(f"  burst: {sum(d.allowed for d in burst)} allowed, then {burst[-1]}")
    for t in range(250, 3001, 250):
        print(f"  t={t:>4}: {rl.try_acquire('app-7', t)}")


def demo_retry_after():
    print("\n3) Retry-After: 5 requests at t=100..140, a 6th at t=150, then retry exactly when told")
    for algo in all_algorithms():
        hint = None
        for probe in (None, -1, 0):
            rl = RateLimiter(algo)
            for t in range(100, 141, 10):
                rl.try_acquire("bob", t)
            d = rl.try_acquire("bob", 150)
            if probe is None:
                hint = d.retry_after_ms
                continue
            again = rl.try_acquire("bob", 150 + hint + probe)
            if probe == -1:
                early = again.allowed
            else:
                on_time = again.allowed
        print(f"  {algo.name:<16} 429, retry in {hint:>4} ms; 1 ms early allowed: {early!s:<5}, on time allowed: {on_time}")


class Lcg:
    def __init__(self, seed):
        self.x = seed & 0xFFFFFFFFFFFFFFFF

    def next(self, bound):
        self.x = (self.x * 6364136223846793005 + 1442695040888963407) & 0xFFFFFFFFFFFFFFFF
        return (self.x >> 33) % bound


def make_trace(seed=19):
    """60 s, 300 clients: 240 steady (about 3/s), 45 bursty (bursts of 8-15), 15 abusive (about 25/s)."""
    rng = Lcg(seed)
    events = []
    for c in range(300):
        key = f"c{c:03d}"
        t = rng.next(1000)
        if c < 240:
            while t < 60_000:
                events.append((t, key))
                t += 1 + rng.next(666)
        elif c < 285:
            while t < 60_000:
                for _ in range(8 + rng.next(8)):
                    events.append((t, key))
                    t += rng.next(40)
                t += 2000 + rng.next(6000)
        else:
            while t < 60_000:
                events.append((t, key))
                t += 1 + rng.next(80)
    events.sort()
    return events


def demo_simulation():
    events = make_trace()
    print(f"\n4) 60 s of traffic, 300 clients, {len(events)} requests, limit 5 per second per client")
    print(f"  {'algorithm':<16} {'allowed':>7} {'clients over 5 in some 1 s':>27} {'worst 1 s':>9} {'peak ints stored':>16}")
    for algo in all_algorithms():
        rl = RateLimiter(algo)
        allowed: dict[str, list[int]] = {}
        peak = 0
        for i, (t, key) in enumerate(events):
            if rl.try_acquire(key, t).allowed:
                allowed.setdefault(key, []).append(t)
            if i % 1000 == 0:
                peak = max(peak, rl.stored_ints())
        worst = {k: max_in_window(v, 1000) for k, v in allowed.items()}
        over = sum(1 for v in worst.values() if v > 5)
        total = sum(len(v) for v in allowed.values())
        print(f"  {algo.name:<16} {total:>7} {over:>27} {max(worst.values()):>9} {peak:>16}")


def demo_threads():
    print("\n5) 8 threads x 1,000 requests on one key, bucket of 100, clock frozen (no refill)")
    rl = RateLimiter(TokenBucket(100, 0))
    counts = [0] * 8

    def work(n):
        for _ in range(1000):
            if rl.try_acquire("shared", 5).allowed:
                counts[n] += 1

    ts = [threading.Thread(target=work, args=(n,)) for n in range(8)]
    for t in ts:
        t.start()
    for t in ts:
        t.join()
    print(f"  allowed: {sum(counts)} (with the per-key lock)")


def demo_eviction():
    print("\n6) Idle keys: 10,000 one-off clients, then a sweep")
    rl = RateLimiter(SlidingLog(5, 1000))
    for i in range(10_000):
        rl.try_acquire(f"ip-{i}", i)
    rl.try_acquire("ip-regular", 10_400)
    print(f"  keys before: {rl.keys()}, stored ints: {rl.stored_ints()}")
    gone = rl.evict_idle(11_000, 1000)
    print(f"  evicted {gone} keys idle for 1 s or more; keys left: {rl.keys()}")


# ---------------- benchmarks ----------------

def bench():
    print("bench: single thread, 1,000,000 calls over 1,000 keys")
    for algo in all_algorithms(100, 1000):
        rl = RateLimiter(algo)
        keys = [f"k{i}" for i in range(1000)]
        t0 = time.perf_counter()
        for i in range(1_000_000):
            rl.try_acquire(keys[i % 1000], i // 50)
        dt = time.perf_counter() - t0
        print(f"  {algo.name:<16} {dt:5.2f} s  ({1_000_000 / dt / 1000:.0f}k calls/s)")
    print("bench: 8 threads x 100,000 requests, one key, bucket of 1,000, frozen clock")
    for locked in (False, True):
        results = []
        for _ in range(5):
            rl = RateLimiter(TokenBucket(1000, 0), locked=locked)
            counts = [0] * 8

            def work(n):
                for _ in range(100_000):
                    if rl.try_acquire("shared", 5).allowed:
                        counts[n] += 1

            ts = [threading.Thread(target=work, args=(n,)) for n in range(8)]
            for t in ts:
                t.start()
            for t in ts:
                t.join()
            results.append(sum(counts))
        print(f"  locked={locked!s:<5} allowed per run: {results}")


def main():
    if "--bench" in sys.argv:
        bench()
        return
    demo_boundary()
    demo_bucket()
    demo_retry_after()
    demo_simulation()
    demo_threads()
    demo_eviction()


if __name__ == "__main__":
    main()

Java

// Rate limiter: fixed window, sliding log, sliding window counter and token bucket
// behind one strategy interface, per-key state with per-key locks, idle-key eviction,
// and a 60-second traffic simulation that measures how far each one overshoots.
//
// Run: java RateLimiter.java           deterministic demos (same output as ratelimiter.py)
//      java RateLimiter.java --bench   timings and the unlocked race
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class RateLimiter {

    record Decision(boolean allowed, long remaining, long retryAfterMs) {
        @Override public String toString() {
            return allowed ? "ok, " + remaining + " left" : "429, retry in " + retryAfterMs + " ms";
        }
    }

    // ---------------- algorithms (Strategy) ----------------
    // Each algorithm is stateless config. Per-key state lives in a small array it creates.
    // Times are integer milliseconds passed in; nothing reads the wall clock.

    interface Algorithm {
        String name();
        Object newState();
        Decision acquire(Object state, long now);
        int size(Object state);
    }

    static final class FixedWindow implements Algorithm {
        final long limit, w;
        FixedWindow(long limit, long w) { this.limit = limit; this.w = w; }
        public String name() { return "fixed window"; }
        public Object newState() { return new long[]{0, 0}; }            // window start, count
        public Decision acquire(Object o, long now) {
            long[] s = (long[]) o;
            long start = now - now % w;
            if (start != s[0]) { s[0] = start; s[1] = 0; }
            if (s[1] < limit) { s[1]++; return new Decision(true, limit - s[1], 0); }
            return new Decision(false, 0, start + w - now);
        }
        public int size(Object o) { return 2; }
    }

    static final class SlidingLog implements Algorithm {
        final long limit, w;
        SlidingLog(long limit, long w) { this.limit = limit; this.w = w; }
        public String name() { return "sliding log"; }
        public Object newState() { return new ArrayDeque<Long>(); }      // timestamps of allowed requests
        @SuppressWarnings("unchecked")
        public Decision acquire(Object o, long now) {
            ArrayDeque<Long> s = (ArrayDeque<Long>) o;
            while (!s.isEmpty() && s.peekFirst() <= now - w) s.pollFirst();
            if (s.size() < limit) { s.addLast(now); return new Decision(true, limit - s.size(), 0); }
            return new Decision(false, 0, s.peekFirst() + w - now);
        }
        @SuppressWarnings("unchecked")
        public int size(Object o) { return ((ArrayDeque<Long>) o).size(); }
    }

    /** Weights the previous fixed window by how much of it still overlaps the last W ms. */
    static final class SlidingCounter implements Algorithm {
        final long limit, w;
        SlidingCounter(long limit, long w) { this.limit = limit; this.w = w; }
        public String name() { return "sliding counter"; }
        public Object newState() { return new long[]{0, 0, 0}; }         // window start, current, previous
        public Decision acquire(Object o, long now) {
            long[] s = (long[]) o;
            long start = now - now % w;
            if (start == s[0] + w) { s[2] = s[1]; s[1] = 0; s[0] = start; }
            else if (start != s[0]) { s[0] = start; s[1] = 0; s[2] = 0; }
            long e = now - start;
            // estimate = prev * (w - e) / w + curr; allow if estimate + 1 <= limit (integers only)
            if (s[2] * (w - e) + (s[1] + 1) * w <= limit * w) {
                s[1]++;
                long left = Math.floorDiv(limit * w - s[2] * (w - e) - s[1] * w, w);
                return new Decision(true, left, 0);
            }
            long spare = limit - s[1] - 1;
            if (spare >= 0) {                                            // fits later in this window, once prev decays
                long need = firstFit(s[2], spare, w);
                if (need < w) return new Decision(false, 0, need - e);
            }
            // otherwise wait for the next window, where today's count becomes "previous"
            return new Decision(false, 0, start + w - now + firstFit(s[1], limit - 1, w));
        }
        /** Smallest offset e in a window with prev * (w - e) <= spare * w. */
        static long firstFit(long prev, long spare, long w) {
            if (prev == 0) return 0;
            long need = Math.max(0, w - (spare * w) / prev);
            while (prev * (w - need) > spare * w) need++;
            return need;
        }
        public int size(Object o) { return 3; }
    }

    /** Tokens are stored in thousandths so refill stays exact integer arithmetic. */
    static final class TokenBucket implements Algorithm {
        final long cap, rate;                                            // rate in tokens/s = thousandths per ms
        TokenBucket(long cap, long perSecond) { this.cap = cap; this.rate = perSecond; }
        public String name() { return "token bucket"; }
        public Object newState() { return new long[]{cap * 1000, -1}; } // milli-tokens, last refill time
        public Decision acquire(Object o, long now) {
            long[] s = (long[]) o;
            if (s[1] >= 0 && now > s[1]) s[0] = Math.min(cap * 1000, s[0] + (now - s[1]) * rate);
            if (s[1] < 0 || now > s[1]) s[1] = now;
            if (s[0] >= 1000) { s[0] -= 1000; return new Decision(true, s[0] / 1000, 0); }
            if (rate == 0) return new Decision(false, 0, -1);
            return new Decision(false, 0, Math.floorDiv(-(1000 - s[0]), -rate));   // ceil((1000 - tokens) / rate)
        }
        public int size(Object o) { return 2; }
    }

    // ---------------- the limiter (Facade) ----------------

    static final class Entry {
        final Object state; long lastSeen;
        Entry(Object state, long now) { this.state = state; this.lastSeen = now; }
    }

    /** One algorithm, one state object and one lock per key. Keys never contend with each other. */
    static final class Limiter {
        final Algorithm algo; final boolean locked;
        private final ConcurrentHashMap<String, Entry> entries = new ConcurrentHashMap<>();
        Limiter(Algorithm a) { this(a, true); }
        Limiter(Algorithm a, boolean locked) { this.algo = a; this.locked = locked; }

        Decision tryAcquire(String key, long now) {
            Entry e = entries.computeIfAbsent(key, k -> new Entry(algo.newState(), now));
            if (!locked) { e.lastSeen = now; return algo.acquire(e.state, now); }
            synchronized (e) {
                e.lastSeen = Math.max(e.lastSeen, now);
                return algo.acquire(e.state, now);
            }
        }

        /** Drop keys not seen for idleMs. Safe only if idleMs >= the window or a full refill. */
        int evictIdle(long now, long idleMs) {
            int before = entries.size();
            entries.entrySet().removeIf(en -> { synchronized (en.getValue()) { return en.getValue().lastSeen <= now - idleMs; } });
            return before - entries.size();
        }
        int keys() { return entries.size(); }
        long storedInts() {
            long n = 0;
            for (Entry e : entries.values()) synchronized (e) { n += algo.size(e.state); }
            return n;
        }
    }

    static List<Algorithm> allAlgorithms(long limit, long w) {
        return List.of(new FixedWindow(limit, w), new SlidingLog(limit, w),
            new SlidingCounter(limit, w), new TokenBucket(limit, limit * 1000 / w));
    }

    // ---------------- demos ----------------

    static int maxInWindow(List<Long> times, long w) {
        int best = 0, i = 0;
        for (int j = 0; j < times.size(); j++) {
            while (times.get(i) <= times.get(j) - w) i++;
            best = Math.max(best, j - i + 1);
        }
        return best;
    }

    static void demoBoundary() {
        System.out.println("1) Limit 5 per second. 10 requests at t=900..990 ms and 10 at t=1000..1090 ms");
        List<Long> times = new ArrayList<>();
        for (int i = 0; i < 10; i++) times.add(900L + 10 * i);
        for (int i = 0; i < 10; i++) times.add(1000L + 10 * i);
        for (Algorithm a : allAlgorithms(5, 1000)) {
            Limiter rl = new Limiter(a);
            List<Long> ok = new ArrayList<>();
            for (long t : times) if (rl.tryAcquire("alice", t).allowed()) ok.add(t);
            System.out.printf("  %-16s allowed %2d, most in any 1000 ms: %2d, at %s%n", a.name(), ok.size(), maxInWindow(ok, 1000), ok);
        }
    }

    static void demoBucket() {
        System.out.println("\n2) Token bucket, capacity 10, refill 2/s: a burst of 14 at t=0, then one every 250 ms");
        Limiter rl = new Limiter(new TokenBucket(10, 2));
        int ok = 0; Decision last = null;
        for (int i = 0; i < 14; i++) { last = rl.tryAcquire("app-7", 0); if (last.allowed()) ok++; }
        System.out.println("  burst: " + ok + " allowed, then " + last);
        for (long t = 250; t <= 3000; t += 250) System.out.printf("  t=%4d: %s%n", t, rl.tryAcquire("app-7", t));
    }

    static void demoRetryAfter() {
        System.out.println("\n3) Retry-After: 5 requests at t=100..140, a 6th at t=150, then retry exactly when told");
        for (Algorithm a : allAlgorithms(5, 1000)) {
            long hint = 0; boolean early = false, onTime = false;
            for (int probe = -2; probe <= 0; probe++) {
                Limiter rl = new Limiter(a);
                for (long t = 100; t <= 140; t += 10) rl.tryAcquire("bob", t);
                Decision d = rl.tryAcquire("bob", 150);
                if (probe == -2) { hint = d.retryAfterMs(); continue; }
                boolean ok = rl.tryAcquire("bob", 150 + hint + probe).allowed();
                if (probe == -1) early = ok; else onTime = ok;
            }
            System.out.printf("  %-16s 429, retry in %4d ms; 1 ms early allowed: %-5s, on time allowed: %s%n",
                a.name(), hint, early ? "True" : "False", onTime ? "True" : "False");
        }
    }

    static final class Lcg {
        long x;
        Lcg(long seed) { x = seed; }
        long next(long bound) {
            x = x * 6364136223846793005L + 1442695040888963407L;
            return (x >>> 33) % bound;
        }
    }

    record Event(long t, String key) {}

    /** 60 s, 300 clients: 240 steady (about 3/s), 45 bursty (bursts of 8-15), 15 abusive (about 25/s). */
    static List<Event> makeTrace(long seed) {
        Lcg rng = new Lcg(seed);
        List<Event> ev = new ArrayList<>();
        for (int c = 0; c < 300; c++) {
            String key = String.format("c%03d", c);
            long t = rng.next(1000);
            if (c < 240) {
                while (t < 60_000) { ev.add(new Event(t, key)); t += 1 + rng.next(666); }
            } else if (c < 285) {
                while (t < 60_000) {
                    long n = 8 + rng.next(8);
                    for (int i = 0; i < n; i++) { ev.add(new Event(t, key)); t += rng.next(40); }
                    t += 2000 + rng.next(6000);
                }
            } else {
                while (t < 60_000) { ev.add(new Event(t, key)); t += 1 + rng.next(80); }
            }
        }
        ev.sort(Comparator.comparingLong(Event::t).thenComparing(Event::key));
        return ev;
    }

    static void demoSimulation() {
        List<Event> events = makeTrace(19);
        System.out.println("\n4) 60 s of traffic, 300 clients, " + events.size() + " requests, limit 5 per second per client");
        System.out.printf("  %-16s %7s %27s %9s %16s%n", "algorithm", "allowed", "clients over 5 in some 1 s", "worst 1 s", "peak ints stored");
        for (Algorithm a : allAlgorithms(5, 1000)) {
            Limiter rl = new Limiter(a);
            Map<String, List<Long>> allowed = new HashMap<>();
            long peak = 0;
            for (int i = 0; i < events.size(); i++) {
                Event e = events.get(i);
                if (rl.tryAcquire(e.key(), e.t()).allowed()) allowed.computeIfAbsent(e.key(), k -> new ArrayList<>()).add(e.t());
                if (i % 1000 == 0) peak = Math.max(peak, rl.storedInts());
            }
            int over = 0, worst = 0; long total = 0;
            for (List<Long> v : allowed.values()) {
                int m = maxInWindow(v, 1000);
                if (m > 5) over++;
                worst = Math.max(worst, m);
                total += v.size();
            }
            System.out.printf("  %-16s %7d %27d %9d %16d%n", a.name(), total, over, worst, peak);
        }
    }

    static void demoThreads() throws InterruptedException {
        System.out.println("\n5) 8 threads x 1,000 requests on one key, bucket of 100, clock frozen (no refill)");
        System.out.println("  allowed: " + race(new Limiter(new TokenBucket(100, 0)), 8, 1000) + " (with the per-key lock)");
    }

    static int race(Limiter rl, int threads, int each) throws InterruptedException {
        int[] counts = new int[threads];
        List<Thread> ts = new ArrayList<>();
        for (int n = 0; n < threads; n++) {
            int id = n;
            ts.add(new Thread(() -> { for (int i = 0; i < each; i++) if (rl.tryAcquire("shared", 5).allowed()) counts[id]++; }));
        }
        for (Thread t : ts) t.start();
        for (Thread t : ts) t.join();
        return Arrays.stream(counts).sum();
    }

    static void demoEviction() {
        System.out.println("\n6) Idle keys: 10,000 one-off clients, then a sweep");
        Limiter rl = new Limiter(new SlidingLog(5, 1000));
        for (int i = 0; i < 10_000; i++) rl.tryAcquire("ip-" + i, i);
        rl.tryAcquire("ip-regular", 10_400);
        System.out.println("  keys before: " + rl.keys() + ", stored ints: " + rl.storedInts());
        int gone = rl.evictIdle(11_000, 1000);
        System.out.println("  evicted " + gone + " keys idle for 1 s or more; keys left: " + rl.keys());
    }

    // ---------------- benchmarks ----------------

    static void bench() throws InterruptedException {
        System.out.println("bench: single thread, 10,000,000 calls over 1,000 keys (after warm-up)");
        String[] keys = new String[1000];
        for (int i = 0; i < 1000; i++) keys[i] = "k" + i;
        for (int round = 0; round < 2; round++) {
            for (Algorithm a : allAlgorithms(100, 1000)) {
                Limiter rl = new Limiter(a);
                long t0 = System.nanoTime();
                for (int i = 0; i < 10_000_000; i++) rl.tryAcquire(keys[i % 1000], i / 500);
                double dt = (System.nanoTime() - t0) / 1e9;
                if (round == 1) System.out.printf("  %-16s %5.2f s  (%.1fM calls/s)%n", a.name(), dt, 10 / dt);
            }
        }
        System.out.println("bench: 8 threads x 100,000 requests, one key, bucket of 1,000, frozen clock");
        for (boolean locked : new boolean[]{false, true}) {
            List<Integer> res = new ArrayList<>();
            for (int r = 0; r < 5; r++) res.add(race(new Limiter(new TokenBucket(1000, 0), locked), 8, 100_000));
            System.out.printf("  locked=%-5s allowed per run: %s%n", locked, res);
        }
    }

    public static void main(String[] args) throws Exception {
        if (Arrays.asList(args).contains("--bench")) { bench(); return; }
        demoBoundary();
        demoBucket();
        demoRetryAfter();
        demoSimulation();
        demoThreads();
        demoEviction();
    }
}

What it printed

1) Limit 5 per second. 10 requests at t=900..990 ms and 10 at t=1000..1090 ms
  fixed window     allowed 10, most in any 1000 ms: 10, at [900, 910, 920, 930, 940, 1000, 1010, 1020, 1030, 1040]
  sliding log      allowed  5, most in any 1000 ms:  5, at [900, 910, 920, 930, 940]
  sliding counter  allowed  5, most in any 1000 ms:  5, at [900, 910, 920, 930, 940]
  token bucket     allowed  5, most in any 1000 ms:  5, at [900, 910, 920, 930, 940]

2) Token bucket, capacity 10, refill 2/s: a burst of 14 at t=0, then one every 250 ms
  burst: 10 allowed, then 429, retry in 500 ms
  t= 250: 429, retry in 250 ms
  t= 500: ok, 0 left
  t= 750: 429, retry in 250 ms
  t=1000: ok, 0 left
  t=1250: 429, retry in 250 ms
  t=1500: ok, 0 left
  t=1750: 429, retry in 250 ms
  t=2000: ok, 0 left
  t=2250: 429, retry in 250 ms
  t=2500: ok, 0 left
  t=2750: 429, retry in 250 ms
  t=3000: ok, 0 left

3) Retry-After: 5 requests at t=100..140, a 6th at t=150, then retry exactly when told
  fixed window     429, retry in  850 ms; 1 ms early allowed: False, on time allowed: True
  sliding log      429, retry in  950 ms; 1 ms early allowed: False, on time allowed: True
  sliding counter  429, retry in 1050 ms; 1 ms early allowed: False, on time allowed: True
  token bucket     429, retry in  150 ms; 1 ms early allowed: False, on time allowed: True

4) 60 s of traffic, 300 clients, 71105 requests, limit 5 per second per client
  algorithm        allowed  clients over 5 in some 1 s worst 1 s peak ints stored
  fixed window       50019                         293        10              600
  sliding log        48444                           0         5             1172
  sliding counter    46892                         161         9              900
  token bucket       50399                         297         9              600

5) 8 threads x 1,000 requests on one key, bucket of 100, clock frozen (no refill)
  allowed: 100 (with the per-key lock)

6) Idle keys: 10,000 one-off clients, then a sweep
  keys before: 10001, stored ints: 10001
  evicted 10000 keys idle for 1 s or more; keys left: 1

Reading it:

  • Demo 1. The boundary burst. The fixed window lets 5 through at 900-940 ms and 5 more at 1000-1040 ms: 10 requests in 140 ms under a “5 per second” limit. The other three allow 5. The token bucket refuses the second group: by t=1090 it has refilled to 0.95 of a token, not quite one.
  • Demo 2. A bucket of 10 refilling at 2 a second absorbs a burst of 10 at once, refuses the next 4 with “retry in 500 ms” (one token takes 500 ms), and then allows exactly one request every 500 ms, refusing the ones in between with “retry in 250 ms”. The burst size and the sustained rate are separate knobs, which is the reason to choose a token bucket.
  • Demo 3. Four very different answers to “when can I try again”. The fixed window says 850 ms, the start of the next calendar second, at which point the client gets all 5 back at once. The sliding log says 950 ms, when the request from t=100 leaves the window. The sliding counter says 1,050 ms, because at the start of the next window the 5 requests from this window still count fully and have to decay to 4. The token bucket says 150 ms, the time to refill one token. In every case a retry 1 ms early is refused and a retry on time is allowed, so the hints are exact. A Retry-After that is too early makes well-behaved clients hammer you; one that is too late wastes their quota.
  • Demo 4. The table that matters, discussed next.
  • Demo 5. 8 threads, 8,000 attempts, 100 tokens, no refill: exactly 100 allowed.
  • Demo 6. 10,000 clients that each sent one request are gone after a sweep at t=11,000 with a 1-second idle limit; the client seen at t=10,400 stays.

What the simulated minute says

The trace has 300 clients for 60 seconds: 240 steady ones sending about 3 requests a second at random gaps, 45 that send bursts of 8 to 15 requests every few seconds, and 15 abusive ones at about 25 a second. 71,105 requests in all, the same limit of 5 a second for everyone.

AlgorithmAllowedClients that got more than 5 in some 1 s spanMost in any 1 s spanPeak integers stored
Fixed window50,01929310600
Sliding log48,444051,172
Sliding counter46,8921619900
Token bucket50,3992979600

What I take from it:

  • Only the sliding log enforces “5 in any second”. If that is the contract, for example an SMS provider that will block you at 6, it is the only correct choice here, and at a limit of 5 its memory cost (about 4 timestamps per active client) is nothing.
  • The token bucket is the most permissive by design. Capacity 5 plus 5 a second of refill allows up to about 10 in a rolling second, and 297 clients hit more than 5 at some point, including steady clients whose random gaps happened to bunch up. That is the point of a burst allowance. If you want a hard cap, lower the capacity; capacity 1 turns it into a strict pacer.
  • The sliding counter is wrong in both directions on bursty traffic. It let 161 clients exceed 5, with a worst case of 9, and it also allowed the fewest requests overall, partly because a burst early in the previous window still counts as 70% present when it has in fact already left. The usual argument for it, that it is almost exact, assumes requests are spread evenly. Bursty clients are exactly the ones you are limiting.
  • The fixed window’s worst case is 2× the limit, and it reached it. For a login form, where the goal is “not millions of guesses”, that is fine and it is the cheapest to run in Redis. For an expensive endpoint it is not.

My defaults: token bucket for a public API (clients understand “burst plus rate”, and it degrades gently), sliding log for small hard limits to third parties, fixed window in Redis for brute-force protection where 2× does not matter.

The benchmark numbers

MeasurementJava 21Python 3.13
Calls per second, one thread, 1,000 keys, fixed window28.5 M2.1 M
Sliding log28.6 M1.8 M
Sliding counter32.8 M1.5 M
Token bucket33.6 M1.7 M
8 threads racing for 1,000 tokens, no lock: allowed, 5 runs1,496 / 1,000 / 1,804 / 1,766 / 1,0001,000 every run
Same with the per-key lock1,000 every run1,000 every run

The algorithms cost about the same; at 30 to 35 ns a call in Java, the hash-map lookup is most of it. The choice between them is about the contract and the memory, not speed. In Python, the limiter costs 0.5 to 0.7 µs per request, which is small next to any web framework’s own overhead.

Where interviewers take it next

“Make it work across 20 servers.” The state moves to Redis. A fixed window is INCR key; EXPIRE key 1 in a pipeline, or SET key 0 EX 1 NX then INCR. A token bucket or sliding log needs a Lua script so the read, decision and write happen in one atomic step on the Redis server; doing GET, deciding in the app and then SET has the same race as the unlocked benchmark, across machines. Use Redis server time, not each app server’s clock. If Redis is down, decide whether to fail open (allow) or closed (refuse); for most APIs, open, with an alert.

“Per user and per IP and a global limit.” Check all of them, and only consume if all allow. The naive loop that calls try_acquire on each in turn takes a token from the per-user bucket and then gets refused by the global one, so a refused request still cost the user. Add a peek that reports without consuming, take the locks in a fixed order (global, then IP, then user), peek all, then commit all.

“Different limits for free and paid users.” Choose the algorithm and limits per key: a rules(key) → Algorithm lookup at entry creation. Because state is separate from the algorithm, a user who upgrades gets the new limit on their next window, or immediately if you drop their entry.

“Some requests are more expensive.” Add cost to acquire. Token bucket: take cost tokens. Fixed window and counter: add cost. Sliding log: store (time, cost) pairs and sum them, or store the timestamp cost times if costs are small.

“What status code and headers?” 429 Too Many Requests with Retry-After in seconds (rounded up, never down). Many APIs also send X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset; there is an IETF draft standardising RateLimit and RateLimit-Policy headers. The Decision object carries everything needed for them.

“The clock jumps backwards.” NTP can step the wall clock. Use a monotonic clock for in-process limiters. The token bucket here ignores time going backwards (now > last before refilling), so a step back cannot mint tokens.

Mistakes worth avoiding

  • Picking an algorithm before agreeing what “5 per second” means. Ask whether bursts are acceptable, and whether “per second” means calendar seconds or any 1,000 ms.
  • Reading the wall clock inside the algorithm. It makes tests depend on timing and makes a backwards NTP step a bug.
  • Floats for tokens. Drift between languages and over long runs; store thousandths.
  • A check and an update in two steps without a lock, in memory or in Redis.
  • One global lock. Correct, and it serialises every client behind one mutex.
  • Never evicting. Memory grows with every IP that ever visited.
  • Evicting faster than the window. A pause becomes a reset.
  • A Retry-After you never tested. The sliding counter’s obvious answer, “the next window”, is wrong.
  • Consuming from the first of several limits when a later one refuses.

Key takeaways

  • The four algorithms enforce four different contracts. On the same trace, “5 per second” let 0, 161, 293 or 297 of 300 clients exceed 5 in some second.
  • Keep the algorithm (shared, immutable config) separate from the per-key state; make the algorithm a strategy.
  • Pass time in as integer milliseconds and use integer arithmetic; both make results exact and testable.
  • Lock per key. Without it, Java let through up to 80% more requests than the bucket held.
  • Evict idle keys, but only after at least a full window.
  • Return a retry time that you have tested: 1 ms early refused, on time allowed.

Exercises

  1. Add cost to acquire for all four algorithms. For the sliding log, compare storing (time, cost) pairs with repeating timestamps, for costs of 1 to 100.
  2. Implement CompositeLimiter(limiters) that allows only if all allow and consumes from none when any refuses. Test it with a per-user limit of 5/s and a global limit of 20/s and 10 users.
  3. Run the simulation with token bucket capacity 1 and rate 5. How many clients exceed 5 in a second now, and how many requests are allowed compared with capacity 5?
  4. Write the fixed window as a Redis Lua script (INCR, set PEXPIRE on the first increment, return the count and the TTL). Why is INCR followed by a separate EXPIRE from the application unsafe if the app crashes between the two?

Quiz

  1. A fixed window allows 100 requests per minute. What is the most a client can send in any 60-second span, and when?
  2. Why does the token bucket store thousandths of a token instead of a float?
  3. At 300 ms into a one-second window, the previous window had 8 requests and the current one has 1. Limit 5. Does the sliding counter allow a request?
  4. Why is the lock per key and not one lock for the whole limiter?
  5. Eviction removes keys idle for 200 ms, and the limit is 10 per minute on a fixed window. What can an attacker do?
Show answers
  1. 200: 100 at the end of one window and 100 at the start of the next, within a few milliseconds of each other.
  2. Integer arithmetic is exact, so refills never drift and the same inputs give the same answer in every language. A float bucket accumulates rounding error over millions of refills, and Python and Java can disagree about whether 0.9999999 tokens is enough.
  3. Estimate = 8 × 700/1000 + 1 = 6.6. Adding one more gives 7.6, above 5, so it is refused. (The integer check: 8 × 700 + 2 × 1000 = 7,600 > 5,000.)
  4. Different clients never need to see each other’s state, so they should not wait for each other. The only race is between two requests from the same client, and a per-key lock serialises exactly those.
  5. Send 10 requests, pause 200 ms so the entry is evicted, and get a fresh window with 10 more: about 10 requests every 200 ms instead of 10 a minute. The idle limit has to be at least the window.

Done with this lesson?

Marking it complete updates the sidebar, the course page and the Continue button.