ASP.NET  

How to Add Built-in Rate Limiting in ASP.NET Core 10 API

Introduction

When you build a modern ASP.NET Core 10 Web API, one of the most important things to think about is how to protect your API from too many requests. If a large number of users, bots, or automated scripts start sending requests at the same time, your server can slow down, consume too many resources, or even stop working.

This is where rate limiting in ASP.NET Core 10 becomes very useful.

Rate limiting helps you control how many requests a client (user, browser, or system) can send to your API within a specific time period. The good news is that ASP.NET Core 10 provides built-in rate limiting middleware, so you do not need any third-party libraries.

In this detailed guide, you will learn how to implement rate limiting in ASP.NET Core 10 step by step using simple language, real examples, and best practices.

What is Rate Limiting?

Rate limiting is a technique used in API development to control how frequently a client can access your API.

In simple words, it means:

  • You define a limit (for example, 5 requests)

  • You define a time period (for example, 10 seconds)

  • If the client exceeds this limit, further requests are temporarily blocked

For example:

  • A user can call your API only 10 times per minute

  • After that, the API will return an error (HTTP 429 - Too Many Requests)

This concept is very important for API security, performance optimization, and scalability in ASP.NET Core applications.

Why Use Built-in Rate Limiting in ASP.NET Core 10?

ASP.NET Core 10 includes a powerful built-in rate limiting system that is easy to configure and highly efficient.

Here are some strong reasons to use it:

  • No third-party dependency: You do not need external NuGet packages

  • Better performance: Optimized by Microsoft for high-speed APIs

  • Simple configuration: Easy to set up in Program.cs

  • Multiple strategies supported: Fixed window, sliding window, token bucket, concurrency limiter

  • Production-ready: Suitable for real-world scalable APIs

Using built-in rate limiting also helps improve API reliability, backend stability, and user experience.

Step 1: Create a New ASP.NET Core 10 Web API Project

First, create a new ASP.NET Core Web API project using the .NET CLI.

dotnet new webapi -n RateLimitingDemo
cd RateLimitingDemo

This command creates a ready-to-use API project with basic configuration.

Step 2: Add Rate Limiting Services

Now, we need to register rate limiting services in the dependency injection container.

Open Program.cs and add the following configuration:

using System.Threading.RateLimiting;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRateLimiter(options =>
{
    options.AddFixedWindowLimiter("fixed", opt =>
    {
        opt.PermitLimit = 5; // Maximum 5 requests
        opt.Window = TimeSpan.FromSeconds(10); // per 10 seconds
        opt.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
        opt.QueueLimit = 2;
    });
});

Explanation (in simple words)

  • PermitLimit = 5 → Only 5 requests are allowed

  • Window = 10 seconds → Time duration for those requests

  • QueueLimit = 2 → Extra requests will wait in queue (max 2)

  • OldestFirst → Older requests are processed first

This configuration is ideal for basic API rate limiting in ASP.NET Core 10.

Step 3: Enable Rate Limiting Middleware

After configuring services, you need to enable the rate limiting middleware in the HTTP pipeline.

var app = builder.Build();

app.UseRateLimiter();

app.MapGet("/", () => "Hello World!")
   .RequireRateLimiting("fixed");

app.Run();

Explanation

  • UseRateLimiter() activates rate limiting

  • RequireRateLimiting("fixed") applies the policy to the endpoint

Now your API endpoint is protected with rate limiting.

Step 4: Test Rate Limiting in ASP.NET Core API

Run your API:

dotnet run

Now send multiple requests using browser, Postman, or curl:

curl http://localhost:5000/

What will happen?

  • First 5 requests → Success

  • After that → API returns HTTP 429 (Too Many Requests)

This confirms that your ASP.NET Core 10 rate limiting implementation is working correctly.

Understanding Fixed Window Rate Limiting

Fixed window is the simplest rate limiting strategy.

How it works

  • Time is divided into fixed blocks (for example, 10 seconds)

  • Requests are counted inside that block

  • Once the limit is reached, further requests are rejected

  • After the window resets, requests are allowed again

Real-life example

Imagine a ticket counter:

  • Only 5 people are allowed every 10 minutes

  • Others must wait for the next time slot

This method is easy to implement and works well for simple API traffic control.

Other Built-in Rate Limiting Strategies in ASP.NET Core 10

ASP.NET Core 10 supports multiple advanced strategies. Let’s understand them in simple terms.

Sliding Window Rate Limiter

options.AddSlidingWindowLimiter("sliding", opt =>
{
    opt.PermitLimit = 10;
    opt.Window = TimeSpan.FromSeconds(10);
    opt.SegmentsPerWindow = 2;
});

Explanation

Sliding window divides time into smaller segments instead of fixed blocks.

  • More smooth control of traffic

  • Avoids sudden bursts at reset time

  • Better for real-time APIs

This is useful for high-traffic ASP.NET Core APIs.

Token Bucket Rate Limiter

options.AddTokenBucketLimiter("token", opt =>
{
    opt.TokenLimit = 10;
    opt.QueueLimit = 2;
    opt.ReplenishmentPeriod = TimeSpan.FromSeconds(5);
    opt.TokensPerPeriod = 5;
    opt.AutoReplenishment = true;
});

Explanation

Think of tokens like credits:

  • Each request consumes one token

  • Tokens are refilled over time

  • Allows short bursts of traffic

Best for:

  • APIs with variable traffic

  • Payment systems

  • Real-time services

Concurrency Limiter

options.AddConcurrencyLimiter("concurrent", opt =>
{
    opt.PermitLimit = 2;
    opt.QueueLimit = 2;
});

Explanation

This limiter controls how many requests can run at the same time.

  • Only 2 requests can execute simultaneously

  • Others wait or get rejected

Useful for:

  • CPU-heavy operations

  • Database-intensive APIs

Applying Rate Limiting Globally

If you want to apply rate limiting to all endpoints:

app.UseRateLimiter();

app.MapControllers().RequireRateLimiting("fixed");

This ensures global API protection in ASP.NET Core 10.

Customizing Rate Limit Response

You can customize the response when a request is rejected.

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

This improves user experience and API usability.

Best Practices for Rate Limiting in ASP.NET Core

To build a scalable and secure API, follow these best practices:

  • Use different rate limits for different endpoints

  • Apply stricter limits on sensitive APIs (login, payments)

  • Combine rate limiting with authentication and authorization

  • Monitor API usage and logs regularly

  • Avoid setting very low limits (can affect real users)

These practices help in building secure, scalable, and production-ready ASP.NET Core APIs.

Real-World Use Cases of Rate Limiting

Login API Protection

  • Limit login attempts (e.g., 5 per minute)

  • Prevent brute-force attacks

Public API Protection

  • Allow higher limits for authenticated users

  • Lower limits for anonymous users

Payment APIs

  • Prevent duplicate transactions

  • Control request bursts

These scenarios show how rate limiting improves API security and performance.

Summary

Rate limiting in ASP.NET Core 10 is a powerful built-in feature that helps you control API traffic, prevent abuse, and improve performance without using any third-party libraries. By using strategies like fixed window, sliding window, token bucket, and concurrency limiter, you can design a secure and scalable Web API. With proper configuration and best practices, you can ensure your ASP.NET Core API remains fast, reliable, and protected against excessive usage, making it suitable for real-world production environments.