A flexible and customizable rate limiting library for modern and legacy .NET APIs.
RateLimit.Throttlr supports multiple rate limiting algorithms:
- Fixed Window
- Sliding Window
- Token Bucket
Install via NuGet:
dotnet add package RateLimit.Throttlr
using RateLimit.Throttlr.Core;
using RateLimit.Throttlr.Extensions;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
// Add rate limiting services
builder.Services.AddRateLimiting(
new RateLimitPolicy(
name: "global", // unique policy name
limit: 5, // max 5 requests
window: TimeSpan.FromSeconds(10) // per 10 seconds
),
limiterType: RateLimiterType.SlidingWindow // Options: FixedWindow | SlidingWindow | TokenBucket
);
app.UseRouting();
app.UseRateLimiting(); // Apply rate limiting
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.Run();
namespace DemoAPI.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
[HttpGet("hello")]
public IActionResult GetHello()
{
return Ok(new
{
message = "Hello, world!",
timestamp = DateTime.UtcNow
});
}
}
}
Each IP (or custom partition key) can only make 5 requests per 10 seconds. Exceeding the limit returns HTTP 429 Too Many Requests. Standard headers: X-RateLimit-Limit: total allowed requests X-RateLimit-Remaining: requests left in the current window X-RateLimit-Reset: Unix timestamp when window resets Retry-After: seconds to wait before next allowed request
Limiter Type Description FixedWindow Counts requests per fixed window interval SlidingWindow Smooths counts using weighted previous window TokenBucket Allows bursts and steady refill rate