API Rate Limiting in ASP.NET Core

What is API Rate Limiting?

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:

  • Prevent Abuse: Protects the API from excessive usage or malicious attacks.
  • Ensure Fair Use: Ensures that all users get equal access to resources.
  • Improve Performance: Helps manage server load and enhance reliability.

Why Use Rate Limiting?

Implementing rate limiting prevents overload on the server, safeguards against denial-of-service attacks, and ensures a better experience for all users.


How to Implement API Rate Limiting in ASP.NET Core

Follow these steps:

1. Install Required NuGet Package


// Run the following command:
Install-Package AspNetCoreRateLimit

                

The AspNetCoreRateLimit package provides tools for implementing rate limiting in your API.

2. Configure Rate Limiting in appsettings.json


// 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.

3. Register Rate Limiting Middleware


// 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.

4. Test the Rate Limiting


// 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.

5. Customize Response for Rate Limiting


// 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.

6. Implement Per-Client Rate Limiting


// 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.