Build a Thread-Safe Token Bucket for Cloud API Quotas
Last updated: November 29, 2026
Quick Overview
Implement a token bucket rate limiter that many request-handling threads call concurrently, allowing bursts up to a capacity and a steady refill rate. It must be correct under contention and testable without real sleeps.
0
0
0 solved
Implement a token bucket rate limiter that many request-handling threads call concurrently, allowing bursts up to a capacity and a steady refill rate. It must be correct under contention and testable without real sleeps.
Google Cloud APIs enforce per-project quotas, and a phone or technical screen often asks for a small in-process limiter before discussing the distributed version. The interviewer checks lazy refill math, where the lock goes, and whether the candidate makes time injectable so the code can be tested deterministically.
What the Interviewer Expects
- Refills lazily from elapsed time instead of running a background thread
- Holds one lock around refill plus decrement so check-then-act is atomic
- Caps tokens at capacity and rejects requests larger than capacity
- Injects a clock so tests do not sleep
- Explains why a monotonic clock is used instead of wall time
Key Topics to Cover
How to Approach This
- Apply SOLID principles. Single Responsibility makes code testable, Open/Closed makes it extensible.
- Choose data structures based on access patterns, not familiarity.
- Prefer immutable data and message passing over shared mutable state for concurrency.
- Design APIs with RESTful conventions, versioning, meaningful errors, and pagination from day one.
Possible Follow-up Questions
- How would you make a caller block until tokens are available instead of failing?
- How do you extend this to a per-key limiter for millions of API keys without unbounded memory?
- What changes when the limiter is shared across many servers?
- How would you reduce lock contention at very high QPS?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice System Design ProblemsSample Answer
Requirements
try_acquire(n)returns True and consumesntokens if available, else False, never blocking.- Bucket starts full, refills at
ratetokens per second, never exceedscapacity. - Safe for many t...
High-Level Design
Store tokens as a float and last refill timestamp. On every call, compute the tokens earned since last and add them, capped. This lazy refill avoids a timer thread and is exact. The refill, the ...