KatInterview

Build a Thread-Safe Token Bucket Rate Limiter

Data Structure DesignModel answer
MediumModel answerData Structure Designconcurrencyrate-limitingsynchronization

Last 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

  1. Thread safety. try_acquire and acquire will be called concurrently from many threads. There must be no over-allocation, double-counting of elapsed time, or lost updates.
  2. 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.
  3. No busy-waiting. acquire must sleep on a condition variable (or equivalent). Polling in a tight loop is not acceptable.
  4. Refill cap. Tokens accumulate proportionally to elapsed time but the bucket total must never exceed capacity.

Constraints

  • 1 <= capacity <= 10^6
  • refill_rate > 0.0
  • 1 <= tokens per call
  • A request for more tokens than capacity can 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.