Java Design Program · CD17
Implement a Rate Limiter in Java (Token Bucket)
A token bucket holds up to N tokens. Each request spends one; tokens trickle back at a fixed rate. Short bursts are allowed, but the long-run rate is capped.
Problem Statement
Write tryAcquire(nowMs) for a limiter with a capacity of 5 tokens that gains one token every 200 ms. It returns true and spends a token if one is available, otherwise false.
The bucket starts full and never holds more than its capacity. The current time is passed in, so the behaviour can be tested exactly.
Input/Output Examples
7 requests at t=0Output5 allowed, 2 rejectedExplanation: the full bucket covers 5 requests.2 requests at t=400Output2 allowedExplanation: 400 ms earned 2 tokens.1 request at t=500OutputrejectedExplanation: only half a token has been earned since t=400.6 requests at t=1600Output5 allowed, 1 rejectedExplanation: the bucket refilled but stops at its capacity of 5.Visual Explanation
- t=0tokens57 requests 5 allowed, 2 rejected
- t=400tokens0 + 22 requests 2 allowed
- t=500tokens0.51 request rejected
- t=1600tokens5 (capped)6 requests 5 allowed
- Doneburst of 5, then 5 per second
This lazy refill needs no timer thread: one subtraction, one minimum and one comparison per request.
Approaches
Both approaches implement the same token bucket and give the same answers for any sequence of requests.
Approach 1: Credit in Milliseconds (Recommended)
Idea: store the bucket as milliseconds of credit: one token is 200 ms, a full bucket is 1000 ms. Add the elapsed time, cap it, and spend 200 ms per request.
- Add
now - lastto the credit and cap it atcapacity × refillMs. - Remember
nowas the last time. - If the credit is at least one token, subtract it and allow the request.
- Otherwise reject.
Time: O(1) · Space: O(1). per request.
Approach 2: Whole Tokens and Refill Time
Idea: count whole tokens. Add one for every full 200 ms since the last refill and move the refill time forward by exactly that much.
- If the bucket is full, reset the refill time to now; a full bucket earns nothing.
- Otherwise add
(now - lastRefill) / refillMstokens, capped at the capacity. - Advance
lastRefillby the intervals used, keeping the leftover time. - Spend a token if one is available.
Time: O(1) · Space: O(1).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Credit in Milliseconds (Recommended)
Integer arithmetic only, so there is no floating-point drift, and partial tokens are kept automatically.
public class RateLimiterCredit {
// Token bucket with lazy refill. Credit is kept in milliseconds of waiting:
// one token = refillMs of credit, a full bucket = capacity * refillMs. All integer, so no rounding.
static class RateLimiter {
private final long refillMs;
private final long maxCredit;
private long credit;
private long lastMs;
RateLimiter(int capacity, long refillMs) {
this.refillMs = refillMs;
this.maxCredit = capacity * refillMs;
this.credit = maxCredit; // start with a full bucket
}
synchronized boolean tryAcquire(long nowMs) {
credit = Math.min(maxCredit, credit + (nowMs - lastMs)); // refill only when asked
lastMs = nowMs;
if (credit >= refillMs) {
credit -= refillMs;
return true;
}
return false;
}
}
public static void main(String[] args) {
// capacity 5, one new token every 200 ms (5 per second); the clock is passed in, so the run is exact
RateLimiter limiter = new RateLimiter(5, 200);
burst(limiter, 0, 7);
burst(limiter, 400, 2);
burst(limiter, 500, 1);
burst(limiter, 1600, 6);
}
static void burst(RateLimiter limiter, long nowMs, int requests) {
int allowed = 0;
for (int i = 0; i < requests; i++) {
if (limiter.tryAcquire(nowMs)) allowed++;
}
System.out.println("t=" + nowMs + " ms, burst of " + requests + ": " + allowed + " allowed, " + (requests - allowed) + " rejected");
}
}
t=0 ms, burst of 7: 5 allowed, 2 rejected t=400 ms, burst of 2: 2 allowed, 0 rejected t=500 ms, burst of 1: 0 allowed, 1 rejected t=1600 ms, burst of 6: 5 allowed, 1 rejected
Time complexity: O(1) · Space complexity: O(1).
Approach 2: Whole Tokens and Refill Time
Closer to how the algorithm is usually explained, with a little more bookkeeping.
public class RateLimiterTokens {
// Token bucket with whole tokens: add one token for every full refill interval that has passed,
// and move the refill time forward by exactly those intervals so partial progress is kept.
static class RateLimiter {
private final int capacity;
private final long refillMs;
private int tokens;
private long lastRefillMs;
RateLimiter(int capacity, long refillMs) {
this.capacity = capacity;
this.refillMs = refillMs;
this.tokens = capacity;
}
synchronized boolean tryAcquire(long nowMs) {
long intervals = (nowMs - lastRefillMs) / refillMs;
if (tokens == capacity) {
lastRefillMs = nowMs; // a full bucket earns nothing while it waits
} else if (intervals > 0) {
if (tokens + intervals >= capacity) {
tokens = capacity;
lastRefillMs = nowMs; // full: leftover time is lost, as in a real bucket
} else {
tokens += (int) intervals;
lastRefillMs += intervals * refillMs;
}
}
if (tokens > 0) {
tokens--;
return true;
}
return false;
}
}
public static void main(String[] args) {
// capacity 5, one new token every 200 ms (5 per second); the clock is passed in, so the run is exact
RateLimiter limiter = new RateLimiter(5, 200);
burst(limiter, 0, 7);
burst(limiter, 400, 2);
burst(limiter, 500, 1);
burst(limiter, 1600, 6);
}
static void burst(RateLimiter limiter, long nowMs, int requests) {
int allowed = 0;
for (int i = 0; i < requests; i++) {
if (limiter.tryAcquire(nowMs)) allowed++;
}
System.out.println("t=" + nowMs + " ms, burst of " + requests + ": " + allowed + " allowed, " + (requests - allowed) + " rejected");
}
}
t=0 ms, burst of 7: 5 allowed, 2 rejected t=400 ms, burst of 2: 2 allowed, 0 rejected t=500 ms, burst of 1: 0 allowed, 1 rejected t=1600 ms, burst of 6: 5 allowed, 1 rejected
Time complexity: O(1) · Space complexity: O(1).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Credit in Milliseconds | O(1) | O(1) |
| Whole Tokens and Refill Time | O(1) | O(1) |
Each request does a fixed number of arithmetic steps, and the limiter stores only a few numbers per bucket, so it scales to one bucket per user or API key.
Interview Tips and Recommended Approach
- Compare the algorithms: token bucket allows bursts; leaky bucket smooths them; fixed windows allow double bursts at window edges.
- Refill lazily. A timer thread per bucket does not scale to thousands of users.
- Make
tryAcquire()synchronized or use an atomic compare-and-set; two threads must not spend the same token. - For many servers, keep the bucket in a shared store such as Redis and update it atomically.
Recommended Approach: Credit in Milliseconds
Why: it stores a single number, uses only integer maths and cannot drift, which makes it easy to reason about and to test with a fake clock.