Rate Limiting Middleware in ASP.NET Core: Control Traffic and Protect Your APIs

Rate Limiting Middleware in ASP.NET Core: Control Traffic and Protect Your APIs

Rate limiting middleware in ASP.NET Core is built-in middleware that controls how many requests a client can make to your app in a given time frame, protecting it from being overwhelmed by traffic — whether that’s abuse, bugs in a client, or just unexpected load. ASP.NET Core provides rate limiting through the Microsoft.AspNetCore.RateLimiting namespace as part of the framework itself. This means you don’t need to install any third-party NuGet package when implementing rate limiting in a single-instance deployment.

Implementing rate limiting in your ASP.NET Core application is a proven strategy for maintaining app stability, enhancing security, and delivering reliable performance — ensuring a consistent, high-quality experience for every user.

Imagine an abusive user writes a for loop that sends hundreds or thousands of requests to your API in a short period of time. Every request queries the database, calls a payment gateway like PayPal, and updates the Cache. Within just a few seconds, this heavy traffic can push the server resource usage to 90%, causing slow responses and timeouts for other customers. The solution is to use a rate limiter in front of the endpoint. When the user sends too many requests, the rate limiter immediately rejects them with a 429 Too Many Requests response, before the request reaches the database, payment gateway, or other expensive services.

Well, if this is your scenario then this tutorial on Rate Limiting Middleware will give you a practical solution.

Rate Limiter Protecting Backend

Why Rate Limiting Is a Must for ASP.NET Core APIs

Rate limiting is a critical technique for managing and controlling the flow of incoming requests to your ASP.NET Core application. Whether you’re building a public API or a high-traffic web service, implementing rate limiting helps ensure stability, security, and consistent performance. Here are the key benefits of using rate limiting in your app:

1. Prevent API Abuse

Rate limiting protects your application from abuse by capping the number of requests a user or client can make within a specific time window. This is especially critical for public-facing APIs, where uncontrolled access can lead to misuse or exploitation.

2. Ensure Fair Usage for All Users

By enforcing request limits, rate limiting guarantees equitable access to your app’s resources. This prevents any single user or client from monopolizing system capacity at the expense of others.

3. Protect Backend Resources from Overload

Controlling the volume of incoming requests prevents your servers from becoming overwhelmed. Rate limiting acts as a safeguard, keeping backend resources — like databases and compute — stable under heavy load.

4. Strengthen Application Security

Rate limiting is an effective defense against Denial of Service (DoS) attacks. By throttling the rate at which requests are processed, it becomes significantly harder for malicious actors to flood your system and disrupt service.

5. Improve App Performance and Responsiveness

Managing incoming request volume helps maintain optimal application performance. This translates directly into a smoother, more responsive user experience — even during traffic spikes.

6. Manage and Predict Infrastructure Costs

For usage-based services, rate limiting gives you control over request volume, making it easier to manage and forecast operational costs tied to API or resource consumption.

The below image explains the working of rate limiting middleware.

Working of Rate Limiting Middleware

Setup of Rate Limiting Middleware

The following steps show how to use the rate limiting middleware in an ASP.NET Core app:

Registration of Limiter

Register the limiter from AddRateLimiter() method as shown below. The options parameter allows you to configure one or more rate-limiting policies for your application by User i.e. Identity.

using Microsoft.AspNetCore.RateLimiting;
using System.Threading.RateLimiting;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRateLimiter(options =>
{
    options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
    
    options.AddFixedWindowLimiter("PublicAPI", opt =>
    {
        opt.PermitLimit = 3;
        opt.Window = TimeSpan.FromSeconds(10);
        opt.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
        opt.QueueLimit = 5;
    });
});

var app = builder.Build();

We created a fixed-window rate limiter policy named “PublicAPI” that controls how many requests a client can make within a specific time period. The fixed-window rate-limiting policy is named “PublicAPI”. A fixed window divides time into predefined intervals. In this example, the application allows a certain number of requests during each 10 second window.

opt.PermitLimit = 3;

This allows a maximum of 3 requests during each time window. For example, if a client sends 3 requests within the current 10-second window, those requests are allowed. Additional requests are subject to the configured queue and, once the queue is full, will be rejected.

This sets the rate-limiting window to 10 seconds.

opt.Window = TimeSpan.FromSeconds(10);

After the 10 second window expires, the request counter resets and the client can make another 3 requests.

We then configure queued requests. When the request limit has been reached, ASP.NET Core can temporarily queue additional requests. OldestFirst means requests are processed in the order they entered the queue—the first request added to the queue is processed first.

opt.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;

Next, we set the queue size to 5.

opt.QueueLimit = 5;

This allows up to 4 additional requests to wait in the queue after the 3-request limit has been reached. Any additional requests are rejected when the queue is full.

Notice the code line:

options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;

options.RejectionStatusCode = StatusCodes.Status429TooManyRequests; specifies the HTTP status code that ASP.NET Core returns when a request is rejected by the rate limiter. HTTP 429 Too Many Requests indicates that the client has sent more requests than the configured rate limit allows within the specified time period.

The additional request can be rejected with:

HTTP/1.1 429 Too Many Requests

Add the Limiter

In the Program.cs file, enable the rate limiting middleware by calling UseRateLimiter() method. The UseRateLimiter() must be called after UseRouting().

app.UseRouting();

app.UseRateLimiter();

app.MapControllers();

app.Run();

If you are using authorization then use limiter before it so that authorization pipeline does not perform CPU heavy work.

app.UseRouting();
app.UseRateLimiter();      // before auth work
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

Apply Rate Limiting Policies to API Endpoints and Pages

