APIs are the backbone of modern applications, powering everything from social media integrations to payment gateways. However, if left unprotected, they can be exploited resulting in Denial of Service (DoS) attacks, server overload, and unexpected costs. One of the most effective techniques to defend against these issues is Rate Limiting.
API rate limiting is the process of controlling how many requests a user or system can make to an API within a given timeframe. For example, an API might allow only 100 requests per minute per user. If a user exceeds this limit, the API will return an error (like 429 Too Many Requests) until the timeframe resets.
Many Web API design patterns and best practices have been proposed to improve performance and reliability. Among them, the Rate Limit pattern plays a crucial role in preventing excessive usage of resources by specific clients. By enforcing limits, API providers can
However, rate limiting is not always standardized. Different providers adopt different strategies, configuration options, and even terminology. This inconsistency can
In such cases, API providers must rely on manual implementations or specialized tools to enforce limits and defend their systems against abusive behavior.
Different algorithms are used to enforce rate limiting, each with trade-offs between accuracy, efficiency, and fairness.
/login
should have stricter limits than /documentation
./checkout
and /login
.X-RateLimit-Limit: 100
X-RateLimit-Remaining: 42
X-RateLimit-Reset: 60
Retry-After
header.CREATE THE MIDDLEWARE
using Microsoft.AspNetCore.Http;
using System.Collections.Concurrent;
using System.Threading.RateLimiting;
using System.Threading.Tasks;
public class RateLimitingMiddleware
{
private readonly RequestDelegate _next;
// Store request counts per IP
private static ConcurrentDictionary<string, (int Count, DateTime Timestamp)> _requests
= new ConcurrentDictionary<string, (int, DateTime)>();
private readonly int _limit = 5; // Max requests
private readonly int _windowSeconds = 10; // Time window (seconds)
public RateLimitingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
var ip = context.Connection.RemoteIpAddress?.ToString() ?? "unknown";
var now = DateTime.UtcNow;
var entry = _requests.GetOrAdd(ip, _ => (0, now));
if ((now - entry.Timestamp).TotalSeconds > _windowSeconds)
{
// Reset window
entry = (0, now);
}
if (entry.Count >= _limit)
{
context.Response.StatusCode = StatusCodes.Status429TooManyRequests;
await context.Response.WriteAsync("Too many requests. Try again later.");
return;
}
_requests[ip] = (entry.Count + 1, entry.Timestamp);
await _next(context);
}
}
REGISTER MIDDLEWARE IN Program.cs
Open Program.cs and add the middleware before app.MapControllers();
app.UseMiddleware<RateLimitingMiddleware>();
Implementing rate limiting in your APIs is a crucial step to protect your backend from abuse, prevent server overload, and ensure fair usage among clients. With .NET Core and .NET 8, creating a custom middleware gives developers full control over how limits are enforced — whether per IP, API key, or endpoint.
In this blog, we walked through:
While this approach works well for single-server deployments, for production-ready applications, consider using distributed caches like Redis or the built-in .NET 8 Rate Limiting Middleware to handle multiple instances and more advanced policies.
By following these steps, you can make your APIs more secure, resilient, and predictable, providing a better experience for both your users and your infrastructure.
Many modern software applications are composed of multiple components — for example, a web application…
In today’s globalized world, language differences continue to be one of the most significant barriers…
In today’s digital world, many people rely on social media platforms like Facebook, Twitter, and…
Despite their impressive performance on a variety of tasks, large language models (LLMs) still have…
Introduction Builder.io is more than simply a drag-and-drop page builder. It's a headless CMS and…
When it comes to building enterprise-grade applications, choosing the right front-end framework is critical. It…
This website uses cookies.