High-Throughput Token-Bucket Rate Limiter with Lazy Refill

Hard · System Design · Software Engineer · Technical Screen

Prompt

Architect and implement an HTTP API rate limiter that restricts each caller (keyed by API token or user ID) to N requests per T seconds. Begin with an in-memory design inside one server process that keeps per-request latency in the microsecond range, stays compact in RAM across millions of distinct callers under heavy throughput, and extends cleanly to a multi-node cluster later.

Structure your design around four milestones:

  1. Sliding-window baseline: Explain how to build an exact sliding-window limiter, specifying the data stored per caller, the allow/reject check at arrival timestamp now, and the time and space complexity.
  2. Failure modes at high scale: Analyze what happens to memory consumption, allocations, and tail latency in the sliding-window design when millions of callers each send heavy traffic.
  3. Token bucket with lazy refill: Re-architect the limiter around a token bucket (capacity, refill_rate, and per-request token spend) storing O(1) state per caller (current_tokens and last_refill_time). Derive the exact lazy refill math that computes accrued tokens on demand at request timestamp now without background timer threads, and explain how this eliminates the sliding window's memory and latency bottlenecks.
  4. Production hardening & cluster scale-out: Address thread-safe concurrent access to a caller's state, lossless eviction of idle callers so memory stays bounded, and extending the limiter across multiple stateless API servers via a shared store like Redis.

Scope & Expectations

  • Algorithmic comparison & memory sizing: Quantify the memory and latency gap between O(N) sliding-window logs and O(1) token buckets, including burst vs. strict rolling-window trade-offs.
  • Exact lazy-refill mechanics: Present clear reference code and trace how capacity clamping, fractional token preservation on rejected calls, and monotonic clocks prevent starvation or overflow.
  • Concurrency, eviction, & distributed extension: Cover lock striping (or atomic updates), O(1) LRU/TTL cleanup of inactive buckets, and single-round-trip atomic execution in Redis.

