Video in progress
How do the token bucket and fixed window algorithms differ in rate limiting?
Fixed window keeps a counter for each time interval (for example, a minute) and can let through double the load at the boundary. Token bucket refills tokens evenly, allows short bursts, but holds the average rate firmly.
📖 Answer
Fixed window. The key is rl:{user}:{minute}, INCR on every request, limit 100. Very simple. The problem is at the boundary: a user sends 100 requests at 12:00:59 and another 100 at 12:01:00 — 200 in 2 seconds, double the limit.
Sliding window softens this problem: it counts the requests in the last 60 seconds (an exact log, or an approximation between two windows).
Token bucket. The bucket holds at most capacity tokens, and rate tokens are added every second. Each request takes one token, and if there are none — 429.
// Bucket4j: 100 per minute, allowing a burst of up to 20 at once
Bandwidth limit = Bandwidth.builder()
.capacity(20)
.refillGreedy(100, Duration.ofMinutes(1))
.build();
Bucket bucket = Bucket.builder().addLimit(limit).build();
if (!bucket.tryConsume(1)) {
return ResponseEntity.status(429).build();
}
Token bucket is the most convenient for APIs: it's normal for 10 parallel requests to go out when a person opens a page, but over a long period the average rate is capped.
Leaky bucket is similar, except it lets requests out at a constant rate — for smoothing a queue, for example when sending requests to an external SMS provider.
Don't forget to return a Retry-After header along with 429 Too Many Requests.
Sign up to mark studied questions and save your progress.