---
title: "Implementing Rate Limiting in ASP.NET APIs"  
description: "Rate limiting is a critical part of building secure, scalable, and reliable APIs. Without it, your API is vulnerable to abuse such as brute-force attacks, denia"  
author: "Anubhav Sharma"  
published: 2026-01-15  
updated: 2026-01-16  
canonical: https://answers.mindstick.com/blog/27/implementing-rate-limiting-in-asp-dot-net-apis  
category: "application"  
tags: ["api"]  
reading_time: 3 minutes  

---

# Implementing Rate Limiting in ASP.NET APIs

Rate limiting is a critical part of building **secure, scalable, and reliable APIs**. Without it, your API is vulnerable to abuse such as[brute-force attacks](https://www.mindstick.com/interview/34229/how-do-you-protect-against-brute-force-login-attempts), [denial-of-service (DoS)](https://www.mindstick.com/forum/158541/how-does-a-distributed-denial-of-service-ddos-attack-work-and-what-are-the-countermeasures), and excessive resource consumption.

This blog explains **what rate limiting is**, **why it matters**, and**how to implement it in ASP.NET**, covering both [**ASP.NET Core**](https://www.mindstick.com/category/article/asp-dot-net-core) and **classic** [**ASP.NET Web API (MVC 5)**](https://www.mindstick.com/articles/178071/what-is-asp-dot-net-mvc-5-new-features-in-asp-dot-net-mvc-5).

## What Is Rate Limiting?

Rate limiting restricts how many requests a client can make to an API within a specific time window.

Examples:

- 100 requests per minute per IP
- 10 login attempts per minute per user
- 2,000 emails per day per account

When the limit is exceeded, the server returns **HTTP 429 – Too Many Requests**.

## Why Rate Limiting Is Important

Rate limiting helps you:

- Prevent [brute-force](https://www.mindstick.com/interview/34229/how-do-you-protect-against-brute-force-login-attempts) and credential-stuffing attacks
- Protect server resources and database connections
- Ensure fair usage across users
- Improve system stability under heavy load

In production systems, rate limiting is considered a **baseline security feature**, not an optional enhancement.

## Rate Limiting in ASP.NET Core (.NET 7+)

ASP.NET Core provides **built-in rate limiting middleware**, making [implementation](https://www.mindstick.com/interview/733/what-is-implementation-and-interface-inheritance) clean and efficient.

### Step 1: Configure Rate Limiting

Add the following configuration in `Program.cs`:

```cs
using System.Threading.RateLimiting;builder.Services.AddRateLimiter(options =>{    options.AddFixedWindowLimiter("fixed", opt =>    {        opt.Window = TimeSpan.FromMinutes(1);        opt.PermitLimit = 100;        opt.QueueLimit = 0;    });    options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;});
```

### Step 2: Enable Middleware

```cs
app.UseRateLimiter();
```

### Step 3: Apply Rate Limit to an API

```cs
[EnableRateLimiting("fixed")][ApiController][Route("api/sample")]public class SampleController : ControllerBase{    [HttpGet]    public IActionResult Get() => Ok("Request successful");}
```

This configuration allows **100 requests per minute per client**.

## Per-IP Rate Limiting

To limit requests based on client IP:

```cs
options.AddPolicy("ip-policy", context =>{    var ip = context.Connection.RemoteIpAddress?.ToString() ?? "unknown";    return RateLimitPartition.GetFixedWindowLimiter(        ip,        _ => new FixedWindowRateLimiterOptions        {            PermitLimit = 50,            Window = TimeSpan.FromMinutes(1)        });});
```

Apply it using:

```cs
[EnableRateLimiting("ip-policy")]
```

## Rate Limiting in ASP.NET MVC 5 / Web API 2

Classic ASP.NET does not include built-in rate limiting. The recommended approach is to use a**custom [action filter](https://www.mindstick.com/blog/11275/action-filter-in-asp-dot-net-mvc)**.

### Custom Rate Limit Attribute

```cs
public class RateLimitAttribute : ActionFilterAttribute{    private static readonly MemoryCache Cache = MemoryCache.Default;    private readonly int _limit;    private readonly int _seconds;    public RateLimitAttribute(int limit, int seconds)    {        _limit = limit;        _seconds = seconds;    }    public override void OnActionExecuting(HttpActionContext actionContext)    {        var ip = actionContext.Request.GetOwinContext()?.Request?.RemoteIpAddress ?? "unknown";        var count = (int?)Cache.Get(ip) ?? 0;        if (count >= _limit)        {            actionContext.Response = actionContext.Request                .CreateResponse((HttpStatusCode)429, "Too many requests");            return;        }        Cache.Set(ip, count + 1, DateTimeOffset.Now.AddSeconds(_seconds));    }}
```

### Apply Rate Limit

```plaintext
[RateLimit(100, 60)]public IHttpActionResult Get(){    return Ok("Success");}
```

This allows **100 requests per minute per IP**.

## Distributed Rate Limiting (Production Scenario)

In load-balanced environments, in-memory cache is not enough.

### Recommended Solution: Redis

- Store counters in [Redis](https://www.mindstick.com/interview/34023/how-do-you-implement-caching-in-dot-net-e-g-memorycache-distributedcache-redis)
- Use [TTL](https://www.mindstick.com/interview/34116/how-do-you-implement-a-file-based-cache-system) to define the rate window
- Share limits across all servers

Example Redis key:

```plaintext
ratelimit:192.168.1.10:/api/loginTTL: 60 seconds
```

This approach ensures consistency across multiple application instances.

## HTTP Headers for Rate Limit Transparency

Best practice is to return rate limit details in headers:

```plaintext
X-RateLimit-Limit: 100X-RateLimit-Remaining: 20Retry-After: 60
```

These headers help API consumers handle throttling gracefully.

## Common Rate Limiting Use Cases

- Login & OTP verification
- Password reset APIs
- Bulk email or SMS sending
- Public APIs and partner integrations

## Conclusion

Rate limiting is essential for building **secure and scalable ASP.NET APIs**. Modern ASP.NET Core applications should leverage the**built-in rate limiter**, while legacy MVC 5 applications can rely on**custom filters or Redis-backed solutions**.

A well-designed rate limiting strategy protects your [infrastructure](https://www.mindstick.com/news/2313/a-cybersecurity-and-infrastructure-security-agency-will-monitor-the-us-midterm-elections), improves reliability, and ensures fair API usage for everyone.

---

Original Source: https://answers.mindstick.com/blog/27/implementing-rate-limiting-in-asp-dot-net-apis

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
