Implementing a token bucket in Java
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite needs a limiter that allows short bursts but keeps a steady long-run rate. Under load, two threads or a wrong clock can break it. Can you build one small class you can trust?
The TokenBucket class: capacity, tokens, refillPerSecond, lastRefill
Token bucket is a limiter that holds up to capacity tokens, adds them at a fixed refill rate and lets a request pass only by taking one whole token.
A token bucket in code is four fields and one method. tryAcquire() takes a token if there is one and says whether it worked.
Example 1 · The TokenBucket class and a first run
import java.util.function.LongSupplier;
class TokenBucket { private final long capacity; private final double refillPerSecond; private final LongSupplier clockMillis; private double tokens; private long lastRefill;
TokenBucket(long capacity, double refillPerSecond, LongSupplier clockMillis) { this.capacity = capacity; this.refillPerSecond = refillPerSecond; this.clockMillis = clockMillis; this.tokens = capacity; // start full this.lastRefill = clockMillis.getAsLong(); }
synchronized boolean tryAcquire() { refill(); if (tokens >= 1) { tokens -= 1; return true; } return false; }
synchronized double available() { refill(); return tokens; }
private void refill() { // lazy: only when someone asks long now = clockMillis.getAsLong(); long elapsed = now - lastRefill; if (elapsed > 0) { tokens = Math.min(capacity, tokens + elapsed * refillPerSecond / 1000.0); lastRefill = now; } }}
class FakeClock implements LongSupplier { private long nowMillis;
public long getAsLong() { return nowMillis; } void advance(long millis) { nowMillis += millis; } void set(long millis) { nowMillis = millis; }}
public class TokenBucketDemo { public static void main(String[] args) { FakeClock clock = new FakeClock(); TokenBucket bucket = new TokenBucket(3, 1.0, clock); // 3 tokens, 1 new token a second
for (int i = 1; i <= 5; i++) { System.out.println("t=0 ms request " + i + ": " + (bucket.tryAcquire() ? "allowed" : "rejected")); } clock.advance(1_500); System.out.println("t=1500 ms tokens now " + bucket.available()); System.out.println("t=1500 ms request 6: " + (bucket.tryAcquire() ? "allowed" : "rejected")); System.out.println("t=1500 ms request 7: " + (bucket.tryAcquire() ? "allowed" : "rejected")); clock.advance(500); System.out.println("t=2000 ms request 8: " + (bucket.tryAcquire() ? "allowed" : "rejected")); }}t=0 ms request 1: allowed t=0 ms request 2: allowed t=0 ms request 3: allowed t=0 ms request 4: rejected t=0 ms request 5: rejected t=1500 ms tokens now 1.5 t=1500 ms request 6: allowed t=1500 ms request 7: rejected t=2000 ms request 8: allowed
What this code does
- Four fields hold the state:
capacity,tokens,refillPerSecondandlastRefill. The bucket starts full, so the first 3 requests pass and requests 4 and 5 are rejected. - After 1.5 seconds, 1.5 tokens have come back. Request 6 takes one, leaving 0.5, so request 7 is rejected. Half a second later the half token has grown to 1 and request 8 passes.
- The constructor takes a
LongSupplierfor the time, so the demo controls time withFakeClockand the output is the same on every run.
The four values are capacity (the most tokens it can hold), tokens (how many it holds now), refillPerSecond (how fast tokens come back) and lastRefill (when tokens were last added).
tokens is a double, because tokens come back in fractions: after 300 ms at 2 tokens a second there are 0.6 new tokens. A request still needs a whole token.
Lazy refill with an injectable clock
Lazy refill means no background timer adds tokens. Each call first adds elapsed × refillPerSecond tokens, caps them at capacity and moves lastRefill to now.
No timer adds tokens. Each call to tryAcquire first works out how much time has passed and adds the tokens that came back.
Example 2 · Mistake: lastRefill is never moved
import java.util.function.LongSupplier;
class BrokenBucket { private final long capacity = 3; private final double refillPerSecond = 1.0; private final LongSupplier clockMillis; private double tokens = 3; private final long lastRefill;
BrokenBucket(LongSupplier clockMillis) { this.clockMillis = clockMillis; this.lastRefill = clockMillis.getAsLong(); }
synchronized boolean tryAcquire() { long elapsed = clockMillis.getAsLong() - lastRefill; // always measured from the start tokens = Math.min(capacity, tokens + elapsed * refillPerSecond / 1000.0); if (tokens >= 1) { tokens -= 1; return true; } return false; }}
class FakeClock implements LongSupplier { private long nowMillis;
public long getAsLong() { return nowMillis; } void advance(long millis) { nowMillis += millis; } void set(long millis) { nowMillis = millis; }}
public class LastRefillBugDemo { public static void main(String[] args) { FakeClock clock = new FakeClock(); BrokenBucket bucket = new BrokenBucket(clock); for (int i = 0; i < 3; i++) bucket.tryAcquire(); // empty it at t = 0
int allowed = 0; for (long t = 1_000; t <= 2_000; t += 100) { // 11 requests in one second clock.set(t); if (bucket.tryAcquire()) allowed++; } System.out.println("Refill rate: 1 per second"); System.out.println("Allowed between 1.0 s and 2.0 s: " + allowed); }}Refill rate: 1 per second Allowed between 1.0 s and 2.0 s: 11
What this code does
- Every call adds tokens for the whole time since the bucket was created, because
lastRefillnever moves. At 1.0 s it adds 1 token, at 1.1 s another 1.1 tokens, and so on. - So a bucket meant to refill 1 token a second lets all 11 requests through. The fix is one line: after adding tokens, set
lastRefill = now, asTokenBucket.refill()does.
Example 3 · Mistake: no cap, so an idle hour becomes a huge burst
public class MissingCapDemo { public static void main(String[] args) { long capacity = 10; double refillPerSecond = 2.0; long idleMillis = 60 * 60 * 1000; // nobody called for an hour
double withoutCap = 0 + idleMillis * refillPerSecond / 1000.0; double withCap = Math.min(capacity, 0 + idleMillis * refillPerSecond / 1000.0);
System.out.println("Tokens after 1 idle hour, no cap: " + withoutCap); System.out.println("Tokens after 1 idle hour, with cap: " + withCap); System.out.println("Burst the client may now send: " + (long) withoutCap + " vs " + (long) withCap); }}Tokens after 1 idle hour, no cap: 7200.0 Tokens after 1 idle hour, with cap: 10.0 Burst the client may now send: 7200 vs 10
What this code does
- The capacity is the largest burst you are willing to accept. Without
Math.min(capacity, ...), quiet time keeps piling up tokens. - After one idle hour the client could fire 7,200 requests at once, which is exactly the flood the limiter exists to stop. With the cap the burst is 10.
The time comes from an injectable clock: a LongSupplier passed into the constructor. In production it is () -> System.nanoTime() / 1_000_000, which only moves forward, unlike the wall clock that can jump when the server's time is corrected. In tests it is a fake clock you move by hand.
Two lines decide whether the bucket is correct: lastRefill = now (or old time is counted again and again) and Math.min(capacity, ...) (or an idle client saves up a giant burst).
Find the bug
Spot the refill bug
Each snippet has one wrong line. Tap it, then read the fix.
Tokens must never go above the capacity.
Round 1 of 2Thread safety with synchronized
Race condition is a bug where two threads read and change the same data at the same moment, so the result depends on timing. Two requests can both take the last token.
A web server runs many threads at once, and two of them may use the same user's bucket. Without a lock, both can take the last token.
Example 4 · Thread-safe: 8 threads, exactly 1,000 tokens
import java.util.concurrent.atomic.AtomicInteger;import java.util.function.LongSupplier;
class TokenBucket { private final long capacity; private final double refillPerSecond; private final LongSupplier clockMillis; private double tokens; private long lastRefill;
TokenBucket(long capacity, double refillPerSecond, LongSupplier clockMillis) { this.capacity = capacity; this.refillPerSecond = refillPerSecond; this.clockMillis = clockMillis; this.tokens = capacity; // start full this.lastRefill = clockMillis.getAsLong(); }
synchronized boolean tryAcquire() { refill(); if (tokens >= 1) { tokens -= 1; return true; } return false; }
synchronized double available() { refill(); return tokens; }
private void refill() { // lazy: only when someone asks long now = clockMillis.getAsLong(); long elapsed = now - lastRefill; if (elapsed > 0) { tokens = Math.min(capacity, tokens + elapsed * refillPerSecond / 1000.0); lastRefill = now; } }}
public class ThreadSafeBucketDemo { public static void main(String[] args) throws InterruptedException { LongSupplier frozenClock = () -> 0L; // no refill during the test TokenBucket bucket = new TokenBucket(1_000, 0.0, frozenClock); AtomicInteger allowed = new AtomicInteger();
Thread[] workers = new Thread[8]; for (int i = 0; i < workers.length; i++) { workers[i] = new Thread(() -> { for (int j = 0; j < 500; j++) { if (bucket.tryAcquire()) allowed.incrementAndGet(); } }); workers[i].start(); } for (Thread w : workers) w.join();
System.out.println("Attempts: " + 8 * 500); System.out.println("Allowed: " + allowed.get() + " (capacity 1000)"); }}Attempts: 4000 Allowed: 1000 (capacity 1000)
What this code does
- 8 threads try 4,000 times on a bucket with 1,000 tokens and no refill. Because
tryAcquireissynchronized, only one thread at a time can read, check and changetokens, so exactly 1,000 pass on every run. - Remove
synchronizedand two threads can both readtokens = 1.0, both pass the check and both take it: the count can go above 1,000, and differs per run. That is a race condition (two threads changing shared data at the same time). - The test uses a frozen clock, so no tokens come back and the expected answer is known exactly.
tryAcquire reads tokens, checks it and changes it. If two threads do that at the same moment, both see 1.0 and both pass.
Marking tryAcquire and available as synchronized lets only one thread inside the bucket at a time. The work inside is a few arithmetic steps, so the lock is held for well under a microsecond and is not a bottleneck.
A repeatable simulation with a fake clock
Fake clock is a small class you control in tests: set(2500) or advance(500) moves time instantly, so a simulation prints the same lines on every run.
Pass the bucket a clock you move by hand, and feed it a fixed list of arrival times.
Example 5 · Simulation with a fake clock: capacity 3, 2 tokens a second
import java.util.function.LongSupplier;
class TokenBucket { private final long capacity; private final double refillPerSecond; private final LongSupplier clockMillis; private double tokens; private long lastRefill;
TokenBucket(long capacity, double refillPerSecond, LongSupplier clockMillis) { this.capacity = capacity; this.refillPerSecond = refillPerSecond; this.clockMillis = clockMillis; this.tokens = capacity; // start full this.lastRefill = clockMillis.getAsLong(); }
synchronized boolean tryAcquire() { refill(); if (tokens >= 1) { tokens -= 1; return true; } return false; }
synchronized double available() { refill(); return tokens; }
private void refill() { // lazy: only when someone asks long now = clockMillis.getAsLong(); long elapsed = now - lastRefill; if (elapsed > 0) { tokens = Math.min(capacity, tokens + elapsed * refillPerSecond / 1000.0); lastRefill = now; } }}
class FakeClock implements LongSupplier { private long nowMillis;
public long getAsLong() { return nowMillis; } void advance(long millis) { nowMillis += millis; } void set(long millis) { nowMillis = millis; }}
public class BucketSimulationDemo { public static void main(String[] args) { FakeClock clock = new FakeClock(); TokenBucket bucket = new TokenBucket(3, 2.0, clock); // one token every 500 ms long[] arrivals = {0, 0, 0, 0, 300, 500, 700, 1_000, 1_000, 2_500, 2_500, 2_500, 2_500}; int allowed = 0; for (long t : arrivals) { clock.set(t); boolean ok = bucket.tryAcquire(); if (ok) allowed++; System.out.printf("t=%5d ms %-8s tokens left %.1f%n", t, ok ? "allowed" : "rejected", bucket.available()); } System.out.println("Allowed " + allowed + " of " + arrivals.length); }}t= 0 ms allowed tokens left 2.0 t= 0 ms allowed tokens left 1.0 t= 0 ms allowed tokens left 0.0 t= 0 ms rejected tokens left 0.0 t= 300 ms rejected tokens left 0.6 t= 500 ms allowed tokens left 0.0 t= 700 ms rejected tokens left 0.4 t= 1000 ms allowed tokens left 0.0 t= 1000 ms rejected tokens left 0.0 t= 2500 ms allowed tokens left 2.0 t= 2500 ms allowed tokens left 1.0 t= 2500 ms allowed tokens left 0.0 t= 2500 ms rejected tokens left 0.0 Allowed 8 of 13
What this code does
- The first burst takes all 3 tokens. At 300 ms only 0.6 of a token is back, so the request is rejected; at 500 ms there is a full token again.
- After the quiet gap from 1.0 s to 2.5 s the bucket is full again (3.0), so the second burst gets 3 requests through and the 4th is rejected.
- A fixed list of arrival times plus a fake clock gives repeatable output, which is how you test a limiter without
Thread.sleep.
Every allowed and rejected request can then be checked by hand. This is far better than Thread.sleep in tests, which is slow and gives slightly different timings each run.
Predict the output
Predict the allowed and rejected requests
Capacity 2, refill 1 token a second. Y means allowed, N means rejected.
Five requests arrive at 0, 0, 0, 1000 and 1500 ms.
Per-key buckets in a ConcurrentHashMap, and cleaning idle ones
Idle clean-up is a job that removes buckets nobody has used for a while, so a map with one bucket per visitor does not grow forever. Nothing is lost: an idle bucket would have refilled to full.
Keep one bucket per user in a ConcurrentHashMap, and create it the first time a key appears.
Example 6 · One bucket per user in a ConcurrentHashMap, and cleaning idle ones
import java.util.TreeSet;import java.util.concurrent.ConcurrentHashMap;import java.util.function.LongSupplier;
class TokenBucket { private final long capacity; private final double refillPerSecond; private final LongSupplier clockMillis; private double tokens; private long lastRefill;
TokenBucket(long capacity, double refillPerSecond, LongSupplier clockMillis) { this.capacity = capacity; this.refillPerSecond = refillPerSecond; this.clockMillis = clockMillis; this.tokens = capacity; // start full this.lastRefill = clockMillis.getAsLong(); }
synchronized boolean tryAcquire() { refill(); if (tokens >= 1) { tokens -= 1; return true; } return false; }
synchronized double available() { refill(); return tokens; }
private void refill() { // lazy: only when someone asks long now = clockMillis.getAsLong(); long elapsed = now - lastRefill; if (elapsed > 0) { tokens = Math.min(capacity, tokens + elapsed * refillPerSecond / 1000.0); lastRefill = now; } }}
class FakeClock implements LongSupplier { private long nowMillis;
public long getAsLong() { return nowMillis; } void advance(long millis) { nowMillis += millis; } void set(long millis) { nowMillis = millis; }}
class UserRateLimiter { private static final long IDLE_MILLIS = 10 * 60 * 1000; // forget users idle for 10 minutes
private final ConcurrentHashMap<String, TokenBucket> buckets = new ConcurrentHashMap<>(); private final ConcurrentHashMap<String, Long> lastSeen = new ConcurrentHashMap<>(); private final LongSupplier clock;
UserRateLimiter(LongSupplier clock) { this.clock = clock; }
boolean tryAcquire(String userId) { lastSeen.put(userId, clock.getAsLong()); return buckets.computeIfAbsent(userId, id -> new TokenBucket(2, 1.0, clock)).tryAcquire(); }
int cleanUp() { long now = clock.getAsLong(); int before = buckets.size(); lastSeen.entrySet().removeIf(e -> { boolean idle = now - e.getValue() > IDLE_MILLIS; if (idle) buckets.remove(e.getKey()); return idle; }); return before - buckets.size(); }
TreeSet<String> users() { return new TreeSet<>(buckets.keySet()); }}
public class PerUserBucketsDemo { public static void main(String[] args) { FakeClock clock = new FakeClock(); UserRateLimiter limiter = new UserRateLimiter(clock);
for (String user : new String[] {"asha", "asha", "asha", "ravi", "meena"}) { System.out.println(user + ": " + (limiter.tryAcquire(user) ? "allowed" : "rejected")); } clock.advance(8 * 60 * 1000); limiter.tryAcquire("ravi"); clock.advance(5 * 60 * 1000); System.out.println("Buckets before clean-up: " + limiter.users()); System.out.println("Removed: " + limiter.cleanUp()); System.out.println("Buckets after clean-up: " + limiter.users()); }}asha: allowed asha: allowed asha: rejected ravi: allowed meena: allowed Buckets before clean-up: [asha, meena, ravi] Removed: 2 Buckets after clean-up: [ravi]
What this code does
- Each user gets their own bucket the first time they appear:
computeIfAbsentcreates it atomically, so two threads never create two buckets for the same user. - Asha's third request is rejected, but Ravi and Meena are not affected: limits are per key.
- Without clean-up the map grows with every user ever seen. Asha and Meena have been idle for 13 minutes, so
cleanUpremoves their buckets; a returning user simply gets a fresh, full bucket.
computeIfAbsent(key, k -> new TokenBucket(...)) creates the bucket safely across threads. Without clean-up the map grows with every visitor, so a job removes buckets unused for a while, such as 10 minutes.
A returning user simply gets a new full bucket, which is exactly what an idle one would have refilled to.
Order of execution
One request, one bucket
Put the steps in the order they happen.
Next step
Check your understanding
12 quick questions