Rate Limiting in ASP.NET Core APIs: Controlling Traffic Fairly and Predictably

Rate Limiting in ASP.NET Core APIs: Controlling Traffic Fairly and Predictably

An API must do more than return correct responses. Excessive traffic, a defective client, or deliberate abuse can exhaust database connections, overload expensive operations, and prevent other consumers from receiving service. Rate limiting controls how much capacity a client or traffic group can consume during a defined period.

ASP.NET Core provides rate limiting middleware through Microsoft.AspNetCore.RateLimiting, built on the System.Threading.RateLimiting infrastructure. It supports several limiter algorithms and allows policies to be applied globally or to selected endpoints. Rate limiting is not a complete DDoS solution, but it is a valuable application-layer control for resource protection, fair usage, and predictable API behavior.

What problem does rate limiting solve?

The number of requests an endpoint can process depends on CPU, memory, network capacity, external services, and database resources. Allowing an unlimited number of calls is especially risky for search, reporting, file generation, and authentication endpoints.

  • Abuse reduction: One client is less likely to consume the entire service capacity.
  • Fairness: Traffic can be separated by user, API key, IP address, or another meaningful partition key.
  • Resource protection: Expensive endpoints can receive stricter policies than inexpensive endpoints.
  • Clear client behavior: A client can receive 429 Too Many Requests when the configured allowance is exceeded.

Do not choose limits arbitrarily. Measure normal traffic, understand endpoint cost, and define an acceptable latency target first. Microsoft recommends carefully load testing applications that use rate limiting before deploying them to production.

Basic setup: register services and middleware

Register rate limiting services with AddRateLimiter, then add the middleware to the request pipeline. In ASP.NET Core 8 and later, the middleware requires the rate limiting services to be registered explicitly.

using System.Threading.RateLimiting;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRateLimiter(options =>
{
    options.AddFixedWindowLimiter("public-api", limiterOptions =>
    {
        limiterOptions.PermitLimit = 60;
        limiterOptions.Window = TimeSpan.FromMinutes(1);
        limiterOptions.QueueLimit = 0;
    });
});

var app = builder.Build();

app.UseRouting();
app.UseRateLimiter();

app.MapGet("/api/products", () => Results.Ok(new[] { "keyboard", "mouse" }))
   .RequireRateLimiting("public-api");

app.Run();

When a named policy is attached to an endpoint, UseRateLimiter should appear after UseRouting. Routing must identify the endpoint before endpoint-specific rate limiting metadata can be evaluated. Applications that use only a global limiter have more flexibility, but the routing-first order is a practical default when policies are involved.

Choosing the right algorithm

ASP.NET Core exposes four main limiter approaches. The correct choice depends on traffic shape, operation cost, and how much waiting the application can tolerate.

Fixed window

A fixed window permits a defined number of requests during a fixed interval, such as 60 requests per minute. It is easy to understand and configure. However, boundary effects can create short bursts: a client may use its allowance at the end of one window and immediately use another allowance when the next window begins.

Sliding window

A sliding window divides time into smaller segments and calculates usage over a moving interval. This reduces the boundary effect found in fixed windows and can provide smoother traffic behavior. It is useful when a more even request pattern is important, although it should be tested with realistic traffic.

Token bucket

With a token bucket, tokens are replenished at a configured rate and each request consumes tokens. A full bucket permits a controlled burst, while sustained traffic is limited by the replenishment rate. This model is useful for APIs that should allow short bursts without accepting unlimited continuous traffic.

Concurrency limiter

A concurrency limiter restricts the number of operations running at the same time instead of limiting the total number of requests in a time interval. It is often a better fit for long-running reports, external service calls, or database-intensive operations. Capacity is returned when a request completes.

Separate clients with partitions

A single global counter allows one busy client to affect everyone else. A PartitionedRateLimiter creates separate buckets for users, API keys, or other client identities.

builder.Services.AddRateLimiter(options =>
{
    options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(
        httpContext =>
        {
            var key = httpContext.User.Identity?.Name
                      ?? httpContext.Request.Headers.Host.ToString();

            return RateLimitPartition.GetFixedWindowLimiter(
                key,
                _ => new FixedWindowRateLimiterOptions
                {
                    PermitLimit = 100,
                    Window = TimeSpan.FromMinutes(1),
                    QueueLimit = 0,
                    AutoReplenishment = true
                });
        });
});

The identity used for partitioning must be available when the limiter evaluates the request. Therefore, middleware ordering and authentication behavior matter. If you use an IP address, make sure the application obtains the real client address safely behind a trusted reverse proxy or load balancer. Do not blindly trust arbitrary client-supplied headers, because an attacker may rotate fake addresses or cause unrelated clients to share a bucket.

Return a useful rejection response

Set the rejection status code explicitly to 429. A Retry-After response header can tell clients when they should try again.

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

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

        await context.HttpContext.Response.WriteAsJsonAsync(
            new
            {
                type = "https://httpstatuses.com/429",
                title = "Too many requests",
                status = 429,
                detail = "Please retry after the indicated interval."
            },
            cancellationToken);
    };
});

In a production API, make the response body consistent with the rest of your public contract. Do not expose internal limiter keys, authentication details, or other sensitive information. If clients retry automatically, use exponential backoff with jitter. Otherwise, many clients may retry simultaneously and create another traffic spike.

Queues are not always beneficial

A positive QueueLimit allows rejected requests to wait temporarily. This can be useful when a small and predictable delay is acceptable. Large queues, however, can consume memory, hide overload, and keep requests alive after the client has already timed out.

For fast APIs, QueueLimit = 0 often produces clearer behavior: the client receives an immediate rejection and can decide what to do. For long-running work, an explicit background job queue with a durable status model may be more appropriate than keeping HTTP requests waiting.

Match policies to endpoint cost

Not all endpoints consume the same resources. A metadata endpoint and a report-generation endpoint should not automatically receive identical limits.

Endpoint typePossible approachImportant consideration
General read APIFixed or sliding windowPartition by user or API key
Search and filteringStricter time-based limitDatabase cost and pagination
File or report generationConcurrency limiterExecution time and cancellation
AuthenticationStrict user or IP-based policyAvoid locking out legitimate users

Observability and testing

Rate limiting should be managed with metrics as well as code. Track rejected requests, policy names, endpoints, and safe client categories. Avoid logging personal data, raw tokens, or complete authentication credentials. Tests should verify parallel requests, window boundaries, expected burst behavior, queued requests, and cancellation.

During load testing, do not look only at the success rate. Review the 429 ratio, p95 and p99 latency, database connection usage, CPU, and external service calls together. A limiter may reduce pressure on one resource while another remains saturated.

Application-level rate limiting is only one layer of defense. CDN controls, a reverse proxy, a web application firewall, and a cloud provider’s DDoS protection may be needed for broader network-level threats. The application limiter should protect the resources that the application itself understands, while upstream controls handle traffic before it reaches the process.

Conclusion

ASP.NET Core rate limiting middleware provides a strong foundation for controlling API traffic according to real resource costs. A robust design selects the appropriate algorithm, partitions traffic using reliable identities, returns clear 429 responses, avoids unnecessary queues, and validates behavior with load tests. The most important operational practice is to observe real traffic and adjust limits based on evidence rather than treating an initial number as permanent.

Sources

//

0 Comments

Write Comment

E-Mail address will not be published