Rate limiting with a token bucket

Allow short bursts but cap the average rate per user, the algorithm behind most API rate limits.

Time O(1) per requestSpace O(u) usersCode C#
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

In the .NET library

ASP.NET Core has built-in rate limiting middleware (AddRateLimiter) with token bucket, fixed window, sliding window and concurrency limiters.