Step-by-step walkthrough

  1. Clarify requirements and exact rate-limit semantics

    Before choosing data structures, pin down what "at most N requests per T seconds" means in production and where the rate limiter sits. A rate limiter is a gatekeeper component that caps how many requests each caller can make over a time period so one noisy or abusive client cannot overload the service.

    Functional requirements

    • Caller key (client_key): Enforce one independent quota per API token when authenticated, falling back to user_id or source IP address on public routes.
    • Quota policy: Permit up to N requests per T-second interval (such as N = 1,000 requests over T = 60 seconds), supporting distinct (N, T) plan tiers (free vs. enterprise) and optional per-route cost weights (such as cost = 1 for a lightweight read and cost = 5 for a bulk export).
    • Actionable rejection headers: Admitted calls proceed directly to route handlers, whereas throttled calls return HTTP 429 Too Many Requests with Retry-After (whole seconds until sufficient tokens accrue) so well-behaved SDKs back off cleanly.

    Non-functional requirements

    • Ultra-low latency: The check runs on every incoming HTTP request, so the single-instance version must finish in microseconds purely in memory, with zero disk or network I/O.
    • Bounded, small memory: Millions of distinct clients must fit comfortably inside one server process, even when N is large.
    • Thread safety: Hundreds of worker threads or coroutines may check and update the same client's state concurrently without over-admitting requests.
    • Distributed extensibility: The core state transition should be clean enough to move into a shared store like Redis when the service scales from one server to dozens.

    Crucial semantics question to state upfront: Does the product need a strict rolling cap ("never more than N requests in any T-second interval") or a sustained average rate with bounded bursts ("N / T requests per second on average, allowing short bursts up to N")? Answering that question explains the fundamental trade-off between a sliding window and a token bucket.

  2. Back-of-the-envelope numbers

    Let's size a realistic single-instance API server to see why memory layout—not arithmetic speed—drives the design.

    Workload assumptions (single API server instance)
      Tier rule                 N = 1,000 requests per T = 60 s
      Active clients            1,000,000 distinct keys active within the last 60 s
      Daily distinct clients    10,000,000 keys seen across 24 hours
      Throughput                50,000 requests/s hitting this instance
    
    Approach A: Sliding-window log (store every accepted timestamp per client)
      Worst-case entries        1,000,000 active clients x 1,000 timestamps = 1,000,000,000 timestamps
      Raw 8-byte int64/float64  1e9 x 8 B = 8 GB of raw timestamps alone
      CPython deque of floats   24 B float object + ~8 B deque pointer = ~32 B per timestamp
                                1e9 x 32 B = ~32 GB of RAM (crashes a standard server/container -> OOM)
    
    Approach B: Token bucket (store just 2 numbers per client)
      Raw payload per client    current_tokens (8 B) + last_refill_time (8 B) = 16 B
      1,000,000 active clients  16 MB raw payload (~220 MB in CPython with dict + __slots__ overhead)
      10,000,000 daily clients  160 MB raw payload (~2.2 GB in CPython if idle clients are never evicted)
    
    CPU cost per request check
      1 hash-table lookup + 4 arithmetic ops ~ 0.5-1.0 microseconds in Python (~50 ns in Go/Rust/Java)
      50,000 req/s x 1 microsecond = 0.05 CPU-seconds/s (~5% of a single CPU core)
    

    Three design lessons jump right out of this math:

    1. Per-client state must be O(1), not O(N). At N = 1,000, storing two 8-byte numbers (16 B) instead of 1,000 timestamps (8,000 B) cuts raw per-client payload by 500x.
    2. Idle client eviction is mandatory even with a token bucket. Keeping all 10 million daily clients forever still consumes gigabytes of hash-table overhead.
    3. Arithmetic is tiny; lock contention and memory churn are the real bottlenecks.
  3. API and high-level architecture

    Keep the limiter behind a small, storage-agnostic interface inside an HTTP middleware (a wrapper that runs before business logic handlers). Separating the pure math from where state is stored makes moving from in-memory maps to Redis painless later.

    Method signature:
      allow(client_key: str, cost: int = 1) -> Decision
    
    Decision fields:
      allowed: bool          # True -> pass to route handler; False -> return HTTP 429
      remaining: int         # Whole tokens left after this decision (for RateLimit-Remaining)
      retry_after_s: float   # Seconds until `cost` tokens are available (0.0 if allowed)
    
    +------------------------------ Single API Server Process ------------------------------+
    |                                                                                       |
    |  HTTP Request --> [Auth / Key Extractor] --> [Rate-Limit Middleware] --> API Handler   |
    |                                                       |                               |
    |                                        limiter.allow(client_key, cost=1)              |
    |                                                       |                               |
    |                                                       v                               |
    |                           +-----------------------------------------------+           |
    |                           | ShardedTokenBucketLimiter                     |           |
    |                           |  - tier_config: plan -> (capacity, rate)      |           |
    |                           |  - shards[0 .. 63] (hash(client_key) % 64):   |           |
    |                           |      * mutex lock                             |           |
    |                           |      * OrderedDict: key -> {tokens, last_ts}  |           |
    |                           |        (front = oldest idle client for LRU)   |           |
    |                           +-----------------------------------------------+           |
    |                                                       |                               |
    |                                    if not allowed: HTTP 429 + Retry-After: ceil(s)    |
    +---------------------------------------------------------------------------------------+
    
    Later (multi-server fleet): replace the in-process shard lookup with one atomic Redis
    Lua script per request against a Redis Cluster shard keyed by `rl:{client_key}`.
    

    Notice two clean boundaries:

    • Tier parameters (capacity, refill_rate) live in a small read-only config table, not inside each client's state, saving 16 bytes on every single client entry.
    • Rejected requests stop at the middleware before JSON body parsing or database queries run, so rejecting an abusive flood stays orders of magnitude cheaper than serving it.
  4. Baseline design: sliding-window log

    To see why we need a token bucket, let's first build the exact sliding-window log baseline. A deque (double-ended queue) lets us append new items to the right end and pop expired items from the left end in O(1) time per operation.

    • Data stored per client: logs[client_id] is a deque of accepted request timestamps sorted from oldest to newest.
    • Allow/reject rule at timestamp now: The active rolling window is (now - T, now].
      1. While the oldest timestamp at log[0] satisfies log[0] <= now - T, pop it from the left—it has aged out of the T-second window.
      2. If len(log) < N, append now to the right and allow the request.
      3. Otherwise reject the request without appending now (if you logged rejected attempts, a client retrying once per second would keep extending its own lockout forever!).

    Let's trace N = 3 requests per T = 12 seconds:

    now     window (now-12, now]   expired popped   deque before check   len < 3?   decision   deque after
    2.0     (-10.0, 2.0]           none             []                   True       ALLOW      [2.0]
    5.0     ( -7.0, 5.0]           none             [2.0]                True       ALLOW      [2.0, 5.0]
    9.0     ( -3.0, 9.0]           none             [2.0, 5.0]           True       ALLOW      [2.0, 5.0, 9.0]
    11.0    ( -1.0, 11.0]          none             [2.0, 5.0, 9.0]      False      REJECT     [2.0, 5.0, 9.0]
    14.0    (  2.0, 14.0]          pop 2.0 (<= 2.0) [5.0, 9.0]           True       ALLOW      [5.0, 9.0, 14.0]
    
    from collections import deque
    
    
    class SlidingWindowLogLimiter:
        def __init__(self, max_requests: int, window_seconds: float):
            self.max_requests = max_requests
            self.window_seconds = window_seconds
            # Per-client state: client_id -> deque of accepted timestamps (oldest -> newest)
            self.client_logs = {}
    
        def allow(self, client_id: str, now: float) -> bool:
            log = self.client_logs.get(client_id)
            if log is None:
                log = deque()
                self.client_logs[client_id] = log
    
            # Evict timestamps at or before (now - T) because the active window is (now - T, now].
            window_start = now - self.window_seconds
            while log and log[0] <= window_start:
                log.popleft()
    
            # Admit if under quota; never record rejected timestamps.
            if len(log) < self.max_requests:
                log.append(now)
                return True
            return False
    
    • Time complexity: Amortized O(1) per request—every accepted timestamp is appended once and popped once across its lifetime, though a single call after a burst expires can pop up to N timestamps (O(N) worst-case latency spike).
    • Space complexity: O(N) per active client, or O(C * N) across C active clients.
  5. Why the sliding window breaks at scale

    When traffic grows to millions of clients sending tens of thousands of requests per second, the sliding-window log breaks down in four distinct ways:

    1. Memory scales with quota size N, punishing your highest-tier customers. For 1M active clients with N = 1,000, timestamps alone take 8 GB packed (~32 GB in Python). Raising an enterprise tier to N = 10,000 multiplies RAM usage 10x even for the exact same number of clients.
    2. Constant heap allocation and garbage-collection churn. Every allowed request allocates a node/float and later frees it—50,000 allocations and deallocations per second right on the hot path, causing garbage-collection pauses.
    3. Spiky tail latency under locks. If a client bursts 1,000 requests at t = 0 and sends 1 request at t = 61, that single call must pop 1,000 items while holding the lock, stalling concurrent requests.
    4. Poor fit for distributed storage. Porting a sliding log to Redis requires one sorted set (ZSET) per client (ZREMRANGEBYSCORE + ZCARD + ZADD), which takes O(log N) time per request and still consumes gigabytes of expensive Redis RAM.

    What about simpler counter approximations? A fixed-window counter (one integer per 60 s clock bucket, like 12:00:00–12:00:59) uses O(1) space, but allows 2N requests instantaneously across a boundary (N at 12:00:59.9 and N at 12:01:00.0). A sliding-window counter blends the previous and current fixed windows in O(1) space, which is a reasonable approximation, but the token bucket gives an exact physical model, continuous smooth refill, explicit burst control, and natural variable-cost support in O(1) time and space.

  6. Improved design: token bucket with lazy refill

    Conceptual model. Picture each client having a small bucket that holds at most capacity tokens. Tokens drip into the bucket continuously at refill_rate tokens per second (for "N requests per T seconds", set capacity = N and refill_rate = N / T), and any tokens above capacity overflow and are discarded. When a request of cost arrives: - If the bucket holds at least cost tokens, remove cost tokens and allow the request. - Otherwise leave the remaining tokens untouched and reject the request.

    Exact per-client state (O(1) memory—just two numbers): - current_tokens: how many tokens were in the bucket after the client's most recent check. - last_refill_time: timestamp of that check from a monotonic clock (time.monotonic()), a clock guaranteed to move only forward since process start so NTP wall-clock jumps cannot delete or fabricate tokens.

    How lazy refill works. Running a background timer thread to add tokens to 1,000,000 buckets every second would waste O(C) CPU touching 990,000 idle callers. Instead, because tokens drip at a constant linear rate and stop at capacity, we leave idle buckets untouched and catch up on the math lazily on demand at arrival timestamp now:

    1. elapsed          = max(0.0, now - last_refill_time)
    2. earned_tokens    = elapsed * refill_rate
    3. current_tokens   = min(capacity, current_tokens + earned_tokens)
    4. last_refill_time = now
    5. if current_tokens >= cost:
           current_tokens -= cost  --> ALLOW
       else:
           retry_after_s = (cost - current_tokens) / refill_rate  --> REJECT
    

    Why is lazy refill 100% equivalent to a continuous drip? Because min(capacity, ...) clips overflow identically whether no one looked at the bucket for 1 millisecond or 3 hours! Let's trace capacity = 6, refill_rate = 2.0 tokens/s (6 req / 3 s), cost = 1:

    now (s)  event                     elapsed  min(6, tokens + elapsed * 2.0)   decision  tokens_after
    0.0      new caller (starts full)  0.0      6.0                              ALLOW     5.0
    0.0      5 more burst requests     0.0      5.0 -> ... -> 1.0                ALLOW x5  0.0
    0.0      7th burst request         0.0      0.0 (< 1)                        REJECT    0.0 (retry in 0.5 s)
    0.2      early retry               0.2      min(6, 0.0 + 0.4) = 0.4          REJECT    0.4 (retry in 0.3 s)
    0.5      retry 0.3 s later         0.3      min(6, 0.4 + 0.6) = 1.0          ALLOW     0.0
    20.0     request after 19.5 s idle 19.5     min(6, 0.0 + 39.0) = 6.0         ALLOW     5.0 (capped at 6!)
    

    Notice now = 0.2 and now = 0.5: saving current_tokens = 0.4 and last_refill_time = 0.2 on the rejected request means 0.3 s later it adds 0.6 to reach 1.0—splitting elapsed time across partial steps gives the exact same result!

    import math
    
    
    class BucketState:
        # __slots__ avoids allocating a per-instance __dict__, cutting Python object memory by ~60%.
        __slots__ = ("current_tokens", "last_refill_time")
    
        def __init__(self, current_tokens: float, last_refill_time: float):
            self.current_tokens = current_tokens
            self.last_refill_time = last_refill_time
    
    
    class TokenBucketLimiter:
        def __init__(self, capacity: float, refill_rate: float):
            if capacity <= 0 or refill_rate <= 0:
                raise ValueError("capacity and refill_rate must be positive")
            self.capacity = capacity          # Max burst size (e.g., N)
            self.refill_rate = refill_rate    # Tokens added per second (e.g., N / T)
            self.buckets = {}                 # client_id -> BucketState
    
        def _lazy_refill(self, bucket: BucketState, now: float) -> None:
            # Guard against non-positive elapsed time so out-of-order timestamps never subtract tokens.
            elapsed = now - bucket.last_refill_time
            if elapsed > 0.0:
                refilled = bucket.current_tokens + elapsed * self.refill_rate
                bucket.current_tokens = min(self.capacity, refilled)
                bucket.last_refill_time = now
    
        def allow(self, client_id: str, now: float, cost: float = 1.0) -> tuple:
            """Return (allowed, remaining_whole_tokens, retry_after_seconds)."""
            if cost > self.capacity:
                # A request costing more than bucket capacity can never succeed.
                return (False, 0, math.inf)
    
            bucket = self.buckets.get(client_id)
            if bucket is None:
                # Unseen clients start with a full bucket.
                bucket = BucketState(self.capacity, now)
                self.buckets[client_id] = bucket
            else:
                self._lazy_refill(bucket, now)
    
            if bucket.current_tokens >= cost:
                bucket.current_tokens -= cost
                return (True, int(bucket.current_tokens), 0.0)
    
            missing_tokens = cost - bucket.current_tokens
            retry_after_s = missing_tokens / self.refill_rate
            return (False, int(bucket.current_tokens), retry_after_s)
    

    Precision detail (floats vs. exact integers): IEEE-754 floats can round 10 * 0.1 to 0.9999999999999999 and reject a boundary request. If you switch to integers, be careful: naive integer division (elapsed_ns * rate) // 10^9 combined with last_refill_ns = now_ns loses remainder nanoseconds if a client retries faster than 1 token-unit! To get exact, remainder-free integer math for N requests per T_ns nanoseconds, define 1 token = T_ns integer units: capacity_units = N * T_ns, each nanosecond adds elapsed_ns * N units (pure integer multiplication, zero division!), and each request subtracts cost * T_ns units.

    Explicit burst trade-off: With capacity = N and refill_rate = N / T, a client starting full can spend N tokens immediately at t = 0 and earn another N tokens across (0, T], admitting up to 2N requests in a single T-second window (never more, and strictly N / T long-run average). If downstream services can only absorb smaller spikes, keep refill_rate = N / T and lower capacity (for example, capacity = 50 instead of 1,000).

  7. Concurrency: keeping per-client updates atomic

    Why isn't the single-threaded TokenBucketLimiter safe in a multi-threaded web server? Because checking a bucket is a read-modify-write sequence. Even in Python (where the GIL switches threads between bytecode instructions), two threads handling requests from the same client_id can interleave:

    Initial state for client "k_1": current_tokens = 1.0
    
    Thread A (request 1)                     Thread B (request 2)
    ---------------------------------------  ---------------------------------------
    reads current_tokens -> sees 1.0
                                             reads current_tokens -> ALSO sees 1.0!
    checks 1.0 >= 1.0 -> True               checks 1.0 >= 1.0 -> True
    writes current_tokens = 0.0 -> ALLOW     writes current_tokens = 0.0 -> ALLOW  (2 requests passed on 1 token!)
    

    Let's compare concurrency strategies from simplest to highest throughput:

    • Single global mutex: Wrap allow() in one threading.Lock(). Simple and correct, and at 50,000 req/s × 1 µs = 5% lock utilization it works initially, but across 32+ CPU cores every unrelated client queues behind one lock.
    • Lock striping / sharded maps (recommended balance): Partition the hash map into S = 64 (or 256) independent shards using hash(client_id) % S. Each shard owns its own Lock and bucket dictionary. Two requests contend only if they hash to the same shard (1/64 chance), eliminating cross-core contention in Go/Java/Rust/free-threaded Python with minimal code.
    • Lock-free Compare-And-Swap (CAS): Pack a 32-bit fixed-point token count and a 32-bit millisecond timestamp into one 64-bit atomic integer (AtomicU64). Threads loop on compare_exchange with zero kernel locks, at the cost of handling 49-day timestamp wrap-around and separate hash-map insertion synchronization.

    Read now = time.monotonic() inside the shard lock so threads always process timestamps in non-decreasing order.

  8. Evicting inactive clients without losing state

    Even at ~220 bytes per client in Python, 10 million one-off clients per day would grow memory by gigabytes every day if we never clean up inactive entries.

    The lossless eviction insight: How long does it take a completely empty bucket (0 tokens) to refill all the way back to capacity?

    idle_ttl = capacity / refill_rate     (for capacity = N and refill_rate = N / T, idle_ttl = T seconds!)
    

    Once a client has been silent for at least idle_ttl seconds, its bucket is guaranteed to be 100% full—which is the exact same state a brand-new client gets (BucketState(capacity, now))! Deleting any bucket with now - last_refill_time >= idle_ttl therefore loses zero rate-limit accuracy.

    To evict in amortized O(1) time without background full-table scans, store each shard's buckets in an LRU (Least Recently Used) ordered map (collections.OrderedDict):

    1. Whenever client_id makes a request, update last_refill_time = now and call move_to_end(client_id), keeping every shard's entries sorted from oldest last_refill_time at the front to newest at the back.
    2. Inside allow(), peek at the front entry. While now - oldest.last_refill_time >= idle_ttl (up to a small cap like max_evictions = 8 so one request never pauses to delete 100,000 keys at once), delete the front entry. Stop immediately at the first entry with now - oldest.last_refill_time < idle_ttl, because every entry behind it is even newer!
    3. Add a hard max_keys_per_shard safety cap against a bot rotating millions of spoofed IPs within T seconds: if full, drop the oldest LRU entry so process memory can never exceed its ceiling.
    import threading
    import time
    from collections import OrderedDict
    
    
    class Shard:
        def __init__(self):
            self.lock = threading.Lock()
            # OrderedDict maintains access order: front = oldest last_refill_time, back = newest.
            self.buckets = OrderedDict()
    
    
    class ShardedTokenBucketLimiter:
        def __init__(
            self,
            capacity: float,
            refill_rate: float,
            num_shards: int = 64,
            max_keys_per_shard: int = 50_000,
        ):
            self.capacity = capacity
            self.refill_rate = refill_rate
            # Any bucket idle for >= idle_ttl seconds has refilled to `capacity` (identical to a new client).
            self.idle_ttl = capacity / refill_rate
            self.max_keys_per_shard = max_keys_per_shard
            self.shards = [Shard() for _ in range(num_shards)]
    
        def _evict_expired(self, shard: Shard, now: float, max_steps: int = 8) -> None:
            # Pop up to `max_steps` idle buckets from the front so per-request latency stays O(1).
            for _ in range(max_steps):
                if not shard.buckets:
                    return
                oldest_key = next(iter(shard.buckets))
                oldest_bucket = shard.buckets[oldest_key]
                if now - oldest_bucket.last_refill_time < self.idle_ttl:
                    # Because entries are ordered by access time, everything behind `oldest_key` is still active.
                    return
                del shard.buckets[oldest_key]
    
        def allow(self, client_id: str, cost: float = 1.0) -> bool:
            if cost > self.capacity:
                return False
    
            shard = self.shards[hash(client_id) % len(self.shards)]
            with shard.lock:
                now = time.monotonic()
                self._evict_expired(shard, now)
    
                bucket = shard.buckets.get(client_id)
                if bucket is None:
                    # Enforce hard memory cap under spoofed-key floods by dropping the least-recently-used key.
                    if len(shard.buckets) >= self.max_keys_per_shard:
                        shard.buckets.popitem(last=False)
                    bucket = BucketState(self.capacity, now)
                    shard.buckets[client_id] = bucket
                else:
                    elapsed = now - bucket.last_refill_time
                    if elapsed > 0.0:
                        bucket.current_tokens = min(
                            self.capacity, bucket.current_tokens + elapsed * self.refill_rate
                        )
                        bucket.last_refill_time = now
                    shard.buckets.move_to_end(client_id)
    
                if bucket.current_tokens >= cost:
                    bucket.current_tokens -= cost
                    return True
                return False
    
  9. Scaling to multiple servers, failure handling, and trade-off summary

    Once we run K = 20 stateless API servers behind a round-robin load balancer, purely local buckets let a client consume 20 * N requests! Three ways to scale out:

    • Sticky load-balancer routing (consistent-hash client_key to one server): Keeps 1 µs local latency, but server deploys/crashes reset buckets and one abusive key overloads a single API host.
    • Static N / K split per server: Zero network calls, but uneven load-balancer routing causes false 429 rejections long before a client actually reaches N.
    • Shared Redis Cluster + atomic Lua script (industry standard): Store {tokens, last_ms} in a Redis hash keyed by rl:{client_key} and run the entire read-refill-consume-expire sequence inside one server-side Lua script (EVALSHA). Because a Redis shard executes Lua scripts single-threaded and atomically, zero distributed locks are needed, and PEXPIRE key ceil(idle_ttl_ms) gives automatic lossless eviction for free! Use Redis server time (redis.call("TIME")) inside the script so clock skew across API servers cannot distort elapsed.
    API Server 1 --\                                     /--> Redis Shard 1 (slots 0..5460)
    API Server 2 --->-- EVALSHA token_bucket(key, cost) -----> Redis Shard 2 (slots 5461..10922)
    API Server K --/     (~0.5 ms intra-DC round trip)   \--> Redis Shard 3 (slots 10923..16383)
    

    Failure modes and resilience: - Redis outage or latency spike: Set a strict 5 ms timeout plus a circuit breaker. For general APIs, fail open to the local in-memory ShardedTokenBucketLimiter configured at N / K (protecting API availability while still blocking massive floods); for sensitive endpoints like /login or /password-reset, fail closed or enforce a strict local cap. - Hot keys: If one enterprise key sends 100,000 req/s, it can saturate its single Redis shard. Add a local token lease: each API server leases batches of B = 50 tokens from Redis and spends them locally in memory, cutting Redis traffic by 50x.

    Final comparison

    Property             Sliding-window log        Sliding-window counter     Token bucket (lazy refill)
    Per-client memory    O(N) timestamps (~8 KB)   O(1) (2 counts + window)   O(1) (2 numbers = 16 B)
    Per-request time     Amortized O(1), worst O(N) O(1)                      Strict O(1)
    Window accuracy      Exact: <= N in every T    Approximate overlap        Exact avg N/T; burst <= capacity
                                                                              (up to capacity + N in one T)
    Idle background CPU  None                      None                       None (lazy math on arrival)
    Redis extension      ZSET: O(log N), high RAM  2 keys + INCR + EXPIRE     1 Hash + Lua + PEXPIRE: O(1)
    