This is how we apply the limiter policy to Minimal API endpoint:

app.MapGet("/api/resource", () => Results.Ok("Rate limited resource"))
   .RequireRateLimiting("PublicAPI");

For API Controllers:

We apply the [EnableRateLimiting] attribute on the controller.

[ApiController]
[Route("api/[controller]")]
[EnableRateLimiting("PublicAPI")]
public class Resource : ControllerBase
{
    [HttpGet]
    public IActionResult Get() => Ok("Rate limited resource");
}

We can also apply [EnableRateLimiting] attribute to a specific action:

[EnableRateLimiting("fixed")]
public class ProductsController : ControllerBase
{
    // Actions
}

For MVC Controllers:

We add the RequireRateLimiting() method on the endpoint.

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers().RequireRateLimiting("PublicAPI");
});
Global Rate Limiting Middleware

A global rate-limiting middleware is a way to apply a rate-limit policy to all incoming HTTP requests in your application, rather than applying rate limiting individually to selected controllers or endpoints.

We configure a global limiter when registering the rate-limiting services:

builder.Services.AddRateLimiter(options =>
{
    options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(
        httpContext =>
            RateLimitPartition.GetFixedWindowLimiter(
                partitionKey: httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown",
                factory: _ => new FixedWindowRateLimiterOptions
                {
                    PermitLimit = 10,
                    Window = TimeSpan.FromSeconds(10),
                    QueueLimit = 0
                }));
});

Here options.GlobalLimiter = …; defines a global limiter.

With this configuration, every request passing through the rate-limiting middleware is evaluated by the global limiter. In this example, each IP address can make up to 10 requests every 10 seconds.

It should also be noted that a global limiter does not require you to add .RequireRateLimiting() to every endpoint.

Disable Rate Limiting for an Endpoint

You can disable rate limiting for a specific endpoint by calling DisableRateLimiting(). This is particularly useful when rate limiting is applied globally, but you want a specific endpoint to be excluded. Example:

app.MapGet("/health", () =>
{
    return Results.Ok("Application is healthy");
})
.DisableRateLimiting();

The DisableRateLimiting attribute exempts an endpoint or controller from rate limiting. Example:

[HttpGet]
[DisableRateLimiting]
public IActionResult HealthCheck()
{
    return Ok("Service is running");
}

Rate Limiter Algorithms

When choosing a rate limiter, you should consider the cost of the endpoint. This cost depends on the resources required to process each request, such as processing time, database access, CPU usage, and I/O operations.

.NET Core provides 4 Rate Limiting Algorithms to choose from, these are:

  1. Fixed window
  2. Sliding window
  3. Token bucket
  4. Concurrency

Fixed Window Limiter

The Fixed Window Limiter limits the number of requests that a client can make during a fixed period of time.

For example, suppose you configure your API to allow 10 requests every 1 minute. The limiter creates a one-minute window and allows the first 10 requests during that window. Once the limit is reached, additional requests are rejected with a 429 Too Many Requests response.

10:00:00 ───────────────── 10:01:00
          Fixed Window
        ┌─────────────────┐
        │ 10 requests     │
        │     allowed     │
        └─────────────────┘

Requests 1–10  → ✅ Allowed
Request 11     → ❌ 429 Too Many Requests
Request 12     → ❌ 429 Too Many Requests

10:01:00 → New window starts
            ↓
       10 requests allowed again

See the following code of a Fixed Window Rate Limiter. The limiter allows 5 requests during each 15-second window.

builder.Services.AddRateLimiter(_ => _
    .AddFixedWindowLimiter(policyName: "fixed", options =>
    {
        options.PermitLimit = 5;
        options.Window = TimeSpan.FromSeconds(15);
        options.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
        options.QueueLimit = 3;
    }));
  • After those 5 requests have been permitted, additional requests cannot immediately execute.
  • When a new window starts, the request count is reset.
  • QueueProcessingOrder.OldestFirst – determines how requests waiting in the queue are processed. OldestFirst means: The request that has been waiting the longest gets processed first.
  • QueueLimit = 3 – This allows up to 3 additional requests to wait in the queue.

So we could have:

5 requests → immediately permitted
3 requests → waiting in queue

9th request → cannot be queued
             ↓
       429 Too Many Requests
When to Use Fixed Window Limiter

Let’s see some necessary conditions where you should use this algo.

  • Simple API Request Limits – Use a Fixed Window Limiter when you want to allow a specific number of requests during a fixed period, such as 100 requests per minute. It is simple to configure and works well for basic public APIs.
  • Protecting Database-Heavy Endpoints – If an endpoint performs expensive database queries, you can limit it to something like 20 requests every 30 seconds. This helps prevent excessive traffic from putting unnecessary load on the database.
  • Controlling Usage of External Services – If your API calls an external service such as a payment gateway, email provider, or third-party API, you can limit requests to 50 requests per minute. This helps prevent your application from making excessive calls to that service.
When not to Use Fixed Window Limiter

Some conditions to avoid this are:

  • When you need smoother traffic control – If you want to prevent users from sending a large burst of requests around the boundary between two time windows, a Sliding Window Limiter is a better choice. For example, if you need to allow 5 requests in any 30-second period, Sliding Window provides better control.
  • When your API needs to support controlled bursts – If users normally make a few requests but occasionally need to send a larger burst, a Token Bucket Limiter may be more appropriate. It allows controlled bursts while still limiting the overall request rate.

Sliding Window Limiter

The Sliding Window Limiter is a rate-limiting algorithm that controls how many requests a client can make within a moving time period.

