Video in progress
Compare the token bucket and sliding window log rate limiters as algorithms. Which do you choose when?
A token bucket works with two numbers per client, the token count and the last refill time, allows bursts and uses O(1) memory. A sliding window log stores every request time, is the most accurate, but its memory is proportional to the limit. In most cases a token bucket or a sliding window counter is enough.
📖 Answer
Token bucket:
final class TokenBucket {
private final long capacity;
private final double refillPerNano;
private double tokens;
private long last;
TokenBucket(long capacity, double perSecond) {
this.capacity = capacity;
this.refillPerNano = perSecond / 1_000_000_000.0;
this.tokens = capacity;
this.last = System.nanoTime();
}
synchronized boolean tryAcquire() {
long now = System.nanoTime();
tokens = Math.min(capacity, tokens + (now - last) * refillPerNano); // lazy refill
last = now;
if (tokens < 1) return false;
tokens -= 1;
return true;
}
}
There is no timer: tokens are added when a request arrives, based on the elapsed time. It uses System.nanoTime(), not currentTimeMillis(): even if the clock jumps backward through NTP, the time difference never goes negative.
The comparison:
| Token bucket | Fixed window | Sliding log | Sliding counter | |
|---|---|---|---|---|
| Memory / key | 2 numbers | 1 number | N timestamps | 2 numbers |
| Accuracy | allows burst | 2× burst at the boundary | exact | approximate, good |
| Complexity | O(1) | O(1) | O(log N) or amortized O(1) | O(1) |
The problem with a fixed window: 100 requests at 12:00:59 and another 100 at 12:01:00 is 200 in one second. A sliding window counter softens this by weighting the current and previous window counts by their time fraction.
I use a sliding log only when the limit is small and accuracy matters, for example "password reset: 5 attempts per hour".
In the distributed case, where the state lives matters more than the algorithm itself. In Redis, making the token bucket atomic with a Lua script is the usual solution. A local bucket on every instance is fast, but the global limit gets multiplied by the number of instances. A ready-made library like Bucket4j is often better than what we'd write ourselves.
Sign up to mark studied questions and save your progress.