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^60 <= refill_rate <= 10^60 <= len(requests) <= 10^5- Each request
[key, timestamp_ms, tokens]has a hashablekey(such asintorstr), integer0 <= timestamp_ms <= 10^9in non-decreasing order, and integer0 <= tokens <= 10^6.
Step-by-step walkthrough
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 distinctkeystarts with a full bucket ofcapacitytokens and replenishes continuously atrefill_ratetokens per second (capped atcapacity). If a bucket holds at leasttokens, we deducttokensand appendTrue; otherwise we deduct nothing and appendFalse.Let's confirm every edge rule from the two examples before writing code:
- Example 1 (
capacity = 4,refill_rate = 2):- At
0 ms,"u1"spends3tokens (1left ->True), then requests2tokens (1 < 2->False, keeping the1leftover token intact). - At
500 ms(0.5 slater),0.5 s * 2 tokens/s = 1token has accrued, bringing"u1"to2tokens so spending2succeeds (True). Notice a fixed 1-second counter would have blocked this mid-second recovery! - At
1000 ms, unseen caller"u2"spends all4tokens immediately (True), confirming that brand-new keys start full.
- At
- Example 2 (
capacity = 3,refill_rate = 2):"api"empties its3-token bucket at0 ms(True).- At
499 ms,0.998tokens have accrued (False). - At
500 ms(1 mslater),0.002more arrives to reach1.000token (True). Any code that floors0.998down to0and advances its timestamp at499 msloses that0.998fraction and wrongly rejects500 ms! - At
5000 ms, idle replenishment stops atcapacity = 3, rejecting cost4(False) while admitting cost3(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
capacityand sustainrefill_ratetokens/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.
- Example 1 (
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 = 5requests per second, and a client fires5requests at999 msand5more at1001 ms(2 msapart):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 lets2Nrequests slip across the boundary in2 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
Nin any rolling second" strictly, but usesO(N)memory per key — prohibitive whenN = 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
capacitytokens and refills continuously atrefill_ratetokens/second. Over any interval ofTseconds, a client can spend at mostcapacity + refill_rate * Ttokens, using only two integers per key andO(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 inO(1)time andO(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 exceedingNcalls in any rolling window even after an idle period, or a leaky bucket if downstream workers need smooth pacing rather than burst tolerance.- Fixed window counter counts requests per calendar second (
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.Avoid float bugs by counting thousandths of a token
Why forbid
floatbalances? In IEEE-754 binary floating point,0.1has no exact representation: adding0.1ten times (100 mssteps at1token/second) produces0.9999999999999999 < 1.0, falsely rejecting a valid request at1000 ms! And rounding refills down to whole integers loses sub-token progress (499 msin Example 2).Because timestamps are in integer milliseconds and
refill_rateis in integer tokens per second (1000 ms), scaling every token byUNITS_PER_TOKEN = 1000makes every refill an exact integer multiplication:1 token = 1000 units refill_rate tokens/s = (refill_rate * 1000 units) / (1000 ms) = refill_rate units per millisecondWe 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_Bucketobject 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_msCode 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 calculateelapsed_ms = now_ms - bucket.last_refill_msand addelapsed_ms * refill_units_per_msright then, capped atcapacity_units.Three details in
allowprevent subtle concurrency and edge-case bugs:- Single critical section (
with self.lock:): "refill -> checkbucket.units >= cost_units-> subtractcost_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. - Backwards-timestamp guard (
if elapsed_ms > 0:): if replayed log timestamps arrive out of order,elapsed_msis negative; ignoringelapsed_ms <= 0avoids accidentally subtracting tokens or movinglast_refill_msbackwards. - No allocation on rejected new keys: if an unseen key asks for
cost_units > capacity_units(orcapacity == 0), we returnFalsebefore inserting intoself.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- Single critical section (
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_unitswhile computing_refilloutside the lock, or readself.buckets.get(key)before acquiringself.lock? - Clock choice: did it call
time.time()instead oftime.monotonic_ns()? - Unbounded memory: if millions of transient IPs hit the service once and leave,
self.bucketsgrows forever unless we clean up idle entries.
Notice a clean invariant: a bucket that has refilled back to
capacity_unitsbehaves identically to a key that is not inself.bucketsat all, because missing keys start full! Soevict_full_buckets()can safely delete every full bucket without changing any futureallow()result (and whenrefill_rate == 0, partially spent one-time quotas never reachcapacity_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)- Race conditions: did the assistant lock only
Part 3: Replay with a manual clock and prove tests catch bugs
ManualClocklets bothrate_limiter_requestsand unit tests advance time to the exact millisecond without slow, flakytime.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 resultsTrace Example 2 (
capacity = 3->3000units,refill_rate = 2units/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 0For Part 3's concurrency test, freeze
ManualClock(0)and setrefill_rate = 0so there are at most100tokens ever available, then release8worker threads simultaneously withthreading.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) == 100Finally, prove your tests have teeth via mutation testing (intentionally introducing a defect to see a test turn red): - Replace integer thousandths with
floattokens -> the10 x 100 msboundary test fails (0.9999999999999999 < 1.0). - Round refills down to whole tokens -> Example 2 fails at500 ms. - Removewith self.lock:and inserttime.sleep(0)betweenif bucket.units < cost_units:andbucket.units -= cost_units(forcing a thread context switch under CPython's GIL) ->sum(admitted)exceeds100, while the locked implementation passes withsum(admitted) == 100every run.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)perallowcall andO(R)to replay allRrequests, because each call performs one dictionary lookup and a handful of integer operations under a lock. Runningevict_full_bucketsscans theKstored keys once inO(K)time. - Space:
O(K)memory, storing just two integers (unitsandlast_refill_ms) per active key (plusO(R)for the returned boolean list inrate_limiter_requests). Whenrefill_rate > 0, any idle bucket refills to full within at mostcapacity / refill_rateseconds, so periodicevict_full_bucketssweeps keep memory bounded to recently active keys.
Edge cases
- Brand-new key: starts with a full bucket (
capacitytokens), so it can spend up tocapacityimmediately ("u2"in Example 1). - Exact millisecond refill boundary:
998units at499 msis rejected, keeps its998units, and reaches1000units (1full token) at500 ms(Example 2). - Sub-millisecond token fractions (
refill_rate = 3):333 msyields999units (False),334 msreaches1002units and spends1000leaving2leftover units, allowing667 ms(2 + 333 * 3 = 1001units) to succeed. - Long idle periods: lazy refill clamps
bucket.unitswithmin(self.capacity_units, ...), so idle keys never bank tokens abovecapacity. - Request cost exceeding
capacity: always returnsFalsewithout 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 = 0orcapacity = 0:refill_rate = 0acts as a non-renewing quota ofcapacitytokens (and partially spent buckets are never evicted because they never refill tocapacity_units);capacity = 0rejects every positive-cost request.- Out-of-order or backwards timestamps:
if elapsed_ms > 0ignores negative elapsed deltas so tokens are never subtracted.
Common mistakes
- Using a fixed-window counter: fails Example 1 at
500 msand allows2 * capacitytraffic bursts across window edges in production. - Flooring refills to whole tokens: computing
added_tokens = (now_ms - last_ms) * refill_rate // 1000and updatinglast_ms = now_msthrows away fractional tokens and fails Example 2. - Using
floatbalances: repeated0.1additions drift to0.9999999999999999and 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-clocktime.time()can jump backwards or forwards during NTP adjustments and corruptelapsed_ms. - Locking only the subtraction (check-then-act race): if two threads run
_refillandif bucket.units < cost_unitsoutside 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 removeself.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
Nrequests in any rolling window, at the cost ofO(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/Falseresponses 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 — typically0.5–2 mswithin 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 tonow_msusing the old parameters first, then clampbucket.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 accidentalcapacity = 0cannot 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 Requestswith aRetry-Afterheader computed from the missing units:ceil((cost_units - bucket.units) / refill_units_per_ms)converted up to whole seconds (or return400/403instead ofRetry-Afterifcost_units > capacity_unitsorrefill_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 toRetry-After.
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?
- 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?
- How would you extend the architecture to support per-tier and per-route quotas that operators can update live without redeploying services?
- What retry metadata should an HTTP response include when throttling a caller, and how do you prevent synchronized retry spikes?
Similar questions
- Dynamic Dynasty Succession Without an Initial Monarch
- In-Memory Tiered Rate Limiter With Live Quota Updates
- Arrow-Driven Kanban Column State Transitions
- Truncate an N-ary Tree Beyond a Target Depth
- Asynchronous Node Counting Across an Unreliable Tree Network
- Distributed Process-Tree Node Counter Over Asynchronous Messaging
More Snowflake interview questions
- Fewest Node Removals to Cap Tree Height Medium
- Counterclockwise Perimeter of a Binary Tree Medium
- Log Fault Search and Service Outage Cascades Medium Pro
- Computing Inherited Access Grants Across a Permission DAG Medium Pro
- Minimum Edits to Form a Perfect Binary Tree Medium Pro
- Locate All Valid Sets in a Four-Feature Deck Hard Pro
- Multiway Tree Height Under Node Removal and Promotion Medium Pro
- Resulting N-ary Tree Height When Splicing Out Nodes Medium Pro
- Per-Key Sliding-Window Request Limiter Medium Pro
- Rooted Tree Height After Node Removals Medium Pro