Unlike the Fixed Window Limiter, which resets the request count at a fixed boundary, the Sliding Window Limiter continuously moves the time window forward. This provides smoother traffic control and helps prevent sudden bursts of requests around the boundary of two fixed windows.

The Sliding Window Limiter works similarly to the Fixed Window Limiter but divides the window into multiple segments. The window moves forward by one segment at each segment interval. The length of each segment is calculated as window duration ÷ number of segments per window.

Understanding Sliding Window in Plain Text

A Sliding Window Limiter continuously looks at a moving period of time and counts requests made during that period. As old requests fall outside the window, new requests become allowed. Let’s take an example and say – A user can make a maximum of 5 requests in any 30-second period.

User makes 5 requests

Imagine the user sends:

10:00:05 → Request 1 ✅
10:00:08 → Request 2 ✅
10:00:12 → Request 3 ✅
10:00:18 → Request 4 ✅
10:00:25 → Request 5 ✅

The user has now used all 5 permits. If the user send another request then it is rejected because the previous 30 seconds contain 5 requests.

10:00:28 → Request 6 ❌

The window starts sliding

Now it’s:

10:00:36

The limiter looks at the previous 30 seconds:

10:00:06 ───────────────── 10:00:36
          30 seconds

What happened to Request 1?

Request 1 → 10:00:05

It is now more than 30 seconds old, so it falls outside the window. Therefore, Request 1 is no longer counted. The limiter now sees:

10:00:08 → Request 2
10:00:12 → Request 3
10:00:18 → Request 4
10:00:25 → Request 5

That’s only 4 requests inside the current 30-second window. Therefore, a new request can be accepted:

10:00:36 → Request 6 ✅

Below, we have defined a sliding window limiter. It includes maximum 5 requests in the window and sliding window is 30 seconds long.

builder.Services.AddRateLimiter(_ => _
    .AddSlidingWindowLimiter(policyName: "sliding", options =>
    {
        options.PermitLimit = 5;
        options.Window = TimeSpan.FromSeconds(30);
        options.SegmentsPerWindow = 3;
        options.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
        options.QueueLimit = 0;
    }));

SegmentsPerWindow is set as 3. This means the limiter divides the 30-second window into 3 segments.

30 seconds
┌──────────┬──────────┬──────────┐
│ 10 sec   │ 10 sec   │ 10 sec   │
└──────────┴──────────┴──────────┘

As time advances, the segments move forward, which gives you the sliding-window behavior. It should also be noted that sliding window limiter uses segments to approximate the sliding behavior rather than maintaining a precise timestamp list for every individual request.

When to Use Sliding Window Limiter

Here are some practical examples where a Sliding Window Limiter is useful:

  1. Public Web APIs – Allow a user to make 100 requests in any 1-minute period. This prevents a client from sending a large burst of requests while still allowing normal API usage.
  2. Login and Authentication APIs – Allow a maximum of 5 login attempts in any 30-second period. This can help prevent a client from repeatedly sending login requests.
  3. Search APIs – Allow 20 searches in any 60-second period. This prevents a user or application from continuously sending expensive search queries.
  4. Payment APIs – Allow 10 payment-related requests in any 1-minute period. This can help protect payment services from excessive traffic.
  5. Database-Heavy APIs – If an endpoint performs expensive database queries, you could allow 30 requests in any 1-minute period to prevent excessive database load.
  6. External API Calls – If your API calls an external service such as a payment provider, email service, or third-party API, a Sliding Window Limiter can prevent your application from making too many calls in a short period.
  7. File Upload APIs – You could allow 10 uploads in any 5-minute period to prevent a user from continuously uploading files and consuming server resources.
When Not to Use Sliding Window Limiter

Some examples where you don’t want to use this algo.

  1. Simple API with a fixed limit — Use Fixed Window
  2. API that needs controlled bursts — Use Token Bucket
  3. Expensive operations that must run simultaneously — Use Concurrency Limiter
  4. Internal health-check endpoint — Don’t unnecessarily rate limit
  5. File upload with occasional bursts — Token Bucket

Token Bucket Limiter

A Token Bucket Limiter is a rate-limiting algorithm that controls how many requests (or operations) are allowed to happen over time, while still permitting short bursts of traffic. It’s one of the most common rate-limiting strategies used in APIs, network traffic shaping, and distributed systems.

Imagine a bucket that holds tokens:

  1. The bucket has a maximum capacity (e.g., 100 tokens).
  2. Tokens are added at a fixed rate (e.g., 10 tokens every second) — this is called the “refill rate.”
  3. Every incoming request consumes one (or more) tokens to proceed.
  4. If there are enough tokens, the request is allowed and the tokens are deducted.
  5. If the bucket is empty, the request is rejected or delayed until more tokens are added.
  6. Tokens stop accumulating once the bucket is full — excess refill is simply discarded.

The key advantage over simpler algorithms (like a fixed request counter) is that it allows bursty traffic while still enforcing a long-term average rate.

An example of this algorithm is given below:

using System.Threading.RateLimiting;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRateLimiter(options =>
{
    options.AddTokenBucketLimiter("token-bucket", opt =>
    {
        opt.TokenLimit = 100;              // max tokens (burst capacity)
        opt.TokensPerPeriod = 20;          // tokens added per replenishment
        opt.ReplenishmentPeriod = TimeSpan.FromSeconds(10); // how often to add tokens
        opt.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
        opt.QueueLimit = 10;               // requests allowed to wait in queue
        opt.AutoReplenishment = true;      // let the timer refill automatically
    });

    options.OnRejected = async (context, token) =>
    {
        context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;
        await context.HttpContext.Response.WriteAsync("Too many requests. Try again later.", token);
    };
});

