Implement a thread-safe token bucket rate limiter.
Problem
Allow up to capacity requests in a burst and refill at ratePerSecond; tryAcquire() returns true if a request is allowed. It must be safe under heavy concurrency.
Approach
Keep tokens and lastRefillNanos. On each call, lazily add elapsed × rate tokens (capped at capacity), then take one if available. Make the read-compute-write atomic: here with a CAS loop over an immutable state object (lock-free), which avoids blocking threads. Use System.nanoTime() (monotonic) rather than wall-clock time.
import java.util.concurrent.atomic.AtomicReference;
class TokenBucket {
private record State(double tokens, long lastRefillNanos) {}
private final double capacity;
private final double tokensPerNano;
private final AtomicReference<State> state;
TokenBucket(double capacity, double ratePerSecond) {
this.capacity = capacity;
this.tokensPerNano = ratePerSecond / 1_000_000_000.0;
this.state = new AtomicReference<>(new State(capacity, System.nanoTime()));
}
boolean tryAcquire() { return tryAcquire(1); }
boolean tryAcquire(int permits) {
while (true) {
State current = state.get();
long now = System.nanoTime();
double refilled = Math.min(capacity, current.tokens() + (now - current.lastRefillNanos()) * tokensPerNano);
if (refilled < permits) {
// Not enough tokens; record the refill so time is not "lost", then reject
if (state.compareAndSet(current, new State(refilled, now))) return false;
continue;
}
if (state.compareAndSet(current, new State(refilled - permits, now))) return true;
// another thread changed the state; retry with fresh values
}
}
public static void main(String[] args) throws InterruptedException {
TokenBucket limiter = new TokenBucket(5, 2); // burst 5, 2 per second
int allowed = 0;
for (int i = 0; i < 10; i++) if (limiter.tryAcquire()) allowed++;
System.out.println("burst allowed: " + allowed); // 5
Thread.sleep(1000);
System.out.println("after 1s: " + limiter.tryAcquire() + ", " + limiter.tryAcquire() + ", " + limiter.tryAcquire()); // true, true, false
}
}Complexity
O(1) per call; lock-free, though retries increase under extreme contention.
Follow-up questions interviewers ask
Try answering each one before you open it.
How would you rate limit per user?
Keep a ConcurrentHashMap<String, TokenBucket> and use computeIfAbsent(userId, k -> new TokenBucket(...)). Bound the map (evict idle buckets with Caffeine's expireAfterAccess) so millions of users do not exhaust memory. Across several application instances, move the bucket state to Redis with a Lua script, as in the distributed rate limiter design.
How is this different from a sliding window limiter?
A token bucket allows bursts up to the bucket size and then enforces the average rate; a sliding window caps the count of requests in any rolling window (for example at most 100 in any 60 s), which prevents bursts beyond that count but needs either a log of timestamps or an approximation. Token buckets are usually preferred for APIs because short bursts are normal.