Sub topic 11
Admission control and token buckets
This chapter assumes you can read short Python examples and know HTTP status codes and request latency. It also assumes you have met bounded queues, load shedding, and the idea of telling clients about overload from earlier chapters.
What admission control does
Admission control is a decision made at the front door: should this request enter the system at all? A request that is refused costs almost nothing. A request that is accepted and then abandoned halfway costs a lot, because it has already used CPU, memory, and downstream calls.
Load shedding from the previous chapters reacts to the state of the system, such as a full queue. Admission control can also be proactive. It limits how fast work may arrive, whatever the current queue depth, so overload is less likely to build up in the first place.
The common form of this is rate limiting. A rate limit says "this caller may send at most R requests per second". Rate limits protect a service in three ways:
- They cap how much any single client can take, so one noisy caller cannot starve the others.
- They keep total admitted load near what you measured the service can handle.
- They make the rejection point cheap, early, and predictable.
Choosing a rate limiting algorithm
Several algorithms exist. They differ in how they treat bursts and how much state they keep.
| Algorithm | Behavior | State per key | Burst handling |
|---|---|---|---|
| Fixed window counter | Counts requests in each calendar window, such as each second | One counter and a window ID | Allows up to twice the limit across a window boundary |
| Sliding window log | Stores a timestamp for each recent request | One entry per request | Exact, but memory grows with the limit |
| Leaky bucket | Requests drain at a constant rate, and extra requests wait or are dropped | A level and a timestamp | Smooths output to a steady rate |
| Token bucket | Tokens refill at a steady rate, and each request spends tokens | A token count and a timestamp | Allows bursts up to the bucket size |
The token bucket is the most common choice because it expresses what most services want: a sustained average rate plus a bounded burst. It also needs only two numbers of state per client.
How a token bucket works
Picture a bucket that holds up to capacity tokens. Tokens are added at rate tokens per second, and the bucket never holds more than capacity. Each request must take cost tokens, normally 1. If enough tokens are present, the request is admitted and the tokens are removed. If not, the request is rejected.
Two parameters control the behavior:
rateis the long-run average. Over a long period, a client cannot exceed this many requests per second.capacityis the burst allowance. A client that has been idle has a full bucket and can sendcapacityrequests at once.
Notice that no background timer adds tokens. The bucket is refilled lazily, when a request arrives, by computing how much time has passed. This is why a bucket per client is cheap: an idle client costs only two numbers in memory and no CPU.
Implementing a token bucket
The implementation below follows the lazy refill idea.
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 FalseThree details matter here.
- It uses
time.monotonic(), nottime.time(). The wall clock can jump backwards when it is adjusted, which would corrupt the token count. The monotonic clock only moves forward. - The refill is capped with
min(self.capacity, ...). Without the cap, a client that was idle for an hour would accumulate a huge burst allowance. - The bucket starts full. That lets a new client send a first burst. Start it empty if you do not want that.
This version is not thread-safe. Two threads could both read self.tokens, both see enough tokens, and both subtract, admitting more than the limit. In a single asyncio event loop it is safe, because allow() has no await and so cannot be interrupted. With threads, wrap the body in a threading.Lock.
Using a bucket to admit requests
To tie the bucket to the signals from the previous chapter, reject with 429 when a client exceeds its own limit. Here is a small, runnable example that keeps one bucket per client.
import time
class TokenBucket:
def __init__(self, rate: float, capacity: float) -> None:
self.rate = rate
self.capacity = capacity
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 False
def retry_after(self, cost: float = 1.0) -> float:
"""Seconds until `cost` tokens will be available."""
missing = max(0.0, cost - self.tokens)
return missing / self.rate
buckets: dict[str, TokenBucket] = {}
def admit(client_id: str):
bucket = buckets.setdefault(client_id, TokenBucket(rate=5, capacity=10))
if bucket.allow():
return 200, {}
wait = max(1, round(bucket.retry_after() + 0.5))
return 429, {"Retry-After": str(wait)}
if __name__ == "__main__":
results = [admit("alice")[0] for _ in range(15)]
print(results)Run it and the first 10 calls return 200, because the bucket starts full with capacity 10. The remaining calls return 429, since the loop runs far faster than the refill rate of 5 tokens per second. The retry_after method turns the token deficit into a useful hint for the client.
Per-client limits versus global limits
You choose what the bucket is keyed on, and the choice changes what is protected.
- A per-client bucket (keyed by API key, user, or IP address) gives fairness. One heavy client is limited without hurting others.
- A global bucket protects the service as a whole. It is a coarse cap on total admitted work.
- A per-endpoint bucket gives expensive operations, such as search or report generation, a tighter limit than cheap ones. Alternatively, use one bucket and set
costhigher for expensive requests.
Using both a per-client and a global limit is common. The per-client limit is checked first, so that a rejected request does not consume global tokens.
Edge cases and gotchas
The sum of client limits can exceed capacity. If you give 1,000 clients a limit of 10 requests per second each, the service may be asked to handle 10,000 requests per second. Per-client limits provide fairness, not protection. You still need a global limit or a concurrency limit, covered in the next chapter.
Limits are not the same as capacity. A static rate is a guess about what the service can handle. If a dependency slows down, the real capacity drops while the configured rate stays the same. Rate limiting does not notice. Pair it with reactive mechanisms like bounded queues and deadlines.
Memory for many keys. A dictionary of buckets grows with the number of distinct clients. Attackers can create many keys, for example by rotating IP addresses. Evict buckets that have been full for a while, since a full bucket is equivalent to a new one, or use a bounded cache.
Distributed limiters. With several servers, each server's local bucket allows its own rate, so the total is the sum. Sharing state in a central store such as Redis gives an exact limit but adds a network call to every request, and a new failure point. A common compromise divides the limit across servers, accepting some inaccuracy. Decide what the limiter should do if its store is unreachable. Failing open keeps traffic flowing but removes protection. Failing closed protects the service but causes an outage.
Burst size is a real decision. A large capacity is friendly to bursty clients but lets them hit the service all at once. If the service cannot survive a burst of capacity requests, the bucket is too big, even if the average rate is fine.
Rejecting is not free. The check should happen as early as possible, before parsing bodies or authenticating against a database. Otherwise the cost of saying no starts to resemble the cost of saying yes.
Rate limiting versus load shedding
Both reject requests, but for different reasons.
| Row | Rate limiting | Load shedding |
|---|---|---|
| Trigger | A caller exceeds its allowance | The service is actually overloaded |
| Depends on service state | No | Yes |
| Typical status | 429 | 503 |
| Main goal | Fairness and a predictable ceiling | Staying responsive under real saturation |
A well-run service uses both. Rate limits keep any single caller within its share. Shedding handles the case where the combined demand is still too high, or where the service has slowed down for some other reason.
Exercise
A token bucket has rate 20 tokens per second and capacity 100. A client has been idle for a long time, then sends 150 requests instantly, one token each. How many are admitted at once, and roughly how many more can it send during the next 2 seconds?
Show answer
The bucket is full at 100 tokens, so 100 requests are admitted at once and the other 50 are rejected. During the next 2 seconds the bucket refills at 20 tokens per second, which is about 40 tokens, so roughly 40 more requests can be admitted.
Exercise
Why does the token bucket in this chapter use time.monotonic() and cap tokens at capacity?
Show answer
time.monotonic() never goes backwards, so clock adjustments cannot produce negative elapsed time or a corrupted token count. The cap stops an idle client from accumulating unlimited tokens, which would allow an enormous burst when it returns.