How to Implement Rate Limiting in NET APIs

Listen to this Post

Rate limiting is a crucial technique to control the number of requests a user can make to your API. It helps in:
– Building usage-based applications
– Preventing malicious users from overloading your system

Starting from .NET 7, rate limiting is built into the framework, making it easier to implement. You can create a rate limit policy partitioned by a user’s ID to apply restrictions per user.

πŸ”— Reference: .NET 7 Rate Limiting Guide

You Should Know: Implementing Rate Limiting in .NET

1. Setting Up Rate Limiting in .NET 7

To enable rate limiting, add the required NuGet package:

dotnet add package Microsoft.AspNetCore.RateLimiting 

2. Configure Rate Limiting Middleware

In `Program.cs`, define a rate-limiting policy:

var rateLimiterPolicy = "PerUserRateLimit";

builder.Services.AddRateLimiter(options => 
{ 
options.AddPolicy(rateLimiterPolicy, context => 
RateLimitPartition.GetFixedWindowLimiter( 
partitionKey: context.User.Identity?.Name ?? context.Request.Headers["X-Client-Id"].ToString(), 
factory: partition => new FixedWindowRateLimiterOptions 
{ 
PermitLimit = 100, 
Window = TimeSpan.FromMinutes(1), 
QueueProcessingOrder = QueueProcessingOrder.OldestFirst, 
QueueLimit = 10 
})); 
}); 

3. Apply Rate Limiting to Endpoints

Use the `

` attribute on controllers or actions:</h2>

[bash]
[EnableRateLimiting("PerUserRateLimit")] 
[bash] 
[Route("api/[bash]")] 
public class UsersController : ControllerBase 
{ 
[bash] 
public IActionResult Get() => Ok("Rate-limited endpoint"); 
} 

4. Handling Rate Limit Exceeded Responses

Customize the response when a user exceeds the limit:

builder.Services.AddRateLimiter(options => 
{ 
options.OnRejected = (context, _) => 
{ 
context.HttpContext.Response.StatusCode = 429; 
context.HttpContext.Response.WriteAsync("Too many requests. Try again later."); 
return new ValueTask(); 
}; 
}); 

5. Testing Rate Limiting

Use curl or Postman to test:

curl -H "X-Client-Id: test-user" http://localhost:5000/api/users 

After exceeding the limit, you should receive a 429 Too Many Requests response.

What Undercode Say

Rate limiting is essential for API security and fairness. Beyond .NET, similar techniques exist in other platforms:

Linux (NGINX Rate Limiting)

http { 
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;

server { 
location /api/ { 
limit_req zone=api_limit burst=20 nodelay; 
proxy_pass http://backend; 
} 
} 
} 

Windows (PowerShell API Throttling)

 Log and block excessive requests 
$log = "C:\logs\api_requests.log" 
$ip = $request.RemoteEndPoint.Address 
$count = (Get-Content $log | Select-String $ip).Count

if ($count -gt 100) { 
Write-Output "HTTP/1.1 429 Too Many Requests" 
exit 
} 

Cloudflare Rate Limiting

If using Cloudflare, set rules in the dashboard:

1. Go to Firewall > Rate Limiting

  1. Define a rule (e.g., “100 requests per minute per IP”)

Expected Output:

βœ… A secure, rate-limited API in .NET 7

βœ… Proper 429 responses for exceeded limits

βœ… Scalable rate-limiting strategies for high-traffic apps

For further reading, check Microsoft’s official docs:

πŸ”— .NET Rate Limiting Documentation

References:

Reported By: Milan Jovanovic – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass βœ…

Join Our Cyber World:

πŸ’¬ Whatsapp | πŸ’¬ TelegramFeatured Image