DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk4 min

Rate Limiting in ASP.NET Core Web API: Policies, Middleware, and 429 Responses

ASP.NET Core rate-limiting middleware supports global, named, and partitioned policies. Learn how to choose an algorithm, attach it correctly, and handle rejected requests.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

ASP.NET Core includes rate-limiting middleware for controlling how many requests an API accepts over time—or how many requests it processes simultaneously. Register a global or named policy with AddRateLimiter, add the middleware with UseRateLimiter, and attach named policies to endpoints or route groups. Choose the limiter and partition keys around the work your API needs to protect, then load test the configuration before deployment.

How to add rate limiting to an ASP.NET Core API

Configure the policy during service registration, then place the middleware in the request pipeline. This illustrative fixed-window configuration deliberately leaves the permit limit and window to your workload; Microsoft’s sample values are demonstrations, not production recommendations. See Microsoft’s ASP.NET Core 10.0 rate-limiting guidance.

As an Amazon Associate I earn from qualifying purchases.

builder.Services.AddRateLimiter(options =>
{
    options.AddFixedWindowLimiter("api", limiter =>
    {
        limiter.PermitLimit = permitsChosenForYourWorkload;
        limiter.Window = TimeSpan.FromMinutes(windowMinutesChosenForYourWorkload);
        limiter.QueueLimit = 0;
    });
});

var app = builder.Build();
app.UseRouting();
app.UseRateLimiter();
app.MapControllers().RequireRateLimiting("api");

The sample applies the named policy to the mapped controller endpoints. In a controller-based application, a named policy can also be attached using EnableRateLimitingAttribute; the API reference documents that attribute and the registration APIs. A policy registered but never attached does not limit the endpoints you intended to protect.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Middleware order matters for endpoint policies

For endpoint-specific policies, call UseRateLimiter after UseRouting, so endpoint selection and its metadata are available. Microsoft notes that the limiter middleware can run before routing when the application uses only a global limiter. Consult the middleware documentation when arranging the full pipeline.

Choose a limiter that matches the constraint

Time-based policies regulate requests over intervals; a concurrency policy limits work happening at the same time instead. Select based on the resource you need to protect—such as CPU, I/O, data access, or long-running operations—not on a claim that one algorithm is universally best.

Limiter What it constrains When to consider it
Fixed window Requests during a fixed interval; the counter resets when that interval ends. A periodic reset is acceptable for the endpoint’s traffic pattern.
Sliding window Requests across a moving interval divided into segments; as the window advances, expired-segment requests are recycled. A moving window better fits the desired behavior than a fixed reset.
Token bucket Requests against tokens that replenish periodically, up to the configured bucket limit. Clients should be able to send a burst, followed by controlled replenishment.
Concurrency Simultaneous requests; it does not set a request cap over a time period. The main concern is how many expensive operations run at once.

These distinctions are described in Microsoft’s middleware guidance. For example, a concurrency limit may help constrain simultaneous expensive work, but it is not a substitute for a time-based cap when the goal is to limit request volume across an interval.

Decide whether the policy is global, named, or partitioned

Global policy

Use a global limiter when the same rule should apply across the application’s endpoints. It is also the case in which the middleware can be placed before routing, according to Microsoft’s guidance.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Named policy

Register named policies when endpoints or groups need different behavior, then attach each policy to the endpoints it should govern. For instance, one policy may suit a costly operation while a different policy applies to a general API group. The limits still need to come from workload evidence rather than copied documentation examples.

Partitioned policy

A partitioned limiter creates separate buckets based on a chosen key. Microsoft’s examples use identity, IP address, API key, or endpoint path as possible dimensions. Choose a key that matches the fairness and abuse-control goal: a per-user bucket behaves differently from a shared per-IP bucket, and neither is automatically right for every API.

  • Derive keys from trusted, deliberate inputs and define how missing or unauthenticated identities are handled.
  • Keep the key space bounded. Microsoft warns that partitioning on unbounded user-controlled input can exhaust memory.
  • Check how clients may share or rotate a key; an IP-based partition, for example, can group multiple clients behind the same address.

Registration and partition factory APIs are documented in the RateLimitPartition API reference.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Return a useful rejection response without promising too much

Use the OnRejected callback to customize what the application does when a request is denied. The HTTP 429 status is commonly used by APIs to indicate that a client has sent too many requests, but the response body and API contract are application choices; Microsoft does not prescribe one universal body format.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Microsoft’s samples show a RetryAfter value for fixed-window, sliding-window, and token-bucket limiters, which can estimate when permits will be added. A concurrency limiter cannot determine when a permit will become available, so do not give clients an exact retry time for that case. If your API returns retry guidance, make sure it matches the selected limiter and the contract clients actually rely on. See Microsoft’s rate-limiting samples.

Load test and review before deployment

Permit counts, window lengths, token counts, and queue sizes are workload-specific settings, not universal defaults. Microsoft explicitly cautions that its samples are not production quality and states in its deployment guidance: “Apps using rate limiting should be carefully load tested and reviewed before deploying.” Test realistic traffic patterns and inspect the effect on both protected endpoints and legitimate clients before settling on values.

Check framework compatibility

ASP.NET Core’s built-in rate-limiting APIs are listed for versions 7.0 through 11.0 in the RateLimiterOptions API reference. Do not confuse them with the older, separate ConcurrencyLimiter middleware. Microsoft marked that middleware obsolete in ASP.NET Core 8 because rate-limiting middleware based on System.Threading.RateLimiting covers its functionality. The ASP.NET Core 11 breaking-change guidance documents its removal in ASP.NET Core 11 and a transitional Microsoft.AspNetCore.ConcurrencyLimiter 9.x or 10.x NuGet package for applications targeting net11.0 that cannot migrate immediately. Check that guidance against the target framework and package versions of your application.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

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

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.