The token bucket: a rate and a burst
Refusing on purpose
Section titled “Refusing on purpose”Every service has a rate it can sustain. A client that sends more, whether by a bug, by greed or by attack, takes capacity from everyone else. A rate limit is a rule that refuses requests above an allowed rate, so that one client cannot use up what the others need. Microsoft’s documentation for ASP.NET Core lists the reasons: preventing abuse, giving every user fair access, protecting the resources behind the service from overload, and keeping the cost of a metered service predictable. The same page is clear about what it is not: rate limiting helps against a denial-of-service attack, but it is not a complete answer to a distributed one, which is why it recommends a dedicated DDoS protection service for that.
The refusal has a name in HTTP. RFC 6585 defines the status code 429 and says that it indicates that the user has sent too many requests in a given amount of time. The response should explain the condition, and it may carry a Retry-After header that says how long to wait before sending a new request. The RFC leaves the rest open: it does not define how the server identifies the user, or how it counts requests. That is the subject of this module, starting with the algorithm that most services use.
A bucket of tokens
Section titled “A bucket of tokens”Stripe describes the token bucket like this: every request takes a token out of a bucket, and tokens are put back slowly. If the bucket is empty, the request is refused. AWS API Gateway names the two numbers that configure it: the rate is the number of requests a second at which tokens are added to the bucket, and the burst is the capacity of the bucket.
Those two numbers answer two different questions.
- The rate is the sustained speed. Over a long time, a client cannot get more than this many requests a second, because that is how fast tokens come back.
- The bucket size is the burst. A client that has been quiet finds a full bucket and can spend all of it at once, however fast it sends.
Mental model. A token bucket remembers how much room is left. Idle time fills it, up to the size of the bucket, and requests empty it. The rate is how fast it fills, and the size is how much it can hold. A short burst depends on the size, and a long overload depends on the rate.
The bucket never delays a request. It decides now: a token is there and the request goes through, or none is and the request is refused. That makes it cheap, since the whole state is one number (the tokens left) and the time of the last refill.
Try it: a burst against a bucket
Section titled “Try it: a burst against a bucket”The lab sends bursty traffic to five limiters at once and shows one of them, the Limiter shown. Here that is the token bucket. The traffic is nothing for most of the time, then 30 requests in each of two seconds, every 20 seconds, which is 3 a second on average. The Rate limit is 5 a second, so the average load is below the limit, and the Bucket size is 60.
The lab runs by itself, one second every half second. Press Pause and then Reset so that it stands at second 40, where the figures below are read. Whenever you change the Rate limit, the Bucket size, the Window or the Gateways, the run starts again at second 40.
A bucket of 60 tokens absorbs a burst of 30 requests in each of two seconds, then refills at 5 a second. Make the bucket smaller and watch requests get rejected.
What is happening
The limit is 5 requests a second on average: 50 in 10 seconds.
Token bucket: the bucket holds up to 60 tokens and gets 5 back every second. Each request takes one token, so up to 60 requests can pass at once, and over a long time 5 a second.
Traffic is bursty: nothing arrives, except 30 requests in each of two seconds, every 20 seconds. The average is 3 a second.
Token bucket: up to 60 requests got through in 10 seconds against 50, because a full bucket lets a burst of 60 pass at once on top of what is refilled.
- Arrived
- 1200 in the last second
- Accepted
- 120100% of the requests
- Rejected
- 00% of the requests
- Most in 10 s
- 60the limit is 50
- Most in one second
- 30the rate is 5 a second
Accepted Rejected (hatched) Rate limit, 5 a second
| Limiter | Accepted | Rejected | Most in one second | Most in 10 s | Kept in memory |
|---|---|---|---|---|---|
| Token bucket (shown) | 120 | 0 | 30 | 60 | 1 (the tokens left) |
| Leaky bucket (queue) | 120 | 0 | 5 | 50 | 10 (requests waiting in the queue) |
| Fixed window | 120 | 0 | 30 | 60 | 1 (the count of this window) |
| Sliding window log | 100 | 20 | 30 | 50 | 20 (a timestamp for each accepted request) |
| Sliding window counter | 100 | 20 | 30 | 50 | 2 (this window's count and the last one's) |
All five see exactly the same requests. The most in 10 s is the most that reached the service behind in any 10 consecutive seconds; the limit is 50.
The chart as a table
| Second | Arrived | Accepted | Rejected | Reached the service behind |
|---|---|---|---|---|
| 20 | 0 | 0 | 0 | 0 |
| 21 | 0 | 0 | 0 | 0 |
| 22 | 0 | 0 | 0 | 0 |
| 23 | 0 | 0 | 0 | 0 |
| 24 | 0 | 0 | 0 | 0 |
| 25 | 0 | 0 | 0 | 0 |
| 26 | 0 | 0 | 0 | 0 |
| 27 | 0 | 0 | 0 | 0 |
| 28 | 0 | 0 | 0 | 0 |
| 29 | 30 | 30 | 0 | 30 |
| 30 | 30 | 30 | 0 | 30 |
| 31 | 0 | 0 | 0 | 0 |
| 32 | 0 | 0 | 0 | 0 |
| 33 | 0 | 0 | 0 | 0 |
| 34 | 0 | 0 | 0 | 0 |
| 35 | 0 | 0 | 0 | 0 |
| 36 | 0 | 0 | 0 | 0 |
| 37 | 0 | 0 | 0 | 0 |
| 38 | 0 | 0 | 0 | 0 |
| 39 | 0 | 0 | 0 | 0 |
Illustrative values, not benchmarks of any real product.
Model notes
Assumptions
- Time moves in whole seconds, read from a clock that only moves when the lab says so. In each second a limiter first sees the new time (a refill, a drain, a new window) and then decides on every request that arrives in that second, all at the same instant.
- The three patterns are built from the average load. Steady sends the load every second. Bursty sends nothing, except 10 times the load in each of two seconds (seconds 9 and 10) of every 20. Spiky sends half the load, or 5 times the load in about one second in eight, chosen by a seeded random draw. All five limiters see the same requests.
Simplifications
- The leaky bucket is the queue variant: accepted requests wait in a queue of the bucket's size and leave it at the rate, one second after they arrive at the earliest. The meter variant, which rejects a request when a level that leaks away would overflow, behaves like a token bucket and is not modelled apart.
- Windows start at multiples of their length (0, 10, 20 s and so on), not at a client's first request. A window limiter allows the rate times the window length, and counts only the requests it accepted.
- The sliding window counter keeps this window's count and the last one's, and estimates the span as the last count times the share of that window still inside the span, plus this count, rounded down in whole requests. It assumes the last window's requests were spread evenly, so it can allow a little more or less than the exact log.
- With several gateways a balancer sends each request to one gateway at random (seeded). With local counters each gateway enforces the whole limit alone. With a shared counter there is one counter; with a delay, a gateway decides on the counter as it was that many seconds ago plus what it let in itself since, and the real counter then goes past its limit (a token bucket owes tokens). Within a second the gateways take turns going first.
- Not modelled: the cost and latency of reaching a shared store (the delay stands for them), the failure of a gateway or of the store (fail open or fail closed), one limit for each client, a cost that differs by request, clients that retry after a rejection, and the 429 response with Retry-After. The numbers are floors and illustrations, not measurements of a product.
Parameter values are illustrative. They are not benchmarks of any real product.
At second 40, two bursts have come: 120 requests Arrived, and the bucket accepted all 120, so Rejected is 0. The largest second is 30 requests (Most in one second), and the most that got through in any 10 seconds (Most in 10 s) is 60, above the 50 that the rate allows over 10 seconds. The status sentence says why: a full bucket lets a burst of 60 pass at once on top of what is refilled. The limit is “5 a second on average”, and the bucket makes an explicit exception for a short burst.
What happens if the bucket is smaller?
Section titled “What happens if the bucket is smaller?”Lower the Bucket size to 20. The run starts again. The bucket holds 20 tokens, so each burst of 30 requests in one second takes 20 and the rest are refused: 50 requests are Accepted, 70 are Rejected, and Most in 10 s falls to 25. At 40 tokens the figures are 90 accepted, 30 rejected and 45 in 10 seconds. The smaller the bucket, the smaller the burst that gets through, and the more of this traffic is refused, even though its average is under the rate.
Set the Bucket size back to 60 and lower the Rate limit to 3. Nothing changes at second 40: the 120 requests are all accepted, and 60 get through in 10 seconds. The bursts are short and the bucket is big enough to cover them, so the refill rate never comes into play. The rate matters when the bucket runs dry, which takes a sustained load, not a burst.
Choosing the two numbers
Section titled “Choosing the two numbers”Two pieces of arithmetic help to choose them.
- How long an empty bucket takes to refill is the size divided by the rate. A bucket of 60 at 5 a second is full again after
60 / 5, which is 12 s. A bucket of 20 is full after20 / 5, which is 4 s. A client that bursts, and then waits that long, can burst again. - The most a client can send in a time
tis the size plus the rate timest, because it can spend a full bucket and the refill that comes during the time. Over 10 seconds, a bucket of 50 at 5 a second allows up to50 + 5 × 10, which is 100 in the worst case. The lab’s bucket of 60 is spent in two seconds, so the refill adds only 5 between the two bursts, and all 60 requests get through.
So the size should be what a well-behaved client really needs for a burst (a page that makes 20 calls at once, a batch job that starts with a spike), and the rate should be what the service can sustain for one client for a long time. A size of 1 is a strict pacing rule. A very large size is hardly a limit at all.
What the client sees
Section titled “What the client sees”When the bucket is empty the service answers 429, and a good answer says when to come back. The bucket knows: the next token arrives when the refill has added what is missing, which is (1 − tokens) / rate. The C# example below computes exactly this and returns it as the retry delay. Many real limiters differ in what they send. AWS API Gateway returns 429 when requests exceed its steady-state rate and burst, and its documentation says that throttling is applied on a best-effort basis and the limits should be thought of as targets rather than guaranteed ceilings. Stripe’s article suggests choosing between 429 and 503 depending on the case. nginx, which the next lesson uses, answers 503 by default and can be set to 429.
// A token bucket: the bucket holds up to `capacity` tokens and refills at a steady rate.// Each request takes one token. A full bucket allows a burst; an empty one allows only the refill rate.using System.Globalization;using ShardCraft.Playground;
var clock = new FakeClock();var limiter = new TokenBucket(clock, capacity: 5, refillPerSecond: 2);
void Send(string label){ var allowed = limiter.TryTake(out var retryAfter); var tokens = limiter.Tokens.ToString("0.0", CultureInfo.InvariantCulture); var verdict = allowed ? "allowed" : $"rejected (429, retry after {retryAfter.TotalMilliseconds:0} ms)"; Console.WriteLine($"t={clock.UtcNow:ss.fff} {label,-8} {verdict,-42} tokens left {tokens}");}
// 1. A burst of 8 requests at once: the full bucket lets 5 through.for (var i = 1; i <= 8; i++) Send($"burst {i}");
// 2. One second later the bucket has refilled 2 tokens.clock.Advance(TimeSpan.FromSeconds(1));for (var i = 1; i <= 3; i++) Send($"after {i}");
// 3. A steady 2 requests per second matches the refill rate, so nothing is rejected...for (var i = 1; i <= 4; i++){ clock.Advance(TimeSpan.FromMilliseconds(500)); Send($"steady {i}");}
// 4. ...and a quiet spell lets the bucket fill up again, but never beyond its capacity.clock.Advance(TimeSpan.FromSeconds(10));Send("quiet");
class TokenBucket(FakeClock clock, int capacity, double refillPerSecond){ private double _tokens = capacity; // starts full private DateTimeOffset _lastRefill = clock.UtcNow;
public double Tokens => _tokens;
public bool TryTake(out TimeSpan retryAfter) { // Refill lazily, from the time since the last call: no timer needed. var elapsed = (clock.UtcNow - _lastRefill).TotalSeconds; _tokens = Math.Min(capacity, _tokens + elapsed * refillPerSecond); _lastRefill = clock.UtcNow;
if (_tokens >= 1) { _tokens -= 1; retryAfter = TimeSpan.Zero; return true; } retryAfter = TimeSpan.FromSeconds((1 - _tokens) / refillPerSecond); // when one token will exist return false; }}
// A real limiter keeps its state per client (a key in Redis, updated atomically with a Lua script) and// returns Retry-After or RateLimit headers. .NET ships one: System.Threading.RateLimiting.TokenBucketRateLimiter.t=00.000 burst 1 allowed tokens left 4.0t=00.000 burst 2 allowed tokens left 3.0t=00.000 burst 3 allowed tokens left 2.0t=00.000 burst 4 allowed tokens left 1.0t=00.000 burst 5 allowed tokens left 0.0t=00.000 burst 6 rejected (429, retry after 500 ms) tokens left 0.0t=00.000 burst 7 rejected (429, retry after 500 ms) tokens left 0.0t=00.000 burst 8 rejected (429, retry after 500 ms) tokens left 0.0t=01.000 after 1 allowed tokens left 1.0t=01.000 after 2 allowed tokens left 0.0t=01.000 after 3 rejected (429, retry after 500 ms) tokens left 0.0t=01.500 steady 1 allowed tokens left 0.0t=02.000 steady 2 allowed tokens left 0.0t=02.500 steady 3 allowed tokens left 0.0t=03.000 steady 4 allowed tokens left 0.0t=13.000 quiet allowed tokens left 4.0This is the exact code that produced this output, run with the .NET SDK when the site was built. Nothing runs in your browser.
The example uses a bucket of 5 tokens refilled at 2 a second, and a clock that only moves when it is told to. A burst of 8 requests at once is a full bucket meeting a spike: 5 are allowed, the other 3 are rejected with a retry after 500 ms, since one token takes 1 / 2 of a second to come back. One second later the bucket holds 2 tokens: two requests are allowed and the third is rejected. A steady 2 requests a second matches the refill, so nothing is rejected. After a quiet 10 seconds the bucket is full again, and it stops at its capacity: the request takes one token and 4 are left, not 20. The bucket refills lazily, from the time that has passed since the last call, so no timer is needed. ASP.NET Core’s built-in token bucket limiter works with a timer instead: when AutoReplenishment is true, an internal timer adds the tokens each replenishment period.
A real limiter keeps one bucket for each client, in a map or a shared store, and the key is a choice: the IP address, the user, the API key. ASP.NET Core’s documentation calls these partitions, and warns that creating them from input that a client controls, such as a spoofed source address, can itself be used for a denial of service. Envoy’s local rate limit filter is also a token bucket, and by default it applies to each Envoy process, which the lesson on distributed limits comes back to.
- A rate limit refuses requests above an allowed rate. The refusal is a 429, which may carry a
Retry-Afterheader. - A token bucket has two numbers: the refill rate, which is the sustained speed, and the size, which is the burst a quiet client can spend at once.
- In the lab, the bucket of 60 accepts all 120 requests of two bursts, and 60 get through in 10 seconds against a rate of 5 a second. A bucket of 20 accepts 50 and rejects 70.
- An empty bucket is full again after size divided by rate: 12 s for 60 at 5 a second.
- The bucket decides at once: a request is allowed or refused, never held.
Next: the leaky bucket, which holds the burst back instead of letting it through.
Your progress
Built by GhaziAlibi.
© ShardCraft. All rights reserved.