var app = builder.Build();

app.UseRateLimiter();

app.MapGet("/api/data", () => "Hello!")
   .RequireRateLimiting("token-bucket");

app.Run();

Note that when AutoReplenishment is set to true, an internal timer automatically refills tokens on the interval defined by ReplenishmentPeriod. When it’s set to false, that automatic refill doesn’t happen — the app is responsible for triggering it manually by calling TryReplenish on the limiter.

When to use Token Bucket

A Token Bucket limiter is best when you want to allow short bursts of requests while maintaining a controlled request rate over time. Here are some common scenarios:

  1. APIs that experience occasional traffic bursts – Example: A product API normally receives 2 requests per second but may receive 20 requests when a new product is released.
  2. Public APIs with request quotas – Example: Allow a client to make up to 100 requests initially and replenish 10 tokens every second.
  3. File upload or batch-processing APIs – Example: An API processes uploaded images and allows 20 processing requests immediately, followed by 5 new requests every second.
  4. External API integrations – Example: A third-party API allows 100 requests per minute. Your application can use a token bucket to control outgoing requests and still permit short bursts.

Concurrency Limiter

A concurrency limiter is a rate-limiting strategy that controls how many requests can be processed at the same time, rather than controlling the rate of requests over a time period. It limits simultaneous, in-flight work — not how frequently requests arrive.

Think of it as a fixed number of “slots” or “permits”:

  • A limiter is configured with a permit limit (e.g., 10 concurrent permits).
  • Each incoming request tries to acquire a permit before being processed.
  • If a permit is available, it’s acquired and the request proceeds.
  • If all permits are in use, the request either waits in a queue or is rejected, depending on configuration.
  • When the request finishes (success or failure), the permit is released back to the pool for the next waiting request.

Unlike token bucket, there’s no replenishment over time — permits aren’t refilled on a timer. A permit becomes available again only when an in-flight request completes and releases it.

A key distinction: with token bucket, a request that takes 5 seconds to process doesn’t hold anything “reserved” — it just spent a token on entry. With a concurrency limiter, that same slow request occupies a permit for its full 5 seconds, directly reducing how many other requests can run concurrently.

Example:

using System.Threading.RateLimiting;

builder.Services.AddRateLimiter(options =>
{
    options.AddConcurrencyLimiter("concurrency-policy", opt =>
    {
        opt.PermitLimit = 10;              // max simultaneous requests
        opt.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
        opt.QueueLimit = 5;                // requests allowed to wait for a free permit
    });

    options.OnRejected = async (context, token) =>
    {
        context.HttpContext.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
        await context.HttpContext.Response.WriteAsync("Server busy, try again shortly.", token);
    };
});

app.UseRateLimiter();

app.MapGet("/api/heavy-report", async () =>
{
    await Task.Delay(3000); // simulate expensive work
    return "done";
})
.RequireRateLimiting("concurrency-policy");
When to Use It
  1. Protecting limited backend resources: e.g., a database connection pool that can only handle 20 concurrent queries — cap concurrent requests to match.
  2. Guarding expensive or slow operations: report generation, image processing, ML inference — where each request holds resources for a while, and too many at once would exhaust memory/CPU.
  3. Preventing thread pool exhaustion: capping how many requests are simultaneously in flight so the server doesn’t get overwhelmed regardless of how fast requests arrive.
  4. Wrapping calls to a downstream service with limited capacity: e.g., a third-party API that can only handle 5 concurrent connections from you.

When It’s Not the Best Fit

  1. If you care about total volume over time (e.g., “1000 requests/hour”) rather than simultaneous load, a token bucket or fixed/sliding window is more appropriate — concurrency limiter says nothing about requests-per-second if each one is fast.
  2. If requests are fast and uniform, concurrency limiting adds little value over simpler rate-based approaches, since permits free up almost instantly anyway.

Rate Limiting Partitions in ASP.NET Core: Control API Traffic by Client

Rate Limiting Partitions let you apply separate rate limit instances to different groups of requests, instead of one global limiter shared by everyone. Each partition gets its own independent bucket/counter/permit pool, keyed by something you choose — typically the client identity.

The Core Problem It Solves

Without partitioning, a single limiter (say, 100 requests/minute) is shared across all traffic. That means one aggressive client can consume the entire quota, starving every other user — even though the intent was “100 requests/minute per user,” not “100 requests/minute total across everyone.”

Partitioning fixes this by creating a separate limiter instance per partition key, so each key (user, IP, API key, tenant, etc.) gets its own isolated quota.

How It Works

  1. You define a partition key selector — a function that inspects the incoming request and returns a key (e.g., the user’s ID, API key, or IP address).
  2. The rate limiter maintains a dictionary of limiters internally, one per unique key value. When a request comes in, its key is computed, and the request is checked against that specific partition’s limiter — not a shared global one.
  3. Partitions are typically created lazily (on first request from a new key) and can be evicted when idle to avoid unbounded memory growth.
By IP Address

Partitioning by IP address means giving each unique client IP its own independent rate limit bucket, instead of sharing one global limit across all traffic. It’s the most common way to rate-limit anonymous/unauthenticated requests, since there’s no user ID or API key to key off of.

Example:

using System.Threading.RateLimiting;
using System.Net;

builder.Services.AddRateLimiter(options =>
{
    options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, IPAddress>(httpContext =>
    {
        var ipAddress = httpContext.Connection.RemoteIpAddress ?? IPAddress.None;

        return RateLimitPartition.GetTokenBucketLimiter(ipAddress, _ =>
            new TokenBucketRateLimiterOptions
            {
                TokenLimit = 50,
                TokensPerPeriod = 10,
                ReplenishmentPeriod = TimeSpan.FromSeconds(10),
                QueueLimit = 0,
                AutoReplenishment = true
            });
    });
});

