Introduction
Rate limiting is a fundamental strategy for maintaining the stability and security of applications. It plays a crucial role in preventing abuse, protecting resources, and ensuring fair usage of APIs or services. In this comprehensive guide, we’ll explore various rate limiting algorithms in the context of .NET Core, providing code snippets for implementing
- Token Bucket,
- Sliding Window,
- Fixed Window,
- and Concurrency limiters.
Token Bucket Algorithm
The Token Bucket algorithm is a versatile approach to rate limiting. It involves maintaining a bucket of tokens, where each token represents a unit of work. Clients can only perform an action if they possess an available token.
Let’s implement a Token Bucket rate limiter in .NET Core:
public class TokenBucketRateLimiter
{
private readonly int capacity;
private readonly Queue<DateTime> tokens;
public TokenBucketRateLimiter(int capacity)
{
this.capacity = capacity;
this.tokens = new Queue<DateTime>();
}
public bool TryConsume()
{
lock (tokens)
{
if (tokens.Count < capacity)
{
tokens.Enqueue(DateTime.Now);
return true;
}
return false;
}
}
}
Usage example:
var rateLimiter = new TokenBucketRateLimiter(5);
if (rateLimiter.TryConsume())
{
Console.WriteLine("Request processed successfully");
}
else
{
Console.WriteLine("Rate limit exceeded");
}
2. Sliding Window Algorithm
The Sliding Window algorithm divides time into fixed intervals, allowing a certain number of requests within each interval. As time progresses, the window slides, and new requests are considered.
Here’s a Sliding Window rate limiter in .NET Core:
public class SlidingWindowRateLimiter
{
private readonly int capacity;
private readonly Queue<DateTime> window;
public SlidingWindowRateLimiter(int capacity)
{
this.capacity = capacity;
this.window = new Queue<DateTime>();
}
public bool TryConsume()
{
lock (window)
{
CleanExpiredTokens();
if (window.Count < capacity)
{
window.Enqueue(DateTime.Now);
return true;
}
return false;
}
}
private void CleanExpiredTokens()
{
var now = DateTime.Now;
while (window.Count > 0 && (now - window.Peek()).TotalSeconds >= 1)
{
window.Dequeue();
}
}
}
Join the conversation! Your thoughts help the community grow.