Build a Thread-Safe Token Bucket Rate Limiter
Data Structure DesignModel answerLast updated
Implement a token bucket that refills lazily on each admission attempt, handles concurrent callers safely, and supports both non-blocking and timeout-bounded acquisition.
Background
Services that fan out to slow or quota-limited downstream APIs need a way to pace their own outbound calls. A token bucket is the standard primitive for this: tokens accumulate at a fixed rate up to a ceiling, and each request consumes one or more tokens before it is allowed through.
Rather than running a dedicated background thread to periodically deposit tokens, your implementation should credit tokens lazily — computed from elapsed time the moment any caller attempts an acquisition. This keeps the design simple and avoids the overhead of a permanent goroutine or timer thread.
What to Implement
class TokenBucket:
def __init__(self, capacity: int, refill_rate: float):
"""
capacity – maximum tokens the bucket can hold; bucket starts full.
refill_rate – tokens added per second (must be > 0).
"""
def try_acquire(self, tokens: int = 1) -> bool:
"""
Tries to consume `tokens` right now without blocking.
Returns True on success, False if there are not enough tokens.
"""
def acquire(self, tokens: int = 1, timeout: float = None) -> bool:
"""
Blocks until `tokens` are available or until `timeout` seconds pass.
timeout=None means wait indefinitely.
Returns True if acquired, False if the timeout expired first.
"""
Requirements
- Thread safety.
try_acquireandacquirewill be called concurrently from many threads. There must be no over-allocation, double-counting of elapsed time, or lost updates. - Monotonic clock. Use
time.monotonic()— never the wall clock — so NTP corrections or manual time changes cannot produce negative elapsed intervals or spurious token bursts. - No busy-waiting.
acquiremust sleep on a condition variable (or equivalent). Polling in a tight loop is not acceptable. - Refill cap. Tokens accumulate proportionally to elapsed time but the bucket total must never exceed
capacity.
Constraints
1 <= capacity <= 10^6refill_rate > 0.01 <= tokensper call- A request for more tokens than
capacitycan never be satisfied; handle it gracefully.
Example
bucket = TokenBucket(capacity=5, refill_rate=2.0)
# Bucket starts with 5.0 tokens.
bucket.try_acquire(3) # True — 2.0 tokens remain
bucket.try_acquire(3) # False — only 2.0 available
# Need 1 more token to reach 3; at 2.0 tok/s that takes 0.5 s.
bucket.acquire(3, timeout=0.2) # False — times out after 0.2 s (~2.4 tokens accumulated)
bucket.acquire(3, timeout=1.0) # True — waits ~0.3 s (bucket was already at ~2.4)
Your answer should cover the core algorithm, all synchronization decisions, complexity, and the edge cases listed in the constraints.
Hints
Hint 1
Lazy refill means: every time any thread touches the bucket, compute `min(capacity, stored + elapsed * rate)` and advance the timestamp — no background thread needed. Both the stored count and the timestamp must be updated inside the same lock to prevent two threads from crediting the same time slice twice.
Hint 2
For `acquire`, don't poll. Compute exactly how long the current deficit would take to refill — `deficit / rate` — and sleep the condition variable for that duration (capped by any remaining timeout). When the thread wakes, re-run the refill and re-check; another thread may have consumed tokens while you slept.
Hint 3
Three edge cases that interviewers probe: (1) `tokens > capacity` — the request is unsatisfiable; return False immediately or `acquire` would block forever. (2) `timeout <= 0` — treat it like `try_acquire`. (3) A timed-out `acquire` still partially refills the bucket for the next caller, so the next wait is shorter than a naive calculation suggests.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core Algorithm
The bucket stores two pieces of state: a floating-point token count and the monotonic timestamp of the last refill. There is no background thread. Instead, every entry point runs the same two-line refill before checking availability:
tokens = min(capacity, tokens + (now - last_refill) * rate)
last_refill = now
Both fields must be read and written inside one lock. If they were protected separately, two threads could each observe the same last_refill, both credit the same elapsed interval, and mint tokens from nothing.
A threading.Condition wraps that lock. It lets blocking callers sleep without holding the lock and wake when their computed wait has elapsed.
Implementation
import threading
import time
from typing import Optional
class TokenBucket:
def __init__(self, capacity: int, refill_rate: float):
if capacity <= 0:
raise ValueError("capacity must be > 0")
if refill_rate <= 0:
raise ValueError("refill_rate must be > 0")
self._capacity = float(capacity)
self._rate = float(refill_rate)
self._tokens = float(capacity) # starts full
self._last = time.monotonic()
self._cond = threading.Condition(threading.Lock())
# ---- internal helpers (caller must hold self._cond) ----
def _refill(self, now: float) -> None:
elapsed = now - self._last
if elapsed > 0:
self._tokens = min(self._capacity, self._tokens + elapsed * self._rate)
self._last = now
def _unsatisfiable(self, tokens: int) -> bool:
# A request larger than capacity can never be met; catch it early.
return tokens <= 0 or tokens > self._capacity
# ---- public API ----
def try_acquire(self, tokens: int = 1) -> bool:
if self._unsatisfiable(tokens):
return False
with self._cond:
self._refill(time.monotonic())
if self._tokens >= tokens:
self._tokens -= tokens
return True
return False
def acquire(self, tokens: int = 1, timeout: Optional[float] = None) -> bool:
if self._unsatisfiable(tokens):
return False
with self._cond:
deadline = (
None if timeout is None
else time.monotonic() + max(0.0, timeout)
)
while True:
now = time.monotonic()
self._refill(now)
if self._tokens >= tokens:
self._tokens -= tokens
return True
# How long until refill covers the deficit?
wait = (tokens - self._tokens) / self._rate
if deadline is not None:
remaining = deadline - now
if remaining <= 0:
return False # timed out — final check already done
wait = min(wait, remaining)
# Releases the lock while sleeping; re-acquires on return.
self._cond.wait(wait)
Why This Is Correct
No over-allocation. The refill, the availability check, and the subtraction are a single critical section. No other thread can observe or modify the bucket between "check" and "consume".
No double-counted time. _last advances to now on every refill call, so each real-world second is credited exactly once regardless of how many threads call in.
Cap respected. min(capacity, ...) discards the surplus. Advancing _last even when the bucket is already full is intentional: time spent at capacity must not be banked as future credit.
Spurious wakeups and thread contention. After every wakeup the loop re-runs _refill and re-checks the balance. If a try_acquire from a concurrent thread drained the bucket during the sleep, this waiter simply sleeps again for the new deficit — no correctness issue.
Monotonic clock. time.monotonic() never jumps backward, so elapsed is always non-negative.
Complexity
| Operation | Time | Space |
|---|---|---|
try_acquire | O(1) | O(1) |
acquire | O(1) per wakeup; typically 1–2 wakeups | O(1) bucket state + Condition bookkeeping |
Edge Cases
tokens > capacity. Return False immediately. Letting this reach acquire(timeout=None) would block forever since the deficit can never close.
tokens <= 0. Invalid input; return False (or raise ValueError — either is defensible, just be consistent).
timeout <= 0. The deadline fires before the first sleep, so acquire degrades to a single try-and-return — identical behaviour to try_acquire.
The example's second acquire. The timed-out acquire(3, timeout=0.2) still runs refill before returning, leaving the bucket at roughly 2.4 tokens. The subsequent acquire(3, timeout=1.0) therefore waits about 0.3 s, not 0.5 s. Noting this in an interview shows you understand that lazy refill is a side effect of every call, not just successful ones.
Floating-point drift. Token counts are floats. A deficit of ~1e-12 produces a near-zero wait; the very next iteration satisfies the check. This is harmless in practice.
Design Notes Interviewers Ask About
Why no notify? The only event that adds tokens is the passage of time — nothing ever returns tokens to the bucket. Each waiter already sleeps for its computed deficit / rate. There is nothing to broadcast. If you add a release() or refund path later, you would call self._cond.notify_all() there.
No time.sleep() inside the lock. Condition.wait(t) releases the lock during the sleep and re-acquires it on return. A bare time.sleep() inside with lock: would serialize the whole system — a common mistake.
Fairness / starvation. This design has no FIFO ordering. A thread requesting 1 token can repeatedly beat a thread requesting 50. For strict ordering, maintain a queue of per-waiter Event objects; only the head waiter sleeps and pops itself on success before signaling the next. That is more complex and only worth it when starvation of large requests is a real concern.
Scaling across processes (Redis). Store tokens and last_refill in a Redis hash and run refill-check-consume as a single Lua script via EVAL. Redis executes scripts atomically, replacing the mutex. Use redis.call('TIME') inside the script rather than a client-side clock to eliminate cross-host skew.