Skip to content

Commit 98ad6f2

Browse files
Rick's branch off Sams rate limit PR (#34926)
* Fix typo in UID for rate limit samples * edits * edits * edits
1 parent 08fd945 commit 98ad6f2

2 files changed

Lines changed: 89 additions & 85 deletions

File tree

aspnetcore/performance/rate-limit-samples.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,12 @@ monikerRange: '>= aspnetcore-7.0'
66
description: Samples for using ASP.NET rate limitng middleware
77
ms.custom: mvc
88
ms.date: 03/05/2025
9-
uid: performance/rate-limit
9+
uid: performance/rate-limit-sample
1010
---
1111

1212
# Rate limiter samples
1313

14-
The following samples aren't meant for production code but are examples on how to use the limiters.
14+
The following samples aren't production quality, they're examples on how to use the limiters.
1515

1616
### Limiter with `OnRejected`, `RetryAfter`, and `GlobalLimiter`
1717

aspnetcore/performance/rate-limit.md

Lines changed: 87 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -19,22 +19,22 @@ The `Microsoft.AspNetCore.RateLimiting` middleware provides rate limiting middle
1919

2020
For an introduction to rate limiting, see [Rate limiting middleware](https://blog.maartenballiauw.be/post/2022/09/26/aspnet-core-rate-limiting-middleware.html).
2121

22-
## Why use rate limiting?
22+
## Why use rate limiting
2323

24-
Rate limiting can be used for managing the flow of incoming requests to your application. Here are some key reasons to implement rate limiting:
24+
Rate limiting can be used for managing the flow of incoming requests to an app. Key reasons to implement rate limiting:
2525

26-
- **Preventing Abuse**: Rate limiting helps protect your application from abuse by limiting the number of requests a user or client can make in a given time period. This is particularly important for public APIs.
27-
- **Ensuring Fair Usage**: By setting limits, you can ensure that all users have fair access to your resources, preventing any single user from monopolizing the system.
28-
- **Protecting Resources**: Rate limiting helps prevent server overload by controlling the number of requests that can be processed, thus protecting your backend resources from being overwhelmed.
29-
- **Enhancing Security**: It can mitigate the risk of Denial of Service (DoS) attacks by limiting the rate at which requests are processed, making it harder for attackers to flood your system.
30-
- **Improving Performance**: By controlling the rate of incoming requests, you can maintain optimal performance and responsiveness of your application, ensuring a better user experience.
26+
- **Preventing Abuse**: Rate limiting helps protect an app from abuse by limiting the number of requests a user or client can make in a given time period. This is particularly important for public APIs.
27+
- **Ensuring Fair Usage**: By setting limits, all users have fair access to resources, preventing users from monopolizing the system.
28+
- **Protecting Resources**: Rate limiting helps prevent server overload by controlling the number of requests that can be processed, thus protecting the backend resources from being overwhelmed.
29+
- **Enhancing Security**: It can mitigate the risk of Denial of Service (DoS) attacks by limiting the rate at which requests are processed, making it harder for attackers to flood a system.
30+
- **Improving Performance**: By controlling the rate of incoming requests, optimal performance and responsiveness of an app can be maintained, ensuring a better user experience.
3131
- **Cost Management**: For services that incur costs based on usage, rate limiting can help manage and predict expenses by controlling the volume of requests processed.
3232

33-
Implementing rate limiting in your ASP.NET Core application can help maintain stability, security, and performance, ensuring a reliable and efficient service for all users.
33+
Implementing rate limiting in an ASP.NET Core app can help maintain stability, security, and performance, ensuring a reliable and efficient service for all users.
3434

3535
## Preventing DDoS Attacks
3636

37-
While rate limiting can help mitigate the risk of Denial of Service (DoS) attacks by limiting the rate at which requests are processed, it is not a comprehensive solution for Distributed Denial of Service (DDoS) attacks. DDoS attacks involve multiple systems overwhelming your application with a flood of requests, making it difficult to handle with rate limiting alone.
37+
While rate limiting can help mitigate the risk of Denial of Service (DoS) attacks by limiting the rate at which requests are processed, it's not a comprehensive solution for Distributed Denial of Service (DDoS) attacks. DDoS attacks involve multiple systems overwhelming an app with a flood of requests, making it difficult to handle with rate limiting alone.
3838

3939
For robust DDoS protection, consider using a commercial DDoS protection service. These services offer advanced features such as:
4040

@@ -44,75 +44,79 @@ For robust DDoS protection, consider using a commercial DDoS protection service.
4444
- **Global Network**: A global network of servers to absorb and mitigate attacks closer to the source.
4545
- **Constant Updates**: Commercial services continuously track and update their protection mechanisms to adapt to new and evolving threats.
4646

47-
If using a cloud hosting service, then DDoS protection is usually available as part of the hosting solution, such as [Azure Web Application Firewall](https://azure.microsoft.com/en-us/products/web-application-firewall/), [AWS Shield](https://aws.amazon.com/shield/) or [Google Cloud Armor](https://cloud.google.com/armor/docs). Dedicated protections is available as Web Application Firewalls (WAF) or as part of a CDN solution such as - [Cloudflare](https://www.cloudflare.com/ddos/) or [Akamai Kona Site Defender](https://www.akamai.com/us/en/products/security/kona-site-defender.jsp)
48-
49-
Implementing a commercial DDoS protection service in conjunction with rate limiting can provide a comprehensive defense strategy, ensuring the stability, security, and performance of your application.
50-
51-
## Using Rate Limiting Middleware
52-
53-
To use the rate limiting middleware in your ASP.NET Core application, follow these steps:
54-
55-
### 1. Install the necessary package:
56-
Add the `Microsoft.AspNetCore.RateLimiting` package to your project. You can do this via the NuGet Package Manager or by running the following command in the terminal:
57-
```sh
58-
dotnet add package Microsoft.AspNetCore.RateLimiting
59-
```
60-
61-
### 2. Configure rate limiting services
62-
In the Program.cs file, configure the rate limiting services by adding the appropriate rate limiting policies. Policies can either be defined as global, for example the following which permits 10 requests per minute:
63-
64-
``` csharp
65-
builder.Services.AddRateLimiter(options =>
66-
{
67-
options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(httpContext =>
68-
RateLimitPartition.GetFixedWindowLimiter(
69-
partitionKey: httpContext.User.Identity?.Name ?? httpContext.Request.Headers.Host.ToString(),
70-
factory: partition => new FixedWindowRateLimiterOptions
71-
{
72-
AutoReplenishment = true,
73-
PermitLimit = 10,
74-
QueueLimit = 0,
75-
Window = TimeSpan.FromMinutes(1)
76-
}));
77-
});
78-
```
79-
80-
Or as named polices, which need to be explicitly applied to the pages or endpoints. For example, to add a fixed window limiter:
81-
82-
``` csharp
83-
var builder = WebApplication.CreateBuilder(args);
84-
85-
builder.Services.AddRateLimiter(options =>
86-
{
87-
options.AddFixedWindowLimiter("fixed", opt =>
88-
{
89-
opt.PermitLimit = 4;
90-
opt.Window = TimeSpan.FromSeconds(12);
91-
opt.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
92-
opt.QueueLimit = 2;
93-
});
94-
});
95-
96-
var app = builder.Build();
97-
```
98-
99-
The global limiter applies to all endpoints automatically when it's configured via options.GlobalLimiter, and no endpoint-specific policy is specified.
100-
101-
### 3. Enable rate limiting middleware
102-
In the Program.cs file, enable the rate limiting middleware by calling UseRateLimiter:
103-
104-
``` csharp
105-
app.UseRouting();
106-
107-
app.UseRateLimiter();
108-
109-
app.UseEndpoints(endpoints =>
110-
{
111-
endpoints.MapControllers();
112-
});
113-
114-
app.Run();
115-
```
47+
When using a cloud hosting service, DDoS protection is usually available as part of the hosting solution, such as [Azure Web Application Firewall](https://azure.microsoft.com/products/web-application-firewall/), [AWS Shield](https://aws.amazon.com/shield/) or [Google Cloud Armor](https://cloud.google.com/armor/docs). Dedicated protections are available as Web Application Firewalls (WAF) or as part of a CDN solution such as [Cloudflare](https://www.cloudflare.com/ddos/) or [Akamai Kona Site Defender](https://www.akamai.com/us/en/products/security/kona-site-defender.jsp)
48+
49+
Implementing a commercial DDoS protection service in conjunction with rate limiting can provide a comprehensive defense strategy, ensuring the stability, security, and performance of an app.
50+
51+
## Use Rate Limiting Middleware
52+
53+
The following steps show how to use the rate limiting middleware in an ASP.NET Core app:
54+
55+
1. Install the `Microsoft.AspNetCore.RateLimiting` package.:
56+
57+
Add the `Microsoft.AspNetCore.RateLimiting` package to the project, via the NuGet Package Manager or the following command:
58+
59+
```sh
60+
dotnet add package Microsoft.AspNetCore.RateLimiting
61+
```
62+
63+
2. Configure rate limiting services.
64+
65+
In the `Program.cs` file, configure the rate limiting services by adding the appropriate rate limiting policies. Policies can either be defined as global or named polices. The following example permits 10 requests per minute:
66+
67+
``` csharp
68+
builder.Services.AddRateLimiter(options =>
69+
{
70+
options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(httpContext =>
71+
RateLimitPartition.GetFixedWindowLimiter(
72+
partitionKey: httpContext.User.Identity?.Name ?? httpContext.Request.Headers.Host. ToString(),
73+
factory: partition => new FixedWindowRateLimiterOptions
74+
{
75+
AutoReplenishment = true,
76+
PermitLimit = 10,
77+
QueueLimit = 0,
78+
Window = TimeSpan.FromMinutes(1)
79+
}));
80+
});
81+
```
82+
83+
Named polices need to be explicitly applied to the pages or endpoints. The following example adds a fixed window limiter:
84+
85+
``` csharp
86+
var builder = WebApplication.CreateBuilder(args);
87+
88+
builder.Services.AddRateLimiter(options =>
89+
{
90+
options.AddFixedWindowLimiter("fixed", opt =>
91+
{
92+
opt.PermitLimit = 4;
93+
opt.Window = TimeSpan.FromSeconds(12);
94+
opt.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
95+
opt.QueueLimit = 2;
96+
});
97+
});
98+
99+
var app = builder.Build();
100+
```
101+
102+
The global limiter applies to all endpoints automatically when it's configured via [options. GlobalLimiter](/dotnet/api/microsoft.aspnetcore.ratelimiting.ratelimiteroptions.globallimiter), and no endpoint-specific policy is specified.
103+
104+
3. Enable rate limiting middleware
105+
106+
In the `Program.cs` file, enable the rate limiting middleware by calling [UseRateLimiter](/dotnet/api/microsoft.aspnetcore.builder.ratelimiterapplicationbuilderextensions.useratelimiter):
107+
108+
``` csharp
109+
app.UseRouting();
110+
111+
app.UseRateLimiter();
112+
113+
app.UseEndpoints(endpoints =>
114+
{
115+
endpoints.MapControllers();
116+
});
117+
118+
app.Run();
119+
```
116120

117121
### Apply rate limiting policies to endpoints or pages
118122

@@ -141,7 +145,7 @@ app.UseEndpoints(endpoints =>
141145

142146
#### Apply rate limiting to Blazor Server Pages
143147

144-
To set rate limiting to all pages, `RequireRateLimiting(Policy)` can be specified on the MapRazorComponents call, for example:
148+
To set rate limiting to all pages, [`RequireRateLimiting(Policy)`](/dotnet/api/microsoft.aspnetcore.builder.ratelimiterendpointconventionbuilderextensions.requireratelimiting) can be specified on the MapRazorComponents call, for example:
145149

146150
``` csharp
147151
app.MapRazorComponents<App>()
@@ -159,7 +163,7 @@ To set policy for individual Blazor Pages, the attribute must be applied to the
159163
<h1>Counter</h1>
160164
```
161165

162-
The `DisableRateLimiting` attribute can be used to disable rate limiting on a Razor Page.
166+
The [`DisableRateLimiting`](/dotnet/api/microsoft.aspnetcore.ratelimiting.disableratelimitingattribute) attribute can be used to disable rate limiting on a Razor Page.
163167

164168
Note: `EnableRateLimiting` is only applied to a Razor Page if `MapBlazorComponents().RequireRateLimiting(Policy)` has ***not*** been called.
165169

@@ -280,9 +284,9 @@ The following code uses the concurrency limiter:
280284

281285
:::code language="csharp" source="~/../AspNetCore.Docs.Samples/fundamentals/middleware/rate-limit/WebRateLimitAuth/Program.cs" id="snippet_concur":::
282286

283-
284287
## Rate Limiting Partitions
285-
Rate limiting partitions divide your traffic into separate "buckets" that each get their own rate limit counters. This allows for more granular control than a single global counter. The partition "buckets" are defined by different keys (like user ID, IP address, or API key).
288+
289+
Rate limiting partitions divide the traffic into separate "buckets" that each get their own rate limit counters. This allows for more granular control than a single global counter. The partition "buckets" are defined by different keys (like user ID, IP address, or API key).
286290

287291
### Benefits of Partitioning
288292
- **Fairness**: One user can't consume the entire rate limit for everyone
@@ -469,7 +473,7 @@ In the preceding controller:
469473

470474
## Rate limiting metrics
471475

472-
The rate limiting middleware provides built-in metrics and monitoring capabilities to help you understand how rate limits are affecting your application performance and user experience. The following metrics are provided for rate limiting:
476+
The rate limiting middleware provides built-in metrics and monitoring capabilities to help understand how rate limits are affecting app performance and user experience. The following metrics are provided for rate limiting
473477

474478
| Metric | Description | Type |
475479
| --- | --- | --- |

0 commit comments

Comments
 (0)