---
title: "How to Implement Rate Limiting in .NET Core API"  
description: "In modern web applications, APIs are constantly exposed to high traffic, bots, and malicious requests. Without protection, excessive requests can overload your"  
author: "Ravi Vishwakarma"  
published: 2026-05-12  
updated: 2026-05-12  
canonical: https://answers.mindstick.com/blog/289/how-to-implement-rate-limiting-in-dot-net-core-api  
category: "database"  
tags: ["database", "sql server", ".net programming"]  
reading_time: 5 minutes  

---

# How to Implement Rate Limiting in .NET Core API

In modern [web applications](https://www.mindstick.com/blog/11464/improve-your-understanding-of-web-applications), APIs are constantly exposed to high traffic, bots, and malicious requests. Without protection, excessive requests can overload your server and degrade [application](https://www.mindstick.com/blog/59/xaml-extensible-application-markup-language) performance.

This is where **Rate Limiting** becomes essential.

Rate limiting controls how many requests a client can make within a specified time window. It protects APIs from abuse, improves reliability, and ensures fair usage among users.

## What is Rate Limiting?

Rate limiting restricts the number of API requests a client can make during a fixed time period.

Example:

```plaintext
100 requests per minute
```

If the client exceeds the limit, the API returns:

```plaintext
HTTP 429 - Too Many Requests
```

## Why Use Rate Limiting?

Rate limiting provides several benefits:

- Prevents API abuse
- Protects against DDoS attacks
- Reduces server load
- Improves API stability
- Ensures fair resource usage
- Controls traffic spikes

![How to Implement Rate Limiting in .NET Core API](https://answers.mindstick.com/blogs/adfcd354-2044-4ac5-a479-67af81546711/images/8e82772b-c95e-43bd-9096-14b22314fef4.png)

## Types of Rate Limiting

## 1. Fixed Window

Limits requests within a fixed time interval.

Example:

```plaintext
100 requests per minute
```

Simple and commonly used.

## 2. Sliding Window

Tracks requests dynamically over time for smoother limiting.

## 3. Token Bucket

Clients consume tokens for requests. Tokens refill over time.

Useful for burst traffic handling.

## 4. Concurrency Limiting

Limits how many requests can run simultaneously.

## Prerequisites

Before starting, ensure you have:

- .NET 7 or later installed
- [ASP.NET Core](https://www.mindstick.com/articles/326150/asp-dot-net-core-why-it-is-best-suited-for-banking-and-finance-sectors) [Web API](https://www.mindstick.com/articles/324352/how-to-create-web-api-in-dot-net-core-3-1-mvc) project
- Basic knowledge of middleware

![How to Implement Rate Limiting in .NET Core API](https://answers.mindstick.com/blogs/adfcd354-2044-4ac5-a479-67af81546711/images/6ef7c475-7bb6-46d2-98ea-b8d309b3cd49.png)

## Create a .NET Core Web API

Run the following command:

```cs
dotnet new webapi -n RateLimitDemo
```

Navigate to the project:

```cs
cd RateLimitDemo
```

## Built-in Rate Limiting in ASP.NET Core

Starting from .NET 7, ASP.NET Core provides built-in rate limiting middleware.

Namespace used:

```cs
using System.Threading.RateLimiting;
```

## Step 1: Configure Rate Limiting

Open `Program.cs`.

Add the following code:

```cs
using System.Threading.RateLimiting;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

builder.Services.AddRateLimiter(options =>
{
    options.AddFixedWindowLimiter("fixed", config =>
    {
        config.PermitLimit = 5;
        config.Window = TimeSpan.FromSeconds(10);
        config.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
        config.QueueLimit = 2;
    });
});

var app = builder.Build();

app.UseRateLimiter();

app.MapControllers();

app.Run();
```

## Understanding the Configuration

## PermitLimit

```cs
config.PermitLimit = 5;
```

Allows only 5 requests.

## Window

```cs
config.Window = TimeSpan.FromSeconds(10);
```

Within a 10-second window.

## QueueLimit

```cs
config.QueueLimit = 2;
```

Extra requests wait in queue.

## QueueProcessingOrder

```cs
QueueProcessingOrder.OldestFirst
```

Processes oldest queued requests first.

## Step 2: Apply Rate Limiting to Controller

Create a controller:

```cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;

namespace RateLimitDemo.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    [EnableRateLimiting("fixed")]
    public class TestController : ControllerBase
    {
        [HttpGet]
        public IActionResult Get()
        {
            return Ok("Request Successful");
        }
    }
}
```

## Step 3: Run the API

Start the application:

```plaintext
dotnet run
```

Test endpoint:

```plaintext
GET /api/test
```

After 5 requests within 10 seconds, you’ll receive:

```plaintext
429 Too Many Requests
```

## Global Rate Limiting

Instead of applying per controller, you can apply globally.

Update middleware:

```plaintext
app.UseRateLimiter();
```

And map endpoints with policy.

## Sliding Window Example

You can also use [sliding window](https://www.mindstick.com/forum/742/sql-keeping-count-of-occurrences-through-a-sliding-window) rate limiting.

Example:

```cs
builder.Services.AddRateLimiter(options =>
{
    options.AddSlidingWindowLimiter("sliding", config =>
    {
        config.PermitLimit = 10;
        config.Window = TimeSpan.FromMinutes(1);
        config.SegmentsPerWindow = 6;
    });
});
```

This provides smoother request tracking.

## Token Bucket Example

Useful for burst traffic.

```cs
builder.Services.AddRateLimiter(options =>
{
    options.AddTokenBucketLimiter("token", config =>
    {
        config.TokenLimit = 10;
        config.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
        config.QueueLimit = 5;
        config.ReplenishmentPeriod = TimeSpan.FromSeconds(10);
        config.TokensPerPeriod = 5;
        config.AutoReplenishment = true;
    });
});
```

## Custom Response for Rate Limit Exceeded

You can customize the response when the limit is exceeded.

```cs
builder.Services.AddRateLimiter(options =>
{
    options.OnRejected = async (context, token) =>
    {
        context.HttpContext.Response.StatusCode = 429;

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

## Best Practices

## Use Different Policies

Different endpoints may need different limits.

Example:

- Login API → Strict limits
- Public APIs → Moderate limits
- Internal APIs → Relaxed limits

## Combine with Authentication

Rate limit based on:

- IP Address
- User ID
- API Key

## Monitor API Usage

Track:

- Rejected requests
- Traffic spikes
- Abuse patterns

Use tools like:

- Prometheus
- Grafana
- Application Insights

## Common Challenges

## Distributed Systems

In multiple server environments, in-memory rate limiting may fail.

Solution:

- Redis-based [distributed caching](https://www.mindstick.com/forum/161411/why-use-distributed-caching-instead-of-local-caching)
- API Gateway rate limiting

## Choosing Correct Limits

- Too strict → blocks real users\ Too loose → ineffective protection

## Rate Limiting with API Gateway

Many organizations implement rate limiting at the API Gateway level using:

- Kong
- NGINX
- YARP
- Azure API Management
- This centralizes [traffic management](https://yourviews.mindstick.com/view/52/strict-traffic-management-system-is-the-demand-of-the-hour) across all APIs.

## Conclusion

Rate limiting is a critical feature for securing and stabilizing APIs. ASP.NET Core makes [implementation](https://www.mindstick.com/interview/733/what-is-implementation-and-interface-inheritance) simple with built-in middleware introduced in .NET 7.

By applying proper rate limiting strategies, you can:

- Protect backend systems
- Prevent abuse
- [Improve performance](https://www.mindstick.com/forum/158717/how-can-you-optimize-database-queries-and-improve-performance-in-asp-dot-net-mvc)
- Ensure fair API usage

Whether you’re building small APIs or enterprise-scale [microservices](https://www.mindstick.com/articles/337598/define-the-importance-of-microservices-in-modern-software-architecture), implementing rate limiting should always be part of your API security strategy.

## Final Thoughts

Modern APIs must be resilient, secure, and scalable. Rate limiting is one of the easiest yet most powerful ways to achieve that.

With ASP.NET Core’s built-in support, developers can implement production-ready rate limiting with minimal code while maintaining flexibility and performance.

---

Original Source: https://answers.mindstick.com/blog/289/how-to-implement-rate-limiting-in-dot-net-core-api

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