Intuition & how it works

Imagine an amusement park restricting each visitor to 6 rides per 3 minutes. One obvious way is to hire an attendant with a giant notebook who writes down the exact timestamp of every single ride each visitor takes, and before letting someone board, crosses out timestamps older than 3 minutes and counts how many lines remain—that is a sliding-window log (an exact rate-limiting algorithm that stores every accepted request's timestamp in a queue per client). Now imagine a much lighter system: every visitor gets a small pouch (token bucket, a fixed-capacity container that refills at a constant rate and spends tokens on each request) that holds at most 6 tokens and earns 2 new tokens every minute. Better yet, nobody walks around the park dropping tokens into a million empty pouches every minute! Instead, the pouch simply has two numbers printed on a tag—current_tokens and last_refill_time—and when a visitor walks up at now, the attendant checks a monotonic clock (a timer guaranteed to move only forward regardless of system wall-clock adjustments), calculates elapsed = now - last_refill_time, adds elapsed * refill_rate capped at capacity, and checks if enough tokens exist. That on-demand catch-up calculation is called lazy refill (computing accumulated tokens mathematically at arrival time rather than running a periodic background timer).

Why do the naive approaches fall short at scale? Storing every accepted timestamp in a sliding-window log means memory grows with clients * N: 1 million active callers with a quota of N = 1,000 requests hold up to 1 billion timestamps (8 GB of raw 64-bit numbers, or ~32 GB of Python objects), while popping hundreds of expired entries at once creates spiky tail latency. Conversely, implementing a token bucket with a background cron/timer thread that loops over 1 million buckets every second wastes CPU updating 990,000 idle callers that are not sending traffic. Lazy refill + LRU (Least Recently Used) idle eviction (keeping callers ordered by last access so buckets idle long enough to refill completely can be discarded in O(1) time) keeps per-request work strictly O(1) and memory tiny (16 bytes of raw payload per active caller).

Let's trace a compact bucket with capacity = 6 tokens (N = 6), refill_rate = 2.0 tokens/second (T = 3 s), and cost = 1 per request:

Arrival time   Elapsed since last   Lazy refill: min(6, tokens + elapsed * 2)   Decision & tokens left
t = 0.0 s      0.0 s (new caller)   starts full at 6.0                          ALLOW  -> 5.0 left
t = 0.0 s      0.0 s (5 more hits)  5.0 -> 4.0 -> 3.0 -> 2.0 -> 1.0             ALLOW  -> 0.0 left
t = 0.2 s      0.2 s                min(6, 0.0 + 0.4) = 0.4 (< 1.0 needed)      REJECT -> 0.4 left (Retry-After: 1s)
t = 0.5 s      0.3 s                min(6, 0.4 + 0.6) = 1.0 (>= 1.0 needed)     ALLOW  -> 0.0 left
t = 20.0 s     19.5 s (long pause)  min(6, 0.0 + 39.0) = 6.0 (capped at 6!)     ALLOW  -> 5.0 left

Key trade-offs

  • Strict rolling-window cap vs. O(1) memory and burst tolerance. A sliding-window log guarantees at most N requests in every T-second interval, but costs O(N) memory per caller. A token bucket with capacity = N and refill_rate = N / T uses O(1) memory (2 numbers), enforces an exact long-run average of N / T, and absorbs legitimate parallel requests—at the price of allowing up to capacity + refill_rate * T = 2N requests inside a single T-second window if a caller starts with a full bucket. Shrinking capacity smooths bursts at the cost of rejecting legitimate parallel page-load calls.
  • Lazy refill vs. timer-driven background refill. Lazy refill touches zero idle callers, needs no background threads, and has continuous sub-millisecond precision because min(capacity, current_tokens + elapsed * refill_rate) matches a continuous drip at every instant. A background refill job burns O(clients) CPU every tick and suffers coarse tick-boundary jumps.
  • Floating-point math vs. exact integer units. Floats are concise for single-node prototypes, but binary rounding (10 * 0.1 == 0.9999999999999999) can falsely reject an exact-boundary request. Expressing 1 token as T_ns integer units (capacity = N * T_ns, adding elapsed_ns * N per check) makes every update exact deterministic integer arithmetic with zero division remainder loss.
  • Lock granularity (1 global lock vs. 64 striped shard locks vs. lock-free CAS). A single global lock serializes all cores; lock striping (hashing keys across 64 independent mutexes and maps) eliminates almost all cross-thread contention in ~15 lines of code; Compare-And-Swap (CAS) (an atomic CPU instruction that updates a 64-bit word only if no other thread modified it first) avoids locks altogether but complicates timestamp wrap-around and map resizing.
  • Lossless TTL eviction vs. hard memory bound. Evicting callers idle for >= capacity / refill_rate seconds is 100% lossless because their buckets have already refilled to capacity, matching a brand-new entry. Adding a hard max_keys_per_shard LRU cap bounds RAM during spoofed-IP attacks, trading slight leniency (evicted active keys get a fresh bucket) for guaranteed server survival.
  • In-process state vs. shared Redis Cluster. Local memory checks take < 1 µs with zero network failure modes, whereas a shared Redis atomic Lua script (a short script executed single-threaded inside Redis so read, refill, and write cannot interleave) enforces a single global limit across K servers at the cost of ~0.5 ms intra-datacenter latency and needing a fail-open (defaulting to allow or local fallback when Redis is unreachable) or fail-closed (blocking requests when Redis is unreachable) policy.

Common mistakes

  • Running a background thread to add tokens to all callers every second. That turns an O(1) per-request problem into an O(total_clients) sweep that wastes CPU on idle keys.
  • Forgetting min(capacity, ...) during lazy refill. Without the capacity ceiling, a caller that goes quiet overnight accumulates millions of tokens and can unleash an unbounded flood later.
  • Advancing last_refill_time = now on rejected requests without saving fractional earned tokens (or truncating integer division remainders while resetting last_refill_time). A caller retrying every 100 ms for a 1 token/s limit will repeatedly earn 0 whole tokens, lose its elapsed time, and starve forever.
  • Using wall-clock time (time.time()) instead of time.monotonic() in-process. An NTP clock adjustment backward produces negative elapsed (subtracting tokens if unguarded) or freezes refills until the clock catches up, while a forward jump hands out free tokens.
  • Assuming Python's GIL or map lookups make allow() thread-safe. Two threads can still interleave between reading current_tokens and writing current_tokens - cost, admitting double the allowed burst unless synchronized per shard or per key.
  • Logging rejected requests in the sliding-window baseline. Appending rejected timestamps keeps the deque full, permanently locking out any caller that retries faster than N / T.
  • Setting eviction TTL shorter than capacity / refill_rate. Expiring a half-empty bucket after 5 s when full recovery takes 60 s lets an attacker pause briefly and receive a brand-new full bucket early.

Follow-up questions

  • Can per-caller state be compressed from two numbers down to a single timestamp without changing admission behavior? Yes, using GCRA (Generic Cell Rate Algorithm), which is mathematically equivalent to a token bucket while storing only one timestamp per caller: TAT (Theoretical Arrival Time, the instant when the bucket will next reach full capacity). Defining emission interval tau = 1 / refill_rate seconds per token, an incoming call of cost at now computes new_tat = max(TAT, now) + cost * tau and admits the call if and only if new_tat - now <= capacity * tau, updating TAT = new_tat when allowed. Because max(TAT, now) - now equals (capacity - current_tokens) * tau, GCRA produces identical decisions in 8 bytes instead of 16 bytes.
  • How would you enforce multiple simultaneous quotas per caller, such as a 20-requests-per-second burst cap alongside a 10,000-requests-per-day ceiling? Represent each quota rule as its own (capacity, refill_rate) bucket inside the caller's shard lock (or inside one Redis Lua script) and verify that every bucket holds sufficient tokens before deducting from any bucket. Running check-all before deduct-all atomically ensures a request blocked by the daily quota never drains tokens from the per-second bucket, while Retry-After reports the largest recovery delay among violated rules.
  • In a Redis-backed fleet, how do you stop a single ultra-hot API key sending 100,000 requests per second from saturating one Redis shard? Add hierarchical local token leasing (batch allocation) on API nodes for high-volume keys. Rather than calling Redis on every arrival, each API node checks out batches of B = 50 tokens at once (cost = 50 in the Lua script) and deducts up to 50 local arrivals in memory before requesting another batch, paired with a brief 200 ms local negative cache once Redis reports an empty bucket so flood traffic is rejected in process without hitting Redis.

Follow-up questions

Similar questions

More Altruist interview questions

All 1 Altruist questions →