Each unique IP (203.0.113.5, 198.51.100.22, etc.) gets its own bucket. IP “A” exhausting their limit doesn’t affect IP “B” at all.

Where the IP Comes From

HttpContext.Connection.RemoteIpAddress gives you the IP of the direct TCP connection to your server. This is fine if your app is directly internet-facing, but in most real deployments there’s a proxy, load balancer, or CDN in front (nginx, IIS, Azure App Service, Cloudflare, AWS ALB, etc.). In that case, RemoteIpAddress will be the proxy’s IP, not the real client’s — every request looks like it comes from the same source, defeating the purpose of per-IP partitioning.

Fix: use Forwarded Headers Middleware to extract the real client IP from headers like X-Forwarded-For:

app.UseForwardedHeaders(new ForwardedHeadersOptions
{
    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});

app.UseRateLimiter(); // after forwarded headers, so RemoteIpAddress is corrected

⚠️ Important: only trust X-Forwarded-For from proxies you control. If it’s blindly trusted from any client, an attacker can spoof the header and claim any IP they want — including deliberately rotating fake IPs to bypass rate limiting entirely. Configure KnownProxies/KnownNetworks on ForwardedHeadersOptions to restrict which upstream hops are trusted.

Why Use IP-Based Partitioning

  1. No authentication required — works for public endpoints, login pages, signup forms, password reset flows — anywhere a user isn’t identified yet.
  2. First line of defense against abuse/scraping — bots and scrapers usually don’t authenticate, so IP is often the only identifying signal available.
  3. Brute-force protection — e.g., limiting login attempts per IP to slow down credential-stuffing attacks.
By User Identity

Partitioning by User Identity means giving each authenticated user their own independent rate limit bucket, keyed off something that uniquely and durably identifies them — typically a user ID or a claim from their auth token — rather than their IP address or connection.

Example:

using System.Threading.RateLimiting;

builder.Services.AddRateLimiter(options =>
{
    options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(httpContext =>
    {
        var userId = httpContext.User.Identity?.IsAuthenticated == true
            ? httpContext.User.FindFirst("sub")?.Value ?? httpContext.User.Identity!.Name!
            : "anonymous"; // or fall back to IP — see below

        return RateLimitPartition.GetTokenBucketLimiter(userId, _ =>
            new TokenBucketRateLimiterOptions
            {
                TokenLimit = 100,
                TokensPerPeriod = 20,
                ReplenishmentPeriod = TimeSpan.FromSeconds(10),
                QueueLimit = 0,
                AutoReplenishment = true
            });
    });
});

Each unique user gets their own bucket, keyed by a stable identifier — commonly the sub claim (subject) from a JWT, a database user ID, or ClaimTypes.NameIdentifier. User A exhausting their quota has zero effect on User B.

Where the Identity Comes From

  • HttpContext.User.Identity.Name — typically populated from the auth cookie/token if using standard ASP.NET Core identity.
  • Specific claims — httpContext.User.FindFirst(ClaimTypes.NameIdentifier) or a custom claim like sub (common in JWT-based auth) is usually more reliable than Name, which can sometimes be null or represent a display name rather than a stable ID.

Typical Full Pipeline Order

app.UseAuthentication();   // populates HttpContext.User
app.UseAuthorization();
app.UseRateLimiter();      // now User.Identity is available for partition key selection

Getting this order right is the most common mistake — if UseRateLimiter() runs before UseAuthentication(), httpContext.User won’t be populated yet, and every request will silently fall into your anonymous/fallback branch regardless of whether the user is actually logged in.

Why By User Identity is Better Than By IP for Authenticated Traffic

IP-basedUser-identity-based
StabilityChanges when user switches networks (WiFi → mobile), uses VPN, or gets a new DHCP leaseStays the same across devices, networks, and sessions
FairnessMultiple users behind the same NAT/office network share one bucketEach individual user is isolated, regardless of shared network
Bypass riskAttacker can rotate IPs (proxy pools, botnets) to get fresh bucketsRequires a new account to get a fresh bucket — much higher cost to abuse
GranularitySame limit for everyone on that IPCan vary by user attributes (see tiering below)
By API Key

Partitioning by API Key means giving each API key its own independent rate limit bucket — the standard approach for machine-to-machine APIs, third-party integrations, and public developer APIs where clients authenticate via a key rather than a user login session.

using System.Threading.RateLimiting;

builder.Services.AddRateLimiter(options =>
{
    options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(httpContext =>
    {
        var apiKey = httpContext.Request.Headers["X-Api-Key"].ToString();

        if (string.IsNullOrEmpty(apiKey))
            return RateLimitPartition.GetTokenBucketLimiter("no-key", _ => RejectAllOptions);

        return RateLimitPartition.GetTokenBucketLimiter(apiKey, _ =>
            new TokenBucketRateLimiterOptions
            {
                TokenLimit = 500,
                TokensPerPeriod = 100,
                ReplenishmentPeriod = TimeSpan.FromSeconds(10),
                QueueLimit = 0,
                AutoReplenishment = true
            });
    });
});

Each unique API key gets its own bucket. Key “A” exhausting its quota has no effect on Key “B” — even if both keys belong to requests hitting the exact same endpoint at the exact same time.

This is exactly how Stripe, GitHub, Twilio, and most public APIs communicate limits — “1000 requests/hour per API key,” not per IP or per account holistically.

