Lesson 2 of 9 · 25m
Token Buckets, Leaky Buckets, and Burst Control
Use bucket semantics deliberately: capacity controls burst size, refill rate controls sustained use, and cost weighting controls real resource consumption.
Token buckets are popular because they mirror how real systems behave: users pause, then act in bursts. A fixed counter punishes normal interactivity; a bucket lets a client save idle capacity and spend it quickly. That is usually desirable — until the bucket becomes large enough to flatten your database every minute. The algorithm is simple. The policy encoded in its parameters is not.
The token bucket mental model
A bucket has capacity C and refills at rate R. Each operation attempts to withdraw cost W:
if tokens >= W:
tokens -= W
allow
else:
reject or deferR controls sustained throughput. C controls burst size. W lets you price operations differently. These knobs are independent, and changing one while pretending you changed another is a common operations mistake.
A concrete implementation shape
def allow(bucket, now, cost=1.0):
elapsed = max(0.0, now - bucket.updated_at)
bucket.tokens = min(bucket.capacity,
bucket.tokens + elapsed * bucket.refill_per_second)
bucket.updated_at = now
if bucket.tokens >= cost:
bucket.tokens -= cost
return True
return FalseThe production version needs atomic compare-and-set or a datastore-native script. The race matters because concurrent requests can read the same token count and all withdraw it.
Leaky bucket is a queue, not a synonym
People use "leaky bucket" loosely. Strictly, it smooths work by leaking queued units at a constant rate:
arrival -> queue if capacity remains -> worker drains at fixed rateUse token buckets when the client may burst up to a bounded allowance. Use queues or concurrency limits when downstream capacity must remain smooth. Many APIs need both: a tenant bucket for fairness and a worker concurrency cap for survival.
Weight cost honestly
A search endpoint may price by result complexity:
cost = 1 + (limit // 50)
if include_archived:
cost *= 3
if query_has_expensive_sort:
cost *= 2Do not pretend precision you cannot measure. A rough but honest cost model beats exact request counting that ignores the real amplifier. Measure with production traces: rows scanned, cache misses, queue duration, bytes read, and downstream calls.
Choose numbers from service math
If a database can absorb 300 expensive queries per second with headroom, and five tenants should not consume more than half collectively, tenant refill rates and burst caps must sum into that budget. Write the arithmetic down. Limits copied from another API are usually wrong because the hidden capacity model is different.
Field notes
- A huge bucket is a denial-of-service grant with a slower billing cycle.
- Refilling continuously at request time avoids timer jobs but still requires atomic state updates.
- Bucket reset behavior must be explicit; operators will otherwise assume quota and burst mean the same thing.
- Rejecting one cheap request while permitting one expensive operation means your cost model is inverted.
Was this lesson helpful?