Sub topic 8
Token bucket: steady rate with controlled bursts
This chapter assumes you know basic HTTP request and response concepts, can read Python, and have seen the fixed window counter from the previous chapters. It covers how the token bucket works, how to implement it, how to choose its two parameters, and where it commonly goes wrong.
The model
A token bucket limiter keeps two numbers for each client: how many tokens are in the bucket, and when the bucket was last updated. Each request must take tokens from the bucket. If enough tokens are available, the request is allowed and the tokens are removed. If not, the request is rejected.
Tokens are added at a constant rate, up to a maximum. The two parameters are:
- capacity: the largest number of tokens the bucket can hold. This is the burst size.
- refill rate: tokens added per second. This is the long-run average rate.
A client that has been idle has a full bucket, so it can send capacity requests at once. After that, it can sustain only refill_rate requests per second. Over any long period, the limiter allows at most refill_rate * duration + capacity requests.
Lazy refill
A naive design runs a timer that adds tokens to every bucket each second. That costs work for every client, including idle ones. The standard approach is lazy refill. Nothing happens between requests. When a request arrives, the limiter computes how many tokens would have been added since the last update and applies them at once.
This makes the cost per request constant, and the state per client is just two values.
A single-process implementation
import time
class TokenBucket:
"""Single-process token bucket. Not thread-safe."""
def __init__(self, capacity, refill_rate):
self.capacity = capacity # maximum tokens (burst size)
self.refill_rate = refill_rate # tokens added per second
self.tokens = float(capacity)
self.last = time.monotonic()
def allow(self, cost=1):
now = time.monotonic()
elapsed = now - self.last
self.last = now
self.tokens = min(self.capacity, self.tokens + elapsed * self.refill_rate)
if self.tokens >= cost:
self.tokens -= cost
return True
return False
bucket = TokenBucket(capacity=5, refill_rate=1)
print([bucket.allow() for _ in range(7)]) # first 5 True, then FalsePoints worth noticing in this code:
- The bucket starts full, so a new client gets an immediate burst. Some systems start it empty to avoid this.
time.monotonic()is used instead oftime.time(). A monotonic clock never goes backwards, so a system clock adjustment cannot produce negative elapsed time.min(self.capacity, ...)is what limits the burst. Without it, a long idle period would store unlimited tokens.self.lastis updated on every call, including rejected ones. This is correct because the refill has already been applied toself.tokens. If you only updatedlaston success, the same elapsed time would be credited twice.- Tokens are floats. At 1 token per second, a request after 0.5 seconds sees 0.5 tokens and is rejected, and the half token is kept for the next call.
- The
costparameter lets expensive operations spend more than one token. A search endpoint might cost 5, while a simple read costs 1.
Choosing capacity and refill rate
The two parameters control different things, so choose them separately.
| Goal | Parameter | Example |
|---|---|---|
| Long-run average rate | `refill_rate` | 10 requests per second |
| Largest instant burst | `capacity` | 20 requests |
| Time to recover from empty to full | `capacity / refill_rate` | 20 / 10 = 2 seconds |
Some practical guidance:
- Start from the sustained rate your backend can handle per client, and set
refill_rateto that. - Set
capacityfrom how bursty legitimate clients are. A page load that fires 8 API calls at once needs a capacity of at least 8. - If
capacityis 1, the bucket allows no bursts and enforces an even spacing of requests. This is very strict. - If
capacityis large compared withrefill_rate, a client can use a long idle period to send a big burst. Check that the backend can survivecapacitysimultaneous requests from many clients at once.
A limit expressed as "100 requests per minute" does not map to one unique bucket. You could use refill_rate = 100/60 with capacity = 100, or with capacity = 10. The first allows 100 requests in one second. The second allows 10 at once and then about 1.67 per second. State which behavior you want.
Comparison with the fixed window
The fixed window counter allows up to twice its limit across a window boundary. For example, with a limit of 100 per minute, a client can send 100 requests at 10:00:59 and 100 more at 10:01:00. A token bucket does not have this problem. Its maximum burst is capacity, whatever the wall-clock time, and the bucket refills smoothly rather than resetting at a boundary.
The cost is a little more arithmetic per request and floating-point state. The token bucket also does not give an exact answer to "how many requests did this client make in the last minute?" It only tracks the current token balance.
Making it distributed
The class above keeps state in one process. Behind a load balancer, each application server would have its own bucket, and a client could get N times the intended rate. The state has to move to a shared store such as Redis.
The read, refill, decision, and write steps must happen as one atomic unit. If two servers read the same token count and both subtract from it, both can spend the same token. A Redis Lua script runs without interruption, so it closes that race. It also uses the Redis server clock through TIME, which avoids skew between application servers.
-- KEYS[1] = bucket key
-- ARGV[1] = capacity, ARGV[2] = refill rate (tokens per second), ARGV[3] = cost
local key = KEYS[1]
local capacity = tonumber(ARGV[1])
local rate = tonumber(ARGV[2])
local cost = tonumber(ARGV[3])
local t = redis.call('TIME')
local now_ms = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)
local data = redis.call('HMGET', key, 'tokens', 'ts')
local tokens = tonumber(data[1])
local ts = tonumber(data[2])
if tokens == nil then
tokens = capacity
ts = now_ms
end
local elapsed_ms = math.max(0, now_ms - ts)
tokens = math.min(capacity, tokens + (elapsed_ms / 1000) * rate)
local allowed = 0
if tokens >= cost then
tokens = tokens - cost
allowed = 1
end
redis.call('HSET', key, 'tokens', tokens, 'ts', now_ms)
redis.call('EXPIRE', key, math.ceil(capacity / rate) * 2)
return allowedDetails in the script:
math.max(0, ...)protects against a negative elapsed time if the Redis clock moves backwards, for example after a failover to a replica with a different clock.- The
EXPIREvalue is twice the time needed to refill from empty. After that long idle, a bucket would be full anyway, so deleting it loses nothing and keeps memory bounded. A missing key is treated as a full bucket. - The script returns only allowed or not allowed. To send a useful
Retry-Afterheader, you would also return the current token count and compute the wait as(cost - tokens) / rate.
Common errors
- No cap on refill. Forgetting
min(capacity, ...)lets idle clients accumulate unlimited burst. - Using wall-clock time in one process.
time.time()can jump. Use a monotonic clock locally, or a single shared time source in a distributed system. - Sharing one bucket across threads without a lock. The Python class is not thread-safe. Two threads can pass the check together and overspend.
- Splitting the read and write in Redis. A
GETfollowed by aSETfrom the application is not atomic, even if each call is fast. - Setting cost above capacity. A request that costs more than
capacitycan never succeed. Validate this at configuration time. - Ignoring key cardinality. One bucket per IP address or per API key means memory grows with the number of distinct clients. The expiry in the script limits this.
Exercise
A bucket has capacity 10 and refill rate 2 tokens per second. It is full. A client sends 10 requests at once, then waits 3 seconds and sends 10 more at once. How many of the second 10 requests are allowed, and why?
Show answer
Six. After the first burst the bucket is empty. In 3 seconds it gains 3 x 2 = 6 tokens, which is below the cap of 10, so six requests succeed and the other four are rejected.
Exercise
Why does the Redis script use the Redis server clock through TIME rather than a timestamp sent by each application server?
Show answer
Application servers' clocks can differ. If each server supplied its own timestamp, the same bucket would be refilled by inconsistent amounts, and a server with a fast clock would grant extra tokens. A single clock source on the Redis server gives one consistent view of time for every request.