Where the Key Comes From

  • Header — most common: X-Api-Key, Authorization: Bearer <key>, or a custom header defined by your API contract.
  • Query string — less secure (logged in URLs, browser history) but still seen in some legacy/public APIs: ?api_key=abc123.
  • Combined with auth middleware — if you validate the key via an IAuthenticationHandler or custom middleware, you can pull the already-validated key/customer from HttpContext.Items or HttpContext.User claims instead of re-parsing the header in the partition key selector.

Common Pattern: Look Up Plan/Tier from the Key

Unlike a raw IP or even a user ID, an API key usually maps to a customer record you control — so the limiter factory typically does a lookup (often cached) to pull tier-specific settings:

options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(httpContext =>
{
    var apiKey = httpContext.Request.Headers["X-Api-Key"].ToString();

    return RateLimitPartition.GetTokenBucketLimiter(apiKey, key =>
    {
        // Cached lookup — avoid hitting DB on every request
        var customer = ApiKeyCache.GetCustomerByKey(key);

        return customer?.Plan switch
        {
            "enterprise" => new TokenBucketRateLimiterOptions
            {
                TokenLimit = 5000, TokensPerPeriod = 1000,
                ReplenishmentPeriod = TimeSpan.FromSeconds(10), AutoReplenishment = true
            },
            "standard" => new TokenBucketRateLimiterOptions
            {
                TokenLimit = 500, TokensPerPeriod = 100,
                ReplenishmentPeriod = TimeSpan.FromSeconds(10), AutoReplenishment = true
            },
            _ => new TokenBucketRateLimiterOptions // unknown/free/invalid key
            {
                TokenLimit = 20, TokensPerPeriod = 5,
                ReplenishmentPeriod = TimeSpan.FromSeconds(10), AutoReplenishment = true
            }
        };
    });
});

The factory delegate passed to GetTokenBucketLimiter only runs once per new key (when the partition is first created), not on every request — so the lookup cost is amortized, not paid per-call.

By Endpoint Path

Partitioning by Endpoint Path means giving each route/endpoint its own independent rate limit bucket — so /api/search and /api/export are limited separately, instead of sharing one global quota. This controls which operations get limited and how strictly, rather than who is making the request.

using System.Threading.RateLimiting;

builder.Services.AddRateLimiter(options =>
{
    options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(httpContext =>
    {
        var path = httpContext.Request.Path.Value?.ToLowerInvariant() ?? "unknown";

        return RateLimitPartition.GetTokenBucketLimiter(path, _ =>
            new TokenBucketRateLimiterOptions
            {
                TokenLimit = 50,
                TokensPerPeriod = 10,
                ReplenishmentPeriod = TimeSpan.FromSeconds(10),
                QueueLimit = 0,
                AutoReplenishment = true
            });
    });
});

Every request to /api/reports/generate shares one bucket; every request to /api/products shares a different bucket. A burst on one endpoint doesn’t consume quota meant for another.

ASP.NET Core Chained Rate Limiters: Apply Multiple Limits

Chained Limiters refers to combining multiple rate limiters so that a request must pass through all of them before it’s allowed through. This is done using PartitionedRateLimiter.CreateChained().

Why use chained limiters?

Sometimes a single rate-limiting algorithm isn’t enough. For example, you might want:

  • A global limit (protect the whole server from being overwhelmed)
  • PLUS a per-user or per-IP limit (prevent one client from hogging capacity)

Chaining lets you enforce both simultaneously — a request is only permitted if it passes every limiter in the chain.

builder.Services.AddRateLimiter(options =>
{
    options.GlobalLimiter = PartitionedRateLimiter.CreateChained(
        // Limiter 1: Global limit across all requests
        PartitionedRateLimiter.Create<HttpContext, string>(context =>
            RateLimitPartition.GetFixedWindowLimiter("global", _ =>
                new FixedWindowRateLimiterOptions
                {
                    PermitLimit = 100,
                    Window = TimeSpan.FromSeconds(10)
                })),

        // Limiter 2: Per-client limit (e.g., by IP)
        PartitionedRateLimiter.Create<HttpContext, string>(context =>
        {
            var ip = context.Connection.RemoteIpAddress?.ToString() ?? "unknown";
            return RateLimitPartition.GetSlidingWindowLimiter(ip, _ =>
                new SlidingWindowRateLimiterOptions
                {
                    PermitLimit = 10,
                    Window = TimeSpan.FromSeconds(10),
                    SegmentsPerWindow = 2
                });
        })
    );
});

app.UseRateLimiter();

Key Points

  • PartitionedRateLimiter.CreateChained(params …) takes multiple PartitionedRateLimiter<T> instances and returns one combined limiter.
  • A request is allowed only if every limiter in the chain grants a lease. If any one of them rejects it, the whole chain rejects it.
  • Each limiter in the chain can use a different algorithm (fixed window, sliding window, token bucket, concurrency limiter) and a different partition key (per-IP, per-user, global, per-endpoint, etc.).
  • Useful for layered protection: e.g., a strict global ceiling plus a looser per-user quota, or a burst-friendly token bucket combined with a hard concurrency cap.
  • You dispose of leases properly (the middleware handles this automatically when used via UseRateLimiter()), and rejected requests get a 503 (configurable) with an optional Retry-After header.

If you’re using this alongside endpoint-specific policies (RequireRateLimiting(“policyName”)), you can also chain limiters within a named policy the same way, not just in the global limiter.

Custom Rejection Handling in Limiters

Without Rejection Handling in Limiters, they returns a bare 503 Service Unavailable (or your configured status code) with no body. Most real apps want a friendlier response:

