Advertisement
Intermediate Redis, Rate Limiting with Redis

What is the token bucket algorithm for rate limiting, and what advantage does it offer over a simple fixed window counter?

Short answer

The token bucket algorithm maintains a bucket that refills with tokens at a steady rate up to a maximum capacity, with each request consuming one token, allowing short bursts of traffic to be handled smoothly as long as tokens are available, while still enforcing an overall…

Save Redis mock interview
Advertisement
AModel answer
The token bucket algorithm maintains a bucket that refills with tokens at a steady rate up to a maximum capacity, with each request consuming one token, allowing short bursts of traffic to be handled smoothly as long as tokens are available, while still enforcing an overall average rate limit over time, unlike a fixed window which can allow a sudden burst right at the window boundary.
-- Simplified token bucket logic using a Lua script
local tokens = tonumber(redis.call('get', KEYS[1]) or capacity)
if tokens > 0 then
  redis.call('decrby', KEYS[1], 1)
  return 1
end
return 0
Real-world example
A video streaming service uses a token bucket rate limiter to allow occasional short bursts of requests from a user's device while still maintaining a steady average request rate over time, providing a smoother user experience than a strict fixed window.
Likely follow-ups
  • How do you implement the steady token refill process efficiently in Redis?
  • When is token bucket a better choice than sliding window log?
Related topics