Sub topic 11
Admission control and token buckets
This chapter assumes you know what load shedding is, how bounded queues work, and how to read short Python examples. It covers admission control, which decides at the front door whether a request may enter, and the token bucket, a common way to enforce a rate.
Admission control
Admission control checks each request before the service does any work on it. If the service is over a limit, the request is rejected right away. This costs far less than accepting the request, queueing it, and timing it out later.
Two kinds of limit are common:
- A rate limit caps how many requests are admitted per unit of time.
- A concurrency limit caps how many requests are in flight at once. The next chapter covers it.
A rate limit protects you from a client sending too fast. It does not know how loaded the service is. If each request suddenly becomes ten times slower, an admitted rate that was safe yesterday can overload you today. Treat the rate as a coarse guard and pair it with other limits.
The token bucket
A token bucket holds tokens. Tokens are added at a steady rate, up to a maximum capacity. Each request must take a token to proceed. If the bucket has no token, the request is rejected.
Two numbers define the behavior:
| Parameter | Meaning | Effect |
|---|---|---|
| rate | Tokens added per second | Long-run average admitted rate |
| capacity | Maximum tokens stored | Largest burst admitted at once |
An idle client builds up tokens, so a short burst passes. A client that keeps sending is held to the steady rate.
import time
class TokenBucket:
def __init__(self, rate: float, capacity: float) -> None:
self.rate = rate # tokens added per second
self.capacity = capacity # maximum burst size
self.tokens = capacity
self.updated = time.monotonic()
def allow(self, cost: float = 1.0) -> bool:
now = time.monotonic()
self.tokens = min(self.capacity, self.tokens + (now - self.updated) * self.rate)
self.updated = now
if self.tokens >= cost:
self.tokens -= cost
return True
return FalseThe bucket does not run a timer. On each call, allow() works out how many tokens arrived since the last call and adds them, capped at capacity. This is cheap and needs no background task. It uses time.monotonic() because that clock never jumps backward when the system time is adjusted.
The cost argument lets expensive requests take more tokens than cheap ones. A search that costs ten times as much as a lookup can be charged ten tokens.
This version is not thread-safe. In a single asyncio event loop it is safe, because allow() has no await. With threads, protect it with a lock.
A worked example
Suppose TokenBucket(rate=5, capacity=10):
- The bucket starts full with 10 tokens.
- A burst of 10 requests arrives at once. All are admitted and the bucket is empty.
- An 11th request right after is rejected.
- After 0.4 seconds, 2 tokens have been added, so 2 more requests pass.
The burst of 10 is allowed once. Over any longer period, the average stays at 5 per second.
Choosing and using the values
- Set
ratebelow the throughput you measured at saturation, with headroom. Setting it at the limit leaves no margin for slow dependencies. - Set
capacityto the largest burst you can absorb without growing latency. A larger capacity is more forgiving to clients and riskier for you. - Keep one bucket per client or API key when you want fairness. A single global bucket lets one noisy client use every token.
- When
allow()returnsFalse, answer with 429 and aRetry-Afterheader, so clients know when to come back.
Exercise
A bucket is created with rate=2 and capacity=6 and starts full. Ten requests arrive at the same instant, then nothing else for 3 seconds, then ten more arrive at the same instant. How many requests are admitted in each burst?
Show answer
The first burst admits 6 requests, because the bucket holds 6 tokens, and rejects 4. After 3 seconds, 3 × 2 = 6 tokens have been added, which reaches the capacity of 6. The second burst also admits 6 and rejects 4.