options.OnRejected = async (context, token) =>
{
    context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;

    if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter))
    {
        context.HttpContext.Response.Headers.RetryAfter =
            ((int)retryAfter.TotalSeconds).ToString();
    }

    await context.HttpContext.Response.WriteAsync(
        "Too many requests. Please try again later.", token);
};

RejectionStatusCode and OnRejected are both global settings on RateLimiterOptions. They apply uniformly to every rejection in the app, regardless of which limiter (global limiter or any named policy) triggered it. If you want different behavior per policy, then you have to build your own custom logic.

Putting it together:

using Microsoft.AspNetCore.RateLimiting;
using System.Threading.RateLimiting;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRateLimiter(options =>
{
    options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;

    // Added: custom rejection handling
    options.OnRejected = async (context, token) =>
    {
        context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;

        if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter))
        {
            context.HttpContext.Response.Headers.RetryAfter =
                ((int)retryAfter.TotalSeconds).ToString();
        }

        await context.HttpContext.Response.WriteAsync(
            "Too many requests. Please try again later.", token);
    };

    options.AddFixedWindowLimiter("PublicAPI", opt =>
    {
        opt.PermitLimit = 3;
        opt.Window = TimeSpan.FromSeconds(10);
        opt.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
        opt.QueueLimit = 5;
    });
});

var app = builder.Build();

app.UseRateLimiter();

app.MapGet("/public-data", () => "Here's some public data")
   .RequireRateLimiting("PublicAPI");

app.Run();

Beware the In-Memory Per-Instance Rate Limiting Trap

“The In-Memory Per-Instance Trap” refers to a common pitfall with ASP.NET Core’s built-in rate limiting middleware: by default, all the limiters (FixedWindowLimiter, SlidingWindowLimiter, TokenBucketLimiter, ConcurrencyLimiter) store their state in memory, inside a single process. This works perfectly on a single server — but becomes a serious problem the moment you scale out.

Every rate limiter you configure (e.g., PermitLimit = 3 per 10 seconds) tracks its counters using in-memory data structures (dictionaries, counters, etc.) that live entirely within that one running instance of your app. There is no built-in distributed store (like Redis) behind it.

It’s called a trap because the code looks correct and works fine in dev/testing — but silently breaks the moment you deploy to a realistic production topology:

Scenario: You deploy behind a load balancer with 3 instances

┌─────────────┐
                    │ Load Balancer│
                    └──────┬──────┘
              ┌────────────┼────────────┐
              ▼            ▼            ▼
        ┌──────────┐ ┌──────────┐ ┌──────────┐
         │Instance A │   │Instance B│    │Instance C│
         │ (limit: 3)│   │(limit: 3)│    │(limit: 3)│
        └──────────┘ └──────────┘ └──────────┘

You configured:

opt.PermitLimit = 3;
opt.Window = TimeSpan.FromSeconds(10);

Intent: “Allow only 3 requests per 10 seconds, globally.”

Reality: Each instance enforces its own separate limit of 3. So if the load balancer round-robins traffic, the same client (or the API as a whole) can actually get:

3 (Instance A) + 3 (Instance B) + 3 (Instance C) = 9 requests allowed

— 3x your intended limit, simply because each server has no idea what the others are counting.

Where this bites people:

  • Auto-scaling environments (Kubernetes, Azure App Service scale-out, AWS ECS) — instance count changes dynamically, so your effective limit changes too, unpredictably.
  • Per-user/per-IP limiters — a client could get routed to different instances across requests and never actually hit the “per-user” cap you intended.
  • Security-sensitive limiters (e.g., login attempt throttling) — this is the worst case. A limiter meant to block brute-force attacks becomes far less effective when an attacker’s requests get spread across instances, multiplying their effective attempt budget.
  • Restarts/deployments — since state is in-memory, a simple app restart or rolling deployment resets all counters to zero instantly, wiping out any accumulated rate-limit state.

In order to avoid this trap we use a distributed backing store — most commonly Redis — instead of relying on in-memory state. The next topic covers this in details.

Distributed Rate Limiting: Scaling Request Control Across Multiple Servers

“Use a distributed backing store — most commonly Redis” means: instead of each app instance keeping rate-limit counters in its own local memory, all instances point to one shared, external store (Redis) that holds the single source of truth for how many requests have been made. Every instance reads and writes to that same store, so the limit is enforced correctly no matter how many instances are running or which one a request lands on.

Why Redis specifically:

  • Fast
  • Atomic operations
  • TTL/expiry support
  • Widely available

Take for example, a scenario before Redis:

Instance A: counter = 3 (in its own RAM)
Instance B: counter = 3 (in its own RAM)
Instance C: counter = 3 (in its own RAM)
→ Effective limit = 9, not 3

After Redis is applied, every instance, before allowing a request, asks Redis “what’s the current count for this key?” and increments it there — not locally.

Instance A ─┐
Instance B ─┼──► Redis: counter = 3  (ONE shared value)
Instance C ─┘
→ Effective limit = 3, enforced correctly regardless of instance count

Implementation

RedisRateLimiting.AspNetCore is a third-party NuGet package that enables distributed rate limiting for ASP.NET Core applications using Redis.

Install it by the below command:

Install-Package RedisRateLimiting.AspNetCore

Add your Redis connection string to appsettings.json:

{
  "ConnectionStrings": {
    "Redis": "localhost:6379"
  }
}

Next, in the Program.cs, configure the Rate Limiter:

using Microsoft.AspNetCore.RateLimiting;
using StackExchange.Redis;

var builder = WebApplication.CreateBuilder(args);

// Connect to Redis
var connectionMultiplexer = ConnectionMultiplexer.Connect(
    builder.Configuration.GetConnectionString("Redis")!);

// Configure Redis-backed rate limiting
builder.Services.AddRateLimiter(options =>
{
    options.AddRedisFixedWindowLimiter("redis", opt =>
    {
        opt.ConnectionMultiplexerFactory = () => connectionMultiplexer;

        // Allow 5 requests
        opt.PermitLimit = 5;

        // Every 10 seconds
        opt.Window = TimeSpan.FromSeconds(10);
    });

    options.OnRejected = async (context, cancellationToken) =>
    {
        context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;

        await context.HttpContext.Response.WriteAsync(
            "Too many requests. Please try again later.",
            cancellationToken);
    };
});

var app = builder.Build();

app.UseRateLimiter();

app.MapGet("/", () => "Request successful!")
   .RequireRateLimiting("redis");

app.Run();

The package provides AddRedisFixedWindowLimiter, with the Redis connection supplied through ConnectionMultiplexerFactory.

How this Works with Multiple Servers

Imagine your application is running on three instances:

Load Balancer
                       |
          -------------------------
          |           |           |
       App 1        App 2        App 3
          \           |          /
           \          |         /
                  Redis
              Shared Counter

Suppose the limit is: 5 requests per 10 seconds. Without Redis, each application instance could maintain its own counter.

With this Redis-backed limiter, the instances use Redis as shared rate-limiting storage, so the configured limit is enforced across the distributed deployment rather than independently per server.

This package supports other limiters like:

  • Concurrency Limiter
  • Fixed Window Limiter
  • Sliding Window Limiter
  • Token Bucket Limiter

For example, the token bucket extension is:

options.AddRedisTokenBucketLimiter("token", opt =>
{
    opt.ConnectionMultiplexerFactory = () => connectionMultiplexer;

    opt.TokenLimit = 10;
    opt.TokensPerPeriod = 5;
    opt.ReplenishmentPeriod = TimeSpan.FromSeconds(10);
});

How to Test Endpoints with Rate Limiting

Before deploying an ASP.NET Core application that uses rate limiting to production, it is important to stress test the application. Rate limiting can behave differently under real-world traffic, especially when many users send requests simultaneously. Stress testing helps you verify that the configured limiter and its options actually provide the protection you expect.

For example, you might configure a rate limiter to allow only a certain number of requests within a specific time window. Manually sending a few requests can confirm that the basic configuration works, but it doesn’t tell you how the application behaves when hundreds or thousands of requests arrive concurrently.

Create a Load-Test Script

A practical approach is to create a JMeter test script that repeatedly calls your rate-limited endpoints. You can create the script using tools such as Apache JMeter HTTP(S) Test Script Recorder or BlazeMeter.

For example, your JMeter test might send 1,000 requests to an endpoint such as:

GET /api/products

If your limiter allows 100 requests per minute, the test should demonstrate that approximately the configured number of requests are accepted while additional requests are rejected with:

HTTP 429 Too Many Requests

Run the Test with Azure Load Testing

Once your JMeter script is ready, you can upload it to Azure Load Testing and run a load test against your application.

This allows you to simulate realistic traffic and observe how your application behaves when the rate limit is reached.

During the test, pay particular attention to:

  • HTTP 200 responses — requests successfully processed by the application.
  • HTTP 429 responses — requests rejected because the rate limit was exceeded.
  • Response times — whether latency increases as traffic grows.
  • CPU and memory usage — whether the application remains healthy under load.
  • Queue behavior — if you configured a non-zero QueueLimit.
  • Rejection behavior — whether your OnRejected handler behaves correctly.
  • Recovery — whether requests are accepted normally once the rate-limit window resets.

Why Stress Testing Matters

The purpose of rate limiting isn’t simply to make some requests return 429. You need to verify that the limiter actually protects your application’s expensive resources under heavy traffic. For example, imagine an endpoint that performs several expensive operations:

Client
   ↓
1000 requests
   ↓
Rate Limiter
   ├── Allowed → Application → Database / External APIs
   │
   └── Rejected → 429 Too Many Requests

A properly configured limiter should reject excessive requests before they reach the expensive application logic. This can prevent excessive CPU usage, database load, and unnecessary calls to external services.

Therefore, stress testing should be performed before production deployment. It gives you confidence that your chosen limiter, partitioning strategy, PermitLimit, Window, QueueLimit, and rejection handling are suitable for the traffic your application is expected to handle.

Summary

The importance of rate limiting goes beyond simply blocking excessive requests. It helps maintain application performance, protects expensive resources such as databases and external APIs, ensures fair usage among clients, and improves the overall reliability and stability of an application. By stopping excessive requests before they consume valuable server resources, rate limiting becomes an essential part of building secure, scalable, and resilient ASP.NET Core applications.

In this tutorial, I covered everything you need to know about Rate Limiting in ASP.NET Core, from the different types of rate limiters to their configuration and practical implementation. I hope this guide has helped you understand how rate limiting works and why it is so important for building secure, reliable, and high-performing applications.

I’d love to hear your thoughts! Let me know in the comments what you think about this tutorial and how you plan to use rate limiting in your ASP.NET Core applications.

SHARE THIS ARTICLE

  • linkedin
  • reddit
yogihosting

ABOUT THE AUTHOR

I hope you enjoyed reading this tutorial. If it helped you then consider buying a cup of coffee for me. This will help me in writing more such good tutorials for the readers. Thank you. Buy Me A Coffee donate

Leave a Reply

Your email address will not be published. Required fields are marked *