Thread-Safe Per-Key Token Bucket Rate Limiter

Medium · Software Engineering Fundamentals · Machine Learning Engineer · Onsite

Problem Statement

Design and implement an in-memory per-key token-bucket rate limiter, and expose rate_limiter_requests(capacity: int, refill_rate: int, requests: List[List]) -> List[bool] to evaluate an ordered sequence of timestamped requests.

Each item in requests is a 3-element list [key, timestamp_ms, tokens] representing a caller identified by key arriving at timestamp_ms (in integer milliseconds) and requesting tokens tokens: - Independent buckets starting full: Every distinct key maintains its own isolated bucket with maximum size capacity tokens. The first time a key appears, its bucket starts full with capacity tokens. - Continuous replenishment: Between calls for the same key, its bucket accrues tokens continuously at refill_rate tokens per second (equivalently, refill_rate / 1000 tokens per millisecond), capped at capacity. Sub-token fractional progress across milliseconds must carry forward accurately with zero floating-point drift. (If a timestamp is equal to or earlier than the bucket's last refill timestamp, zero tokens are added or removed.) - All-or-nothing deduction: After replenishing up to timestamp_ms, if the bucket holds at least tokens tokens, subtract tokens from the bucket and record True. Otherwise, leave the bucket balance unchanged (deduct zero tokens) and record False.

Return the boolean list of admission outcomes corresponding to requests.

In an interview discussion alongside the code, be ready to: 1. Justify choosing a token bucket over fixed-window counters, sliding-window logs/counters, and leaky-bucket queues in terms of burst handling, boundary accuracy, and per-key space/time cost. 2. Structure the limiter as a reusable, thread-safe class backed by an injectable monotonic clock and lossless eviction of idle full buckets. 3. Verify exact millisecond refill boundaries and multi-threaded contention without time.sleep().

Examples

Example 1

Input:
  capacity = 4
  refill_rate = 2
  requests = [
    ["u1", 0, 3],
    ["u1", 0, 2],
    ["u1", 500, 2],
    ["u1", 1000, 1],
    ["u2", 1000, 4]
  ]

Output:
  [True, False, True, True, True]

Explanation: - At 0 ms, "u1" starts full with 4 tokens and spends 3 (True, 1 left). Asking immediately for 2 more fails (False), leaving the remaining 1 token untouched. - At 500 ms (0.5 s later), 0.5 * 2 = 1 token has replenished, bringing "u1" to 2 tokens; spending 2 succeeds (True, 0 left). - At 1000 ms, another 1 token has replenished for "u1" (True), while unseen caller "u2" starts with a full 4-token bucket and spends all 4 at once (True).

Example 2

Input:
  capacity = 3
  refill_rate = 2
  requests = [
    ["api", 0, 3],
    ["api", 499, 1],
    ["api", 500, 1],
    ["api", 5000, 4],
    ["api", 5000, 3]
  ]

Output:
  [True, False, True, False, True]

Explanation: - "api" drains all 3 tokens at 0 ms (True). - By 499 ms, 499 * (2 / 1000) = 0.998 tokens have accrued, which is short of 1 (False, keeping 0.998 tokens). - Just 1 ms later at 500 ms, 0.002 more tokens arrive to reach 1.000 token (True, 0 left). - By 5000 ms, replenishment caps at capacity = 3: requesting 4 tokens fails without draining anything (False), and requesting 3 tokens right afterward succeeds (True).

Constraints

  • 0 <= capacity <= 10^6
  • 0 <= refill_rate <= 10^6
  • 0 <= len(requests) <= 10^5
  • Each request [key, timestamp_ms, tokens] has a hashable key (such as int or str), integer 0 <= timestamp_ms <= 10^9 in non-decreasing order, and integer 0 <= tokens <= 10^6.

Step-by-step walkthrough

  1. Understand the design scope and the judge contract

    We need to build a reusable, thread-safe per-key token-bucket rate limiter and expose rate_limiter_requests(capacity, refill_rate, requests) to replay [key, timestamp_ms, tokens] calls. Every distinct key starts with a full bucket of capacity tokens and replenishes continuously at refill_rate tokens per second (capped at capacity). If a bucket holds at least tokens, we deduct tokens and append True; otherwise we deduct nothing and append False.

    Let's confirm every edge rule from the two examples before writing code:

    • Example 1 (capacity = 4, refill_rate = 2):
      • At 0 ms, "u1" spends 3 tokens (1 left -> True), then requests 2 tokens (1 < 2 -> False, keeping the 1 leftover token intact).
      • At 500 ms (0.5 s later), 0.5 s * 2 tokens/s = 1 token has accrued, bringing "u1" to 2 tokens so spending 2 succeeds (True). Notice a fixed 1-second counter would have blocked this mid-second recovery!
      • At 1000 ms, unseen caller "u2" spends all 4 tokens immediately (True), confirming that brand-new keys start full.
    • Example 2 (capacity = 3, refill_rate = 2):
      • "api" empties its 3-token bucket at 0 ms (True).
      • At 499 ms, 0.998 tokens have accrued (False).
      • At 500 ms (1 ms later), 0.002 more arrives to reach 1.000 token (True). Any code that floors 0.998 down to 0 and advances its timestamp at 499 ms loses that 0.998 fraction and wrongly rejects 500 ms!
      • At 5000 ms, idle replenishment stops at capacity = 3, rejecting cost 4 (False) while admitting cost 3 (True).

    In an interview, state your clarified engineering contract up front:

    • Scope & key: single-process, thread-safe library class keyed by any hashable caller ID (user ID, API key, IP, or (user, route)).
    • Traffic shape: allow instant bursts up to capacity and sustain refill_rate tokens/second, supporting variable token costs per request.
    • Over-limit behavior: reject immediately (False) without queueing or deducting tokens.
    • Precision: exact to the millisecond with no boundary overshoot.
  2. Part 1: Compare rate-limiting algorithms and pick token bucket

    To compare rate-limiting families fairly, test each one against the boundary-burst scenario: suppose the limit is N = 5 requests per second, and a client fires 5 requests at 999 ms and 5 more at 1001 ms (2 ms apart):

    Time (ms):        0                999 | 1000               2000
    Fixed window:     [---- window 1 ----5]|[5---- window 2 -----]
                                         ^^^
                             10 requests pass in just 2 ms!
    
    Algorithm                Boundary burst           Memory per key      Time per call
    -----------------------  -----------------------  ------------------  -------------
    Fixed window counter     Up to 2N in an instant   1 count + window    O(1)
    Sliding window log       At most N in any window  Up to N timestamps  O(1) amortized
    Sliding window counter   ~N (weighted estimate)   2 counts + window   O(1)
    Token bucket             Up to capacity at once   balance + last_ms   O(1)
    Leaky bucket (queue)     Smoothed; excess waits   FIFO queue          O(1) + delay
    
    • Fixed window counter counts requests per calendar second (0..999 ms, 1000..1999 ms). It takes two integers per key, but lets 2N requests slip across the boundary in 2 ms.
    • Sliding window log keeps the exact timestamp of every admitted request in a queue and drops entries older than the window. It enforces "at most N in any rolling second" strictly, but uses O(N) memory per key — prohibitive when N = 10,000.
    • Sliding window counter estimates the rolling count from the current window count plus the overlap fraction of the previous window. It uses O(1) memory, but it is an approximation rather than exact continuous refill.
    • Token bucket holds up to capacity tokens and refills continuously at refill_rate tokens/second. Over any interval of T seconds, a client can spend at most capacity + refill_rate * T tokens, using only two integers per key and O(1) work.
    • Leaky bucket (queue) drains requests at a fixed pace to protect fragile downstream systems, which adds queueing latency instead of giving an immediate True/False.

    Why token bucket wins here: it allows controlled bursts (capacity), enforces a steady long-run average (refill_rate), answers immediately in O(1) time and O(1) space per key, and matches the continuous millisecond refill in Examples 1 and 2. Be candid about when you would choose differently: pick a sliding window log (or sliding counter) if a strict SLA forbids ever exceeding N calls in any rolling window even after an idle period, or a leaky bucket if downstream workers need smooth pacing rather than burst tolerance.

  3. Part 2: Write a tight prompt before generating code

    Asking an AI assistant to "write a Python rate limiter" invites silent production bugs: floating-point drift, time.time() wall-clock jumps, missing thread locks, and unbounded dictionary growth. Instead, specify the contract, data types, clock injection, and thread-safety invariants up front so you can review the generated code against an explicit checklist:

    Prompt to the AI assistant:
    Implement TokenBucketLimiter(capacity: int, refill_rate: int, clock) in Python:
    1. allow(key, tokens=1) -> bool. Each key gets an independent bucket that starts
       full at `capacity` tokens and refills continuously at `refill_rate` tokens/s,
       capped at `capacity`. Fractional tokens must carry over across calls.
    2. A rejected request must deduct zero tokens.
    3. `clock` is a zero-arg callable returning integer milliseconds; default to a
       monotonic clock (never time.time()). Use exact integer arithmetic, no floats.
    4. Thread-safe in one process: clock read, refill, check, and deduction must be
       atomic under a lock.
    5. Add evict_full_buckets() -> int to delete idle keys that have refilled to full.
    6. Write deterministic unit tests with a fake ManualClock (no time.sleep) covering
       exact millisecond boundaries and multi-threaded contention.
    
  4. Avoid float bugs by counting thousandths of a token

    Why forbid float balances? In IEEE-754 binary floating point, 0.1 has no exact representation: adding 0.1 ten times (100 ms steps at 1 token/second) produces 0.9999999999999999 < 1.0, falsely rejecting a valid request at 1000 ms! And rounding refills down to whole integers loses sub-token progress (499 ms in Example 2).

    Because timestamps are in integer milliseconds and refill_rate is in integer tokens per second (1000 ms), scaling every token by UNITS_PER_TOKEN = 1000 makes every refill an exact integer multiplication:

    1 token              = 1000 units
    refill_rate tokens/s = (refill_rate * 1000 units) / (1000 ms)
                         = refill_rate units per millisecond
    

    We also default to time.monotonic_ns() // 1_000_000 (a monotonic clock guaranteed never to jump backwards when NTP adjusts the system wall clock) and store each key's state in a small _Bucket object with named fields:

    import threading
    import time
    
    # Store token balances in integer thousandths (1 token = 1000 units) so that
    # refilling `refill_rate` tokens/second equals `refill_rate` units/millisecond
    # with exact integer arithmetic and zero floating-point rounding drift.
    UNITS_PER_TOKEN = 1000
    
    
    def monotonic_ms() -> int:
        """Return elapsed milliseconds from a monotonic clock that never jumps backwards."""
        return time.monotonic_ns() // 1_000_000
    
    
    class _Bucket:
        """Per-key state: current balance in thousandths of a token and last refill timestamp."""
    
        __slots__ = ("units", "last_refill_ms")
    
        def __init__(self, units: int, last_refill_ms: int):
            self.units = units
            self.last_refill_ms = last_refill_ms
    
  5. Code atomic refill, check, and spend under one lock

    Instead of running a background timer to drip tokens into every bucket, we perform lazy refill: whenever a key makes a request at now_ms, we calculate elapsed_ms = now_ms - bucket.last_refill_ms and add elapsed_ms * refill_units_per_ms right then, capped at capacity_units.

    Three details in allow prevent subtle concurrency and edge-case bugs:

    1. Single critical section (with self.lock:): "refill -> check bucket.units >= cost_units -> subtract cost_units" is a read-modify-write sequence. Holding one lock across the clock read, refill, check, and subtraction guarantees two threads can never see the same remaining token and both spend it.
    2. Backwards-timestamp guard (if elapsed_ms > 0:): if replayed log timestamps arrive out of order, elapsed_ms is negative; ignoring elapsed_ms <= 0 avoids accidentally subtracting tokens or moving last_refill_ms backwards.
    3. No allocation on rejected new keys: if an unseen key asks for cost_units > capacity_units (or capacity == 0), we return False before inserting into self.buckets, since a full bucket has the exact same future behavior as a missing key.
    class TokenBucketLimiter:
        """Thread-safe per-key token bucket holding up to `capacity` tokens, refilling at `refill_rate` tokens/s."""
    
        def __init__(self, capacity: int, refill_rate: int, clock=monotonic_ms):
            if capacity < 0 or refill_rate < 0:
                raise ValueError("capacity and refill_rate must not be negative")
            self.capacity_units = capacity * UNITS_PER_TOKEN
            self.refill_units_per_ms = refill_rate
            self.clock = clock
            # buckets maps each active key -> _Bucket(units, last_refill_ms)
            self.buckets: Dict[Any, _Bucket] = {}
            self.lock = threading.Lock()
    
        def _refill(self, bucket: _Bucket, now_ms: int) -> None:
            """Lazily add tokens earned between `bucket.last_refill_ms` and `now_ms`, capped at capacity."""
            elapsed_ms = now_ms - bucket.last_refill_ms
            # Guard with `elapsed_ms > 0` so out-of-order timestamps never subtract tokens.
            if elapsed_ms > 0:
                added_units = elapsed_ms * self.refill_units_per_ms
                bucket.units = min(self.capacity_units, bucket.units + added_units)
                bucket.last_refill_ms = now_ms
    
        def allow(self, key: Any, tokens: int = 1) -> bool:
            """Spend `tokens` from `key`'s bucket if available; leave the bucket unchanged when rejected."""
            if tokens < 0:
                raise ValueError("tokens must not be negative")
            cost_units = tokens * UNITS_PER_TOKEN
    
            # Read clock, refill, check balance, and deduct inside one lock so concurrent
            # threads cannot observe the same available tokens and double-spend them.
            with self.lock:
                now_ms = self.clock()
                bucket = self.buckets.get(key)
                if bucket is None:
                    # A brand-new key starts with a full bucket. If its first request already
                    # exceeds capacity, reject without allocating dictionary state for that key.
                    if self.capacity_units < cost_units:
                        return False
                    self.buckets[key] = _Bucket(self.capacity_units - cost_units, now_ms)
                    return True
    
                self._refill(bucket, now_ms)
                # Strict `<`: when `bucket.units == cost_units`, the request fits exactly and is allowed.
                if bucket.units < cost_units:
                    return False
                bucket.units -= cost_units
                return True
    
  6. Review AI-generated code and bound memory with eviction

    During Part 2, walk the interviewer through what you inspect in an AI assistant's first draft:

    • Race conditions: did the assistant lock only bucket.units -= cost_units while computing _refill outside the lock, or read self.buckets.get(key) before acquiring self.lock?
    • Clock choice: did it call time.time() instead of time.monotonic_ns()?
    • Unbounded memory: if millions of transient IPs hit the service once and leave, self.buckets grows forever unless we clean up idle entries.

    Notice a clean invariant: a bucket that has refilled back to capacity_units behaves identically to a key that is not in self.buckets at all, because missing keys start full! So evict_full_buckets() can safely delete every full bucket without changing any future allow() result (and when refill_rate == 0, partially spent one-time quotas never reach capacity_units, so they are rightly kept):

    def evict_full_buckets(self) -> int:
        """Remove buckets that have refilled back to full capacity to bound memory from idle keys."""
        with self.lock:
            now_ms = self.clock()
            full_keys = []
            for key, bucket in self.buckets.items():
                self._refill(bucket, now_ms)
                # Deleting a full bucket is lossless because an unseen key also starts full.
                if bucket.units == self.capacity_units:
                    full_keys.append(key)
            for key in full_keys:
                del self.buckets[key]
            return len(full_keys)
    
  7. Part 3: Replay with a manual clock and prove tests catch bugs

    ManualClock lets both rate_limiter_requests and unit tests advance time to the exact millisecond without slow, flaky time.sleep() calls:

    class ManualClock:
        """Controllable clock for deterministic timestamp replay and sleep-free boundary tests."""
    
        def __init__(self, now_ms: int = 0):
            self.now_ms = now_ms
    
        def __call__(self) -> int:
            return self.now_ms
    
    
    def rate_limiter_requests(capacity: int, refill_rate: int, requests: List[List]) -> List[bool]:
        """Replay `[key, timestamp_ms, tokens]` requests against a TokenBucketLimiter."""
        clock = ManualClock()
        limiter = TokenBucketLimiter(capacity, refill_rate, clock)
        results: List[bool] = []
        for key, timestamp_ms, tokens in requests:
            clock.now_ms = timestamp_ms
            results.append(limiter.allow(key, tokens))
        return results
    

    Trace Example 2 (capacity = 3 -> 3000 units, refill_rate = 2 units/ms) step by step:

    Request            now_ms   units before -> after refill     cost   decision   units left
    -----------------  ------   ------------------------------   ----   --------   ----------
    ["api", 0, 3]           0   new key -> 3000                  3000   True                0
    ["api", 499, 1]       499   0 + 499*2 = 998                  1000   False             998
    ["api", 500, 1]       500   998 + 1*2 = 1000                 1000   True                0
    ["api", 5000, 4]     5000   min(3000, 0 + 4500*2) = 3000     4000   False            3000
    ["api", 5000, 3]     5000   3000 (0 ms elapsed)              3000   True                0
    

    For Part 3's concurrency test, freeze ManualClock(0) and set refill_rate = 0 so there are at most 100 tokens ever available, then release 8 worker threads simultaneously with threading.Barrier(8):

    def test_concurrent_calls_never_over_admit():
        limiter = TokenBucketLimiter(capacity=100, refill_rate=0, clock=ManualClock(0))
        admitted = [0] * 8
        start = threading.Barrier(8)
    
        def worker(idx: int) -> None:
            start.wait()
            for _ in range(500):
                if limiter.allow("shared-key"):
                    admitted[idx] += 1
    
        threads = [threading.Thread(target=worker, args=(i,)) for i in range(8)]
        for thread in threads:
            thread.start()
        for thread in threads:
            thread.join()
        assert sum(admitted) == 100
    

    Finally, prove your tests have teeth via mutation testing (intentionally introducing a defect to see a test turn red): - Replace integer thousandths with float tokens -> the 10 x 100 ms boundary test fails (0.9999999999999999 < 1.0). - Round refills down to whole tokens -> Example 2 fails at 500 ms. - Remove with self.lock: and insert time.sleep(0) between if bucket.units < cost_units: and bucket.units -= cost_units (forcing a thread context switch under CPython's GIL) -> sum(admitted) exceeds 100, while the locked implementation passes with sum(admitted) == 100 every run.

  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    import threading
    import time
    
    # Store token balances in integer thousandths (1 token = 1000 units) so that
    # refilling `refill_rate` tokens/second equals `refill_rate` units/millisecond
    # with exact integer arithmetic and zero floating-point rounding drift.
    UNITS_PER_TOKEN = 1000
    
    
    def monotonic_ms() -> int:
        """Return elapsed milliseconds from a monotonic clock that never jumps backwards."""
        return time.monotonic_ns() // 1_000_000
    
    
    class _Bucket:
        """Per-key state: current balance in thousandths of a token and last refill timestamp."""
    
        __slots__ = ("units", "last_refill_ms")
    
        def __init__(self, units: int, last_refill_ms: int):
            self.units = units
            self.last_refill_ms = last_refill_ms
    
    
    class TokenBucketLimiter:
        """Thread-safe per-key token bucket holding up to `capacity` tokens, refilling at `refill_rate` tokens/s."""
    
        def __init__(self, capacity: int, refill_rate: int, clock=monotonic_ms):
            if capacity < 0 or refill_rate < 0:
                raise ValueError("capacity and refill_rate must not be negative")
            self.capacity_units = capacity * UNITS_PER_TOKEN
            self.refill_units_per_ms = refill_rate
            self.clock = clock
            # buckets maps each active key -> _Bucket(units, last_refill_ms)
            self.buckets: Dict[Any, _Bucket] = {}
            self.lock = threading.Lock()
    
        def _refill(self, bucket: _Bucket, now_ms: int) -> None:
            """Lazily add tokens earned between `bucket.last_refill_ms` and `now_ms`, capped at capacity."""
            elapsed_ms = now_ms - bucket.last_refill_ms
            # Guard with `elapsed_ms > 0` so out-of-order timestamps never subtract tokens.
            if elapsed_ms > 0:
                added_units = elapsed_ms * self.refill_units_per_ms
                bucket.units = min(self.capacity_units, bucket.units + added_units)
                bucket.last_refill_ms = now_ms
    
        def allow(self, key: Any, tokens: int = 1) -> bool:
            """Spend `tokens` from `key`'s bucket if available; leave the bucket unchanged when rejected."""
            if tokens < 0:
                raise ValueError("tokens must not be negative")
            cost_units = tokens * UNITS_PER_TOKEN
    
            # Read clock, refill, check balance, and deduct inside one lock so concurrent
            # threads cannot observe the same available tokens and double-spend them.
            with self.lock:
                now_ms = self.clock()
                bucket = self.buckets.get(key)
                if bucket is None:
                    # A brand-new key starts with a full bucket. If its first request already
                    # exceeds capacity, reject without allocating dictionary state for that key.
                    if self.capacity_units < cost_units:
                        return False
                    self.buckets[key] = _Bucket(self.capacity_units - cost_units, now_ms)
                    return True
    
                self._refill(bucket, now_ms)
                # Strict `<`: when `bucket.units == cost_units`, the request fits exactly and is allowed.
                if bucket.units < cost_units:
                    return False
                bucket.units -= cost_units
                return True
    
        def evict_full_buckets(self) -> int:
            """Remove buckets that have refilled back to full capacity to bound memory from idle keys."""
            with self.lock:
                now_ms = self.clock()
                full_keys = []
                for key, bucket in self.buckets.items():
                    self._refill(bucket, now_ms)
                    # Deleting a full bucket is lossless because an unseen key also starts full.
                    if bucket.units == self.capacity_units:
                        full_keys.append(key)
                for key in full_keys:
                    del self.buckets[key]
                return len(full_keys)
    
    
    class ManualClock:
        """Controllable clock for deterministic timestamp replay and sleep-free boundary tests."""
    
        def __init__(self, now_ms: int = 0):
            self.now_ms = now_ms
    
        def __call__(self) -> int:
            return self.now_ms
    
    
    def rate_limiter_requests(capacity: int, refill_rate: int, requests: List[List]) -> List[bool]:
        """Replay `[key, timestamp_ms, tokens]` requests against a TokenBucketLimiter."""
        clock = ManualClock()
        limiter = TokenBucketLimiter(capacity, refill_rate, clock)
        results: List[bool] = []
        for key, timestamp_ms, tokens in requests:
            clock.now_ms = timestamp_ms
            results.append(limiter.allow(key, tokens))
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture a rechargeable arcade card for each user: a token bucket is a container that starts full at capacity tokens, steadily drips new tokens in at refill_rate per second (never overflowing past capacity), and lets a request through only if the card currently holds enough tokens to pay for it. Instead of running a background timer thread to drip tokens into every user's card every millisecond, we use lazy refill, which means computing how many tokens accumulated since that user's last visit (elapsed_ms * refill_rate) only at the moment a new request arrives.

Naive designs fail at boundaries and under concurrency. A fixed per-second counter resets abruptly on each second mark, letting a client fire twice its limit across 999 ms and 1000 ms while wrongly blocking steady traffic at 500 ms. Even inside a token bucket, storing balances as float introduces binary rounding drift (0.1 added ten times becomes 0.9999999999999999 < 1.0), and checking the balance without a mutex lock lets two threads spend the last token twice. Scaling balances into integer thousandths of a token (1 token = 1000 units) makes refill_rate tokens/second equal to refill_rate integer units/millisecond with zero rounding error.

Walk through the first three calls of Example 2 (capacity = 3 tokens = 3000 units, refill_rate = 2 tokens/s = 2 units/ms) for key "api": 1. ["api", 0, 3]: "api" is new so it starts at 3000 units, spends 3000 (True), and stores (units=0, last_refill_ms=0). 2. ["api", 499, 1]: 499 ms elapsed adds 499 * 2 = 998 units -> (units=998, last_refill_ms=499). Cost is 1000 > 998, so we return False and leave all 998 units intact. 3. ["api", 500, 1]: 1 ms elapsed adds 2 units -> 998 + 2 = 1000 units. Cost is 1000, so it fits (True) and leaves (units=0, last_refill_ms=500).

Complexity

Let R be the number of requests and K be the number of distinct keys with active buckets.

  • Time: O(1) per allow call and O(R) to replay all R requests, because each call performs one dictionary lookup and a handful of integer operations under a lock. Running evict_full_buckets scans the K stored keys once in O(K) time.
  • Space: O(K) memory, storing just two integers (units and last_refill_ms) per active key (plus O(R) for the returned boolean list in rate_limiter_requests). When refill_rate > 0, any idle bucket refills to full within at most capacity / refill_rate seconds, so periodic evict_full_buckets sweeps keep memory bounded to recently active keys.

Edge cases

  • Brand-new key: starts with a full bucket (capacity tokens), so it can spend up to capacity immediately ("u2" in Example 1).
  • Exact millisecond refill boundary: 998 units at 499 ms is rejected, keeps its 998 units, and reaches 1000 units (1 full token) at 500 ms (Example 2).
  • Sub-millisecond token fractions (refill_rate = 3): 333 ms yields 999 units (False), 334 ms reaches 1002 units and spends 1000 leaving 2 leftover units, allowing 667 ms (2 + 333 * 3 = 1001 units) to succeed.
  • Long idle periods: lazy refill clamps bucket.units with min(self.capacity_units, ...), so idle keys never bank tokens above capacity.
  • Request cost exceeding capacity: always returns False without allocating a bucket entry for unknown keys or draining existing tokens.
  • Rejected request followed by a smaller request: a rejected request deducts zero units, so a smaller request right behind it can still succeed.
  • refill_rate = 0 or capacity = 0: refill_rate = 0 acts as a non-renewing quota of capacity tokens (and partially spent buckets are never evicted because they never refill to capacity_units); capacity = 0 rejects every positive-cost request.
  • Out-of-order or backwards timestamps: if elapsed_ms > 0 ignores negative elapsed deltas so tokens are never subtracted.

Common mistakes

  • Using a fixed-window counter: fails Example 1 at 500 ms and allows 2 * capacity traffic bursts across window edges in production.
  • Flooring refills to whole tokens: computing added_tokens = (now_ms - last_ms) * refill_rate // 1000 and updating last_ms = now_ms throws away fractional tokens and fails Example 2.
  • Using float balances: repeated 0.1 additions drift to 0.9999999999999999 and reject valid requests right on the boundary.
  • Using time.time() instead of a monotonic clock: a monotonic clock is a timer that only moves forward at a steady rate, whereas wall-clock time.time() can jump backwards or forwards during NTP adjustments and corrupt elapsed_ms.
  • Locking only the subtraction (check-then-act race): if two threads run _refill and if bucket.units < cost_units outside the lock, both can pass the check on the last token and over-admit.
  • Writing time.sleep() tests or unverified concurrency tests: sleep-based tests are slow and cannot hit exact millisecond edges, and a concurrency test that still passes when you remove self.lock (because CPython's GIL hid the race) has not actually tested thread safety.

Alternative approaches

  • Sliding window log: stores a per-key queue of timestamps for all requests admitted in the last window. It guarantees strictly at most N requests in any rolling window, at the cost of O(N) memory per key.
  • Sliding window counter: stores only the current window's count and previous window's count, weighting the previous window by the remaining overlap fraction. It uses O(1) memory per key, though it approximates burst boundaries.
  • Generic Cell Rate Algorithm (GCRA): tracks a single "theoretical arrival time" integer per key instead of (units, last_refill_ms). It is mathematically equivalent to a token bucket with half the state, making atomic updates in distributed stores compact.
  • Leaky bucket queue: places accepted requests into a fixed-size FIFO queue drained at a constant rate, trading immediate True/False responses for smooth downstream pacing.

Follow-up questions

  • If traffic is spread across a fleet of stateless application nodes enforcing a single global quota per caller, how do you guarantee atomic token deductions and how does that affect request latency? Store each key's (units, last_refill_ms) in a shared low-latency store such as Redis and execute the clock read, refill, check, and deduction inside one Redis Lua script (a short server-side script that Redis runs atomically from start to finish) or a compare-and-set (CAS) loop (an update that succeeds only if the record's version has not changed since it was read), using the store's single clock to avoid clock skew across app servers. This adds one network round trip on every request — typically 0.5–2 ms within one data center or tens of milliseconds cross-region — plus hot-key pressure that you spread by sharding keys across Redis nodes. To cut latency on ultra-hot paths, servers can lease small batches of tokens from Redis and spend them locally, trading slight under-utilization across servers for zero per-request network hops.
  • When the backing data store for your shared rate limiter goes down or times out, should the gateway fail open or fail closed, and how do you decide? Choose between fail-closed (rejecting traffic when the limiter is down) and fail-open (allowing traffic through when the limiter is down) based on what the limit protects. Security-critical or direct-cost endpoints — such as password-login attempts or paid GPU/LLM inference quotas — should fail closed so an outage cannot enable brute-force attacks or runaway spend. General API fairness limits should fail open onto a local in-process fallback limiter (for example, global_limit / num_servers) guarded by a short timeout and a circuit breaker (a switch that temporarily stops calling a failing dependency so timeouts do not pile up on every request).
  • How would you extend the architecture to support per-tier and per-route quotas that operators can update live without redeploying services? Key buckets by (customer_id, endpoint) and fetch (capacity, refill_rate) for (tier, endpoint) from a dynamic configuration store, cached in each server's memory with a short TTL (time-to-live expiration window) or updated via pub/sub push notifications, falling back to conservative defaults if config lookup fails. When a key's rate or capacity changes, lazily refill its existing bucket up to now_ms using the old parameters first, then clamp bucket.units = min(bucket.units, new_capacity_units) so a config reload neither grants a free burst nor wipes earned tokens. Validate config pushes before rollout so an accidental capacity = 0 cannot lock out production traffic.
  • What retry metadata should an HTTP response include when throttling a caller, and how do you prevent synchronized retry spikes? Return HTTP 429 Too Many Requests with a Retry-After header computed from the missing units: ceil((cost_units - bucket.units) / refill_units_per_ms) converted up to whole seconds (or return 400/403 instead of Retry-After if cost_units > capacity_units or refill_rate == 0, since retrying will never succeed). To prevent a thundering herd (many rejected clients waking up at the exact same second and colliding again), clients should apply exponential backoff (doubling wait times after repeated failures) with random jitter (adding a small random delay), and the server can also add a small random offset to Retry-After.

Follow-up questions

Similar questions

More Snowflake interview questions

All 130 Snowflake questions →