How it works
A token bucket stores up to a capacity of tokens. Tokens refill over time. Each request consumes a token if one is available; otherwise it is throttled. A capacity of 10 and a refill of 2 tokens per second permits a burst of 10 after idleness, then sustains roughly 2 requests per second. Refill is capped at capacity, so unused allowance does not grow without bound.
With those numbers: at 0 seconds the bucket is full and 10 requests arrive, leaving no tokens. At 1.5 seconds it has earned 3 tokens. Four requests then arrive: three pass and one is rejected. Over a full minute it can admit at most 130: the starting 10 plus 120 from refill. No background timer is needed; store the token count and the last update time, then work out the refill when the next request arrives. Amazon API Gateway describes its throttling this way, with a rate and a burst setting.
This is useful when ordinary traffic arrives in short bursts but its average should remain bounded. It is a poor fit when the protected system cannot absorb a burst, since a full bucket releases its whole capacity at once. A leaky bucket instead drains a finite queue at a steady pace, which is helpful when downstream work needs a smooth output rate; NGINX’s limit_req module uses this method. With room for 20 queued requests and a drain of 5 per second, the last one waits 4 seconds. When the queue fills, requests must be rejected or handled by another explicit policy.
An API may accept ten rapid actions after idle time but only two per second thereafter. Which parameters fit?
Use a token bucket with capacity 10 and refill rate 2 tokens per second, assuming each action costs one token. Specify how precise the burst guarantee must be across distributed instances.
Use this as a guide for self review; written answers are not graded.Keep in mind
- Token capacity and refill rate control different behavior.
- Leaky bucket smooths output but introduces queue delay.