Kryat Docs Image

Rate Limiting

Important

No rate limiting = Bankrupt

Rate limiting is an important security feature that prevents abuse of your APIs by limiting how many requests a client can make within a specific time period. This guide explains how to implement IP-based rate limiting in KikiWriting.

Using ASP.NET Core Rate Limiting Middleware

ASP.NET Core provides built-in middleware for rate limiting. Here's how to implement it in KikiWriting:

Step 1: Add Required NuGet Package

First, add the rate limiting package to your project:

dotnet add package Microsoft.AspNetCore.RateLimiting

Step 2: Configure Rate Limiting in Program.cs

// In Program.cs
using Microsoft.AspNetCore.RateLimiting;
using System.Threading.RateLimiting;
 
// Add rate limiting services
builder.Services.AddRateLimiter(options =>
{
    options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(context =>
    {
        // Get the client's IP address
        var clientIp = context.Connection.RemoteIpAddress?.ToString() ?? "unknown";
        
        return RateLimitPartition.GetFixedWindowLimiter(clientIp, partition =>
            new FixedWindowRateLimiterOptions
            {
                AutoReplenishment = true,
                PermitLimit = 100,      // 100 requests
                Window = TimeSpan.FromMinutes(1)  // per minute
            });
    });
    
    // Add specific policies for different endpoints
    options.AddPolicy("api", context =>
    {
        var clientIp = context.Connection.RemoteIpAddress?.ToString() ?? "unknown";
        
        return RateLimitPartition.GetFixedWindowLimiter(clientIp, partition =>
            new FixedWindowRateLimiterOptions
            {
                AutoReplenishment = true,
                PermitLimit = 20,      // 20 requests
                Window = TimeSpan.FromSeconds(10)  // per 10 seconds
            });
    });
    
    // Configure options
    options.OnRejected = async (context, token) =>
    {
        context.HttpContext.Response.StatusCode = 429; // Too Many Requests
        context.HttpContext.Response.ContentType = "application/json";
        
        await context.HttpContext.Response.WriteAsJsonAsync(new 
        { 
            error = "Too many requests. Please try again later."
        }, token);
    };
});
 
// Use rate limiting middleware
var app = builder.Build();
app.UseRateLimiter();

Step 3: Apply Rate Limiting to Controllers or Actions

You can apply rate limiting to specific controllers or actions using the [EnableRateLimiting] attribute:

[ApiController]
[Route("api/[controller]")]
[EnableRateLimiting("api")]  // Apply the "api" policy
public class GraphsController : ControllerBase
{
    // Controller actions
}

Or for specific actions:

[HttpPost]
[EnableRateLimiting("api")]  // Apply the "api" policy
public async Task<IActionResult> ProcessGraph(GraphInputModel model)
{
    // Action implementation
}

On this page