API Rate Limiting is the practice of controlling the number of requests a client can make to an API within a specified time period. It helps to:
Implementing rate limiting prevents overload on the server, safeguards against denial-of-service attacks, and ensures a better experience for all users.
Follow these steps:
// Run the following command:
Install-Package AspNetCoreRateLimit
The AspNetCoreRateLimit
package provides tools for implementing rate limiting in your API.
// appsettings.json
{
"IpRateLimiting": {
"EnableEndpointRateLimiting": true,
"StackBlockedRequests": false,
"RealIpHeader": "X-Real-IP",
"ClientIdHeader": "X-ClientId",
"HttpStatusCode": 429,
"GeneralRules": [
{
"Endpoint": "*",
"Period": "1m",
"Limit": 10
}
]
}
}
Here, the configuration limits each client to 10 requests per minute to any endpoint.
// Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOptions();
builder.Services.AddMemoryCache();
builder.Services.Configure(builder.Configuration.GetSection("IpRateLimiting"));
builder.Services.AddInMemoryRateLimiting();
builder.Services.AddSingleton();
var app = builder.Build();
app.UseIpRateLimiting(); // Add the rate limiting middleware
app.MapGet("/", () => "Welcome to the API!");
app.Run();
The middleware processes each request and enforces the rate limiting rules defined in appsettings.json
.
// Use a tool like Postman or curl to test:
curl -X GET http://localhost:5000/
After 10 requests in one minute, you will receive an HTTP 429 (Too Many Requests) status code.
// Modify Program.cs to customize the response
app.UseIpRateLimiting();
app.Use(async (context, next) =>
{
if (context.Response.StatusCode == 429)
{
context.Response.ContentType = "application/json";
await context.Response.WriteAsync("{\"error\":\"Rate limit exceeded. Try again later.\"}");
}
else
{
await next.Invoke();
}
});
This customizes the message returned to clients when they exceed the rate limit.
// appsettings.json
{
"IpRateLimiting": {
"GeneralRules": [
{
"Endpoint": "*",
"Period": "1m",
"Limit": 5
}
]
},
"ClientRateLimiting": {
"GeneralRules": [
{
"ClientId": "client1",
"Endpoint": "*",
"Period": "1m",
"Limit": 20
}
]
}
}
Define specific rate limits for individual clients by specifying ClientId
.