Token Bucket Rate Limiter

Medium
ConcurrencyRate 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

  1. Allow up to capacity burst requests instantly.
  2. Sustain refillRate requests per second long-term.
  3. allowRequest() must be non-blocking and thread-safe.
  4. acquireToken() blocks until a token is available (useful for throttling, not rejection).
  5. 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.