
From the very first minute a production Web API is exposed to the public internet, it becomes a target for automated traffic. A credential-stuffing botnet might fire 5,000 password attempts per second at your POST /api/auth/login endpoint, an aggressive competitor scraper might hammer your product catalog 10,000 times per second, or a buggy infinite useEffect loop in a frontend client might saturate your PostgreSQL connection pool in seconds.
The result? Legitimate paying customers experience timeouts and service outages. The architectural defense mechanism that enforces a strict mathematical upper bound on how many requests a client (partitioned by IP address, authenticated user ID, or B2B API key) can execute within a time window is called Rate Limiting.
What We Will Implement Step by Step in This Guide:
1. Visual timelines and mathematical trade-offs of the 4 core Rate Limiting algorithms: Fixed Window, Sliding Window, Token Bucket, and Concurrency Limiter.
2. The #1 Production Reverse-Proxy Disaster: Why deploying behind Nginx or Cloudflare withoutUseForwardedHeaders()buckets all users under127.0.0.1and locks out your entire customer base!
3. Complete ASP.NET CoreProgram.cssetup featuring partitioned per-user/per-IP Token Bucket policies for general traffic, strict Sliding Window policies for login/checkout, and Concurrency policies for heavy PDF generation.
4. Returning RFC 7807429 Too Many Requestspayloads with standardRetry-Afterheaders and handling them cleanly in TypeScript clients.
1. Visual and Mathematical Anatomy of the Four Rate Limiting Algorithms
Before writing code, let us examine how the four built-in algorithms in ASP.NET Core's System.Threading.RateLimiting namespace operate and where each shines:
Algorithm 1: Fixed Window
Rule: "At most 100 requests per static 1-minute calendar window (e.g., 14:00:00 – 14:01:00)."
- Pros: Stores only a single integer counter and timestamp per partition key; lowest memory footprint.
- Weakness (The Boundary Burst Problem): If an attacker sends 100 requests at
14:00:59and another 100 requests one second later at14:01:00(when the new window resets the counter to zero), 200 requests pass through in just 2 seconds:
The Fixed Window Boundary Burst Vulnerability:
14:00:00 14:00:59 │ 14:01:00 14:02:00
├───────────────────────────●─────┼─────●───────────────────────────┤
100 Reqs 100 Reqs
└──────┬──────┘
200 requests slip through in 2 seconds!
Algorithm 2: Sliding Window (Best for High-Risk Authentication & Mutation Endpoints)
To eliminate the boundary burst flaw of Fixed Window, a Sliding Window divides the 1-minute window into smaller sub-segments (for example, 3 segments of 20 seconds each). Every 20 seconds, the window slides forward by one segment and evaluates the rolling sum across the trailing 60 seconds. A client that exhausts its quota at 14:00:59 remains blocked at 14:01:01!
Algorithm 3: Token Bucket (Best for General REST API & SPA Frontend Traffic)
When a real human opens a modern Single-Page Application (Next.js / React), the browser immediately fires 10–15 parallel requests (navigation menu, user profile, notifications, dashboard metrics) and then remains quiet for the next 30 seconds while the user reads the screen. Token Bucket accommodates legitimate short bursts while strictly enforcing long-term average throughput:
Token Bucket (Bucket Capacity: 60 Tokens | Refill Rate: +20 Tokens every 10 seconds)
┌───────────────────┐
│ ● ● ● ● ● ● ● ● │ <-- System automatically adds +20 tokens every 10s (capped at 60)
│ ● ● ● ● ● ● ● ● │
└─────────┬─────────┘
▼ Each incoming HTTP request consumes 1 token from the client's bucket:
[ Token Available? ] ──(Yes)──► HTTP 200 OK (Request proceeds to Controller)
│
(No, Bucket Empty!)
▼
HTTP 429 Too Many Requests (Retry-After: 10)
Algorithm 4: Concurrency Limiter (Best for CPU/Memory-Intensive Endpoints)
Instead of counting requests per minute, a Concurrency Limiter caps the number of simultaneous in-flight requests executing at the exact same millisecond. For example, restricting a heavy PDF invoice generator or Excel export endpoint to 10 concurrent executions prevents thread-pool starvation and Out-Of-Memory (OOM) crashes.
| Algorithm | Memory Overhead | Burst Behavior | Recommended Production Use Case |
|---|---|---|---|
| Fixed Window | Very Low | Allows 2x burst at window edges | Internal microservices or coarse hourly/daily quota enforcement. |
| Sliding Window | Moderate | Strictly smooths rolling traffic | /api/auth/login, /api/contact, OTP verification, and checkout endpoints. |
| Token Bucket | Low | Permits bursts up to bucket capacity | General REST API read/list endpoints consumed by web and mobile UIs. |
| Concurrency | Very Low | Caps simultaneous active execution | Heavy PDF generation, Excel exports, and AI inference endpoints. |
2. Critical Production Warning: Reading the Real Client IP Behind Nginx or Cloudflare!
When you test IP-based rate limiting on your local machine (localhost), everything works as expected. Then you deploy your container behind Nginx, Cloudflare, or an AWS Application Load Balancer—and suddenly, the moment a single bot hits the rate limit, every single customer on your website gets blocked with HTTP 429 simultaneously!
Why does this happen? Because the reverse proxy terminates the external TCP connection and forwards the request to your Kestrel (.NET) container over the loopback interface (127.0.0.1), placing the real visitor's IP inside the X-Forwarded-For HTTP header. If you do not enable ForwardedHeadersMiddleware, ASP.NET Core sees httpContext.Connection.RemoteIpAddress as 127.0.0.1 for every visitor on earth, throwing all users into the exact same rate-limit bucket!
To fix this, configure ForwardedHeadersOptions and call app.UseForwardedHeaders() before app.UseRateLimiter() in Program.cs:
using Microsoft.AspNetCore.HttpOverrides;
// Enabling real client IP extraction (X-Forwarded-For) behind Nginx / Cloudflare:
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
// Clear default loopback-only restrictions when running inside Docker / cloud networks:
options.KnownNetworks.Clear();
options.KnownProxies.Clear();
});
3. Complete Enterprise Rate Limiting Configuration in ASP.NET Core (Program.cs)
Now let us assemble a complete 3-tier rate-limiting configuration in Program.cs:
1. A partitioned Token Bucket policy (general-api-bucket) keyed by authenticated User ID (or fallback Client IP for anonymous visitors).
2. A strict Sliding Window policy (strict-write-window) allowing at most 5 requests per minute per IP for login, checkout, and public forms.
3. A Concurrency Limiter policy (heavy-report-concurrency) capping heavy PDF exports at 10 concurrent executions.
// File Path: src/DigitalHat.Commerce.WebApi/Program.cs
using System;
using System.Globalization;
using System.Security.Claims;
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.Extensions.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);
// 1. Resolve real client IP addresses from X-Forwarded-For behind Nginx / Cloudflare:
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
options.KnownNetworks.Clear();
options.KnownProxies.Clear();
});
// 2. Register Partitioned Rate Limiter Policies:
builder.Services.AddRateLimiter(options =>
{
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
// Return RFC 7807 ProblemDetails JSON and a standard Retry-After header when throttled:
options.OnRejected = async (context, cancellationToken) =>
{
int retryAfterSeconds = 60;
if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out TimeSpan retryAfter))
{
retryAfterSeconds = Math.Max(1, (int)Math.Ceiling(retryAfter.TotalSeconds));
}
context.HttpContext.Response.Headers.RetryAfter = retryAfterSeconds.ToString(CultureInfo.InvariantCulture);
context.HttpContext.Response.ContentType = "application/problem+json";
var problem = new ProblemDetails
{
Status = StatusCodes.Status429TooManyRequests,
Title = "Too Many Requests",
Detail = $"You have exceeded the allowed request rate. Please wait {retryAfterSeconds} seconds before retrying.",
Instance = context.HttpContext.Request.Path
};
await context.HttpContext.Response.WriteAsJsonAsync(problem, cancellationToken: cancellationToken);
};
// POLICY A: Partitioned Token Bucket for General API Traffic (Per User ID or Per Client IP)
options.AddPolicy("general-api-bucket", httpContext =>
{
string? userId = httpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
string clientIp = httpContext.Connection.RemoteIpAddress?.ToString() ?? "anonymous";
string partitionKey = !string.IsNullOrWhiteSpace(userId) ? $"user:{userId}" : $"ip:{clientIp}";
return RateLimitPartition.GetTokenBucketLimiter(partitionKey, _ => new TokenBucketRateLimiterOptions
{
TokenLimit = 60,
ReplenishmentPeriod = TimeSpan.FromSeconds(10),
TokensPerPeriod = 20,
AutoReplenishment = true,
QueueLimit = 0
});
});
// POLICY B: Strict Sliding Window for Login, Checkout & Contact Forms (Max 5 attempts/min per IP!)
options.AddPolicy("strict-write-window", httpContext =>
{
string clientIp = httpContext.Connection.RemoteIpAddress?.ToString() ?? "anonymous";
return RateLimitPartition.GetSlidingWindowLimiter(clientIp, _ => new SlidingWindowRateLimiterOptions
{
PermitLimit = 5,
Window = TimeSpan.FromMinutes(1),
SegmentsPerWindow = 3,
QueueLimit = 0
});
});
// POLICY C: Concurrency Limiter for Heavy PDF/Excel Report Generation (Max 10 active jobs)
options.AddConcurrencyLimiter("heavy-report-concurrency", concurrencyOptions =>
{
concurrencyOptions.PermitLimit = 10;
concurrencyOptions.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
concurrencyOptions.QueueLimit = 5;
});
});
builder.Services.AddControllers();
var app = builder.Build();
// PIPELINE ORDER RULE: 1. ForwardedHeaders -> 2. Authentication -> 3. RateLimiter -> 4. Controllers
app.UseForwardedHeaders();
app.UseAuthentication();
app.UseRateLimiter();
app.UseAuthorization();
app.MapControllers();
app.Run();
4. Applying Rate Limiting Policies to Controllers and Endpoints
You can now apply policies declaratively at the controller level or override them on specific action methods using [EnableRateLimiting] and [DisableRateLimiting]:
// File Path: src/DigitalHat.Commerce.WebApi/Controllers/OrdersController.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace DigitalHat.Commerce.WebApi.Controllers;
[ApiController]
[Route("api/[controller]")]
[EnableRateLimiting("general-api-bucket")] // Entire controller is protected by Token Bucket by default
public class OrdersController : ControllerBase
{
[HttpGet]
public IActionResult GetOrders() => Ok(new[] { "ORD-2026-001", "ORD-2026-002" });
[HttpPost("checkout")]
[EnableRateLimiting("strict-write-window")] // Checkout is strictly capped at 5 attempts per minute!
public IActionResult Checkout() => Ok(new { status = "PaymentProcessed" });
[HttpGet("export-pdf")]
[EnableRateLimiting("heavy-report-concurrency")] // At most 10 concurrent PDF exports across the server!
public IActionResult ExportPdf() => Ok(new { fileUrl = "/exports/orders-2026.pdf" });
[HttpGet("health")]
[DisableRateLimiting] // Kubernetes / Docker health probes bypass rate limiting
public IActionResult Health() => Ok(new { healthy = true });
}
5. Handling 429 Retry-After Gracefully in Frontend (TypeScript) Clients
When a frontend application receives an HTTP 429 Too Many Requests status, it should read the Retry-After header to display an accurate countdown or schedule an automatic retry:
// Reading HTTP 429 and the Retry-After Header in Next.js / TypeScript:
const response = await fetch("https://api.dgtalhat.com/api/orders/checkout", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(orderPayload),
});
if (response.status === 429) {
const retryAfterSeconds = Number(response.headers.get("Retry-After") ?? "60");
throw new Error(`Rate limit reached. Please wait ${retryAfterSeconds} seconds before trying again.`);
}
6. Congratulations! You Have Completed the Web API & Networking Series
Across this 3-part series, you have built a production RESTful Web API in ASP.NET Core, engineered type-safe HTTP/JSON/JWT clients in TypeScript and C#, and shielded your endpoints with multi-tiered Rate Limiting. Next, proceed to Series 04 · Advanced Architecture: CQRS, MediatR & Cloud to learn how we structure large-scale enterprise systems without 3,000-line fat services!
Did you find this engineering guide helpful?
Give it a like or share it with your team and network.