Rate Limiting In .NET Core

Rate limiting is about restricting the number of requests to an API, usually within a specific time window or based on other criteria.

This is practical for a few reasons.

  1. Prevents overloading of servers or applications
  2. Improves security and guards against DDoS attacks
  3. Reduces costs by preventing unnecessary resource usage

In a multi-tenant application, each unique user can have a limitation on the number of API requests.

Using AspNetCoreRateLimit

The AspNetCoreRateLimit library by StefH is a popular choice for rate limiting in .NET Core applications. It supports client-based, IP-based, and endpoint-based rate limits.

Step 1. Install the NuGet package: AspNetCoreRateLimit.

NuGet package

Step 2. Configure Services.

In Program.cs, register the required services and register in the middleware section.

using AspNetCoreRateLimit;

var builder = WebApplication.CreateBuilder(args);

// Add configuration for rate limiting
builder.Services.AddOptions();
builder.Services.AddMemoryCache();

// Add the services for rate limiting
builder.Services.Configure<IpRateLimitOptions>(
    builder.Configuration.GetSection("IpRateLimiting")
);
builder.Services.Configure<IpRateLimitPolicies>(
    builder.Configuration.GetSection("IpRateLimitPolicies")
);
builder.Services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
builder.Services.AddInMemoryRateLimiting();

var app = builder.Build();

// Use rate limiting middleware
app.UseIpRateLimiting();

app.MapControllers();
app.Run();

Step 3. Add Configuration.

In appsettings.json, define the rate-limiting rules.

Note. Inside json section, you can change settings according to requirements.

"IpRateLimiting": {
  "EnableEndpointRateLimiting": true,
  "StackBlockedRequests": false,
  "RealIpHeader": "X-Real-IP",
  "ClientIdHeader": "X-ClientId",
  "HttpStatusCode": 429,
  "GeneralRules": [
    {
      "Endpoint": "*", 
      "Period": "1m", 
      "Limit": 5
    },
    {
      "Endpoint": "/api/values", 
      "Period": "10s",
      "Limit": 2
    }
  ]
},
"IpRateLimitPolicies": {
  "IpRules": [
    {
      "Ip": "192.168.1.1",
      "Rules": [
        {
          "Period": "1h",
          "Limit": 100
        }
      ]
    }
  ]
}

Step 4. Test the Configuration.

Make requests to your application. After exceeding the limit, you should receive a 429 Too Many Requests response.

In the above configuration, we have defined a rate-limiting policy called "EndpointRateLimitPolicy". This policy specifies that within a 1-minute period, a client can make up to 5 requests to any endpoint. Additionally, within a 1-minute period, a client can make up to 5 requests to any endpoint. You can customize these values according to your application’s requirements.


Similar Articles