Token Bucket Rate Limiter
MediumConcurrencyRate LimitingToken BucketSemaphoreAtomic OperationsConcurrent Design
Problem Statement
Design a thread-safe Token Bucket Rate Limiter that controls the rate of requests to a service. The bucket holds up to capacity tokens and is refilled at a rate of refillRate tokens per second. Each request consumes one token; requests are rejected (or blocked) when the bucket is empty.
class TokenBucketRateLimiter {
public TokenBucketRateLimiter(int capacity, int refillRatePerSecond) {}
// Returns true if the request is allowed, false if rate limit exceeded
public boolean allowRequest() {}
// Blocking variant: waits until a token is available
public void acquireToken() throws InterruptedException {}
public int availableTokens() {}
}
Key Entities
- Token count: Current number of available tokens (volatile long or AtomicLong).
- Last refill timestamp: Used to lazily compute how many tokens to add.
- Refill logic: Tokens added = elapsed_seconds × refillRate, capped at capacity.
- ReentrantLock / synchronized: Guards token consumption and refill atomically.
Requirements
- Allow up to
capacityburst requests instantly. - Sustain
refillRaterequests per second long-term. allowRequest()must be non-blocking and thread-safe.acquireToken()blocks until a token is available (useful for throttling, not rejection).- Handle high concurrency (thousands of threads calling simultaneously).
Asked at: Uber, Amazon, Google, Twitter, Netflix, Stripe, Paytm, Swiggy
!Constraints
- 1 ≤ capacity ≤ 10^6
- 1 ≤ refillRatePerSecond ≤ 10^6
- Thread-safe for concurrent callers.
- Refill must be lazy (computed on demand), not using a background thread by default.
- Time precision: use System.nanoTime() for sub-millisecond accuracy.
Output
Run or submit your code to see output here.