Rate limiting with a token bucket
Allow short bursts but cap the average rate per user, the algorithm behind most API rate limits.
Watch it animatedStep through it, with the running line highlighted. Free with an account.The idea
Each user has a bucket that holds up to N tokens and refills at a steady rate. A request takes one token; with no tokens left it is rejected with 429. Bursts up to N are allowed, but over time the user cannot exceed the refill rate.
Code
class TokenBucket
{
double _tokens; DateTime _last = DateTime.UtcNow;
const double Rate = 1.0; // tokens added per second
public bool Allow(int capacity)
{
var now = DateTime.UtcNow;
_tokens = Math.Min(capacity, _tokens + (now - _last).TotalSeconds * Rate);
_last = now;
if (_tokens < 1) return false; // 429 Too Many Requests
_tokens -= 1;
return true;
}
}Tips
- Across many servers the bucket must live in a shared store such as Redis, updated atomically with a Lua script.
- Return a Retry-After header with 429 so clients know when to try again.
- Other algorithms: fixed window (simple, but bursts at window edges), sliding window log (exact, more memory).
In the .NET library
ASP.NET Core has built-in rate limiting middleware (AddRateLimiter) with token bucket, fixed window, sliding window and concurrency limiters.