Video in progress
How do you design a high-load rate limiter (token bucket) inside one JVM that doesn't use locks?
I keep the state in one immutable object (the token count and the last refill time) and update it with a CAS loop on an AtomicReference. It's lock-free and correct, but under very high contention CAS retries pile up. In that case, splitting by key or using a ready-made library is better.
📖 Answer
Token bucket: the capacity is capacity, rate tokens are added per second, and each request takes one token. The problem is that two fields (the tokens and the time) have to change together, atomically. Two separate AtomicLongs get this wrong: there's a moment when one is updated and the other is still old.
So I put the state into one immutable record:
final class TokenBucket {
private record State(double tokens, long lastNanos) { }
private final double capacity, perNano;
private final AtomicReference<State> state;
TokenBucket(double capacity, double perSecond) {
this.capacity = capacity;
this.perNano = perSecond / 1_000_000_000d;
this.state = new AtomicReference<>(new State(capacity, System.nanoTime()));
}
boolean tryAcquire() {
while (true) {
State cur = state.get();
long now = System.nanoTime();
double refilled = Math.min(capacity, cur.tokens() + (now - cur.lastNanos()) * perNano);
if (refilled < 1) return false; // no token: reject
State next = new State(refilled - 1, now);
if (state.compareAndSet(cur, next)) return true; // we won
// another thread changed it: recompute
}
}
}
What I paid attention to:
System.nanoTime()is monotonic, whilecurrentTimeMilliscan jump back on an NTP adjustment;- so that the time source can be replaced in tests, in practice I inject it as a
LongSupplier; - a new record on every attempt means allocation, but short-lived objects are cheap for the young GC.
The limits of this design:
- if hundreds of threads fight over one bucket, CAS failures eat CPU. The fix is a separate bucket per user or API key (
ConcurrentHashMap<Key, TokenBucket>, with Caffeine evicting stale keys); - this limit holds only inside one pod. With 10 pods, the total limit is 10 times higher. If you need a global limit, use a Lua script in Redis or do it at the API gateway level;
- if you need a blocking (waiting) mode, this code only does "reject"; for waiting, you'd compute when the next token arrives and
parkNanos.
In prod I usually take Resilience4j's RateLimiter or Bucket4j: they give you the same idea, better tested. I keep writing my own for interviews or a very special requirement.
Sign up to mark studied questions and save your progress.