rea-analysis-optimization
MOmorluto/rea485k近 7 天新增 9,215 个 star
Built-in ASP.NET Core 10 rate limiting: fixed/sliding window, token bucket, concurrency, per-user and per-IP partitions, strict login limits, 429 with Retry-After, multi-instance behaviour. Use for "rate limiting", "throttling", "429", "Retry-After", "AddRateLimiter", "brute force on login". Do NOT use for outbound retries (use resilience).
AddRateLimiter + UseRateLimiter ship in the shared framework (no package) and cover fixed window, sliding window, token bucket and concurrency limits. A hand-written counter in a filter misses partitions, queueing and metadata.api-hardening); without that, every request shares the load balancer's IP.RejectionStatusCode = 429 (the default is 503, which looks like an outage) and write Retry-After from the lease metadata so well-behaved clients back off.builder.Services.AddRateLimiter(options =>
{
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.OnRejected = async (context, ct) =>
{
if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter))
context.HttpContext.Response.Headers.RetryAfter =
((int)Math.Ceiling(retryAfter.TotalSeconds)).ToString(NumberFormatInfo.InvariantInfo);
await TypedResults.Problem(
statusCode: StatusCodes.Status429TooManyRequests,
title: "Too many requests.",
extensions: new Dictionary<string, object?> { ["code"] = "rate-limited" })
.ExecuteAsync(context.HttpContext);
};
// Every request: per user when signed in, per IP otherwise.
options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(http =>
RateLimitPartition.GetTokenBucketLimiter(RateLimitKeys.ForCaller(http), _ => new TokenBucketRateLimiterOptions
{
TokenLimit = 100,
TokensPerPeriod = 50,
ReplenishmentPeriod = TimeSpan.FromSeconds(10),
QueueLimit = 0,
}));
// Login and token endpoints: per IP, small fixed window.
options.AddPolicy(RateLimitPolicies.Auth, http =>
RateLimitPartition.GetFixedWindowLimiter(RateLimitKeys.ForIp(http), _ => new FixedWindowRateLimiterOptions
{
PermitLimit = 5,
Window = TimeSpan.FromMinutes(1),
QueueLimit = 0,
}));
// Expensive reports: at most two running at once per user.
options.AddPolicy(RateLimitPolicies.Reports, http =>
RateLimitPartition.GetConcurrencyLimiter(RateLimitKeys.ForCaller(http), _ => new ConcurrencyLimiterOptions
{
PermitLimit = 2,
QueueLimit = 0,
}));
});
public static class RateLimitPolicies
{
public const string Auth = "auth";
public const string Reports = "reports";
}
public static class RateLimitKeys
{
public static string ForCaller(HttpContext http) =>
http.User.FindFirstValue(ClaimTypes.NameIdentifier) is { } userId ? $"user:{userId}" : ForIp(http);
public static string ForIp(HttpContext http) =>
$"ip:{http.Connection.RemoteIpAddress?.ToString() ?? "unknown"}";
}
Partition keys from user input (an IP, a header, an API key) let an attacker create unlimited partitions. Keep QueueLimit = 0 for API traffic, so a rejected request fails fast instead of holding a connection.
internal sealed class LoginEndpoint : IEndpoint
{
public void Map(IEndpointRouteBuilder endpoints) =>
endpoints.MapPost("/login", (LoginRequest request, CancellationToken ct) => TypedResults.Ok())
.RequireRateLimiting(RateLimitPolicies.Auth)
.AllowAnonymous();
}
internal sealed class HealthEndpoint : IEndpoint
{
public void Map(IEndpointRouteBuilder endpoints) =>
endpoints.MapGet("/health/live", () => TypedResults.Ok())
.DisableRateLimiting() // probes must never be throttled
.AllowAnonymous();
}
public sealed record LoginRequest(string Email, string Password);
A group (MapGroup(...).RequireRateLimiting(...)) applies one policy to a whole module. An endpoint policy runs in addition to the GlobalLimiter.
app.UseForwardedHeaders(); // real client IP first
app.UseAuthentication(); // so partitions can read the user
app.UseAuthorization();
app.UseRateLimiter(); // endpoint policies need routing, which WebApplication adds implicitly
UseRateLimiter must come after routing when you use endpoint policies, and after authentication when partitions read HttpContext.User. Anonymous traffic still lands in the per-IP partition.
| Limiter | Behaviour | Use for |
|---|---|---|
| Fixed window | N requests per window, counter resets at the boundary | Login attempts, simple quotas |
| Sliding window | Window split into segments, smooths the boundary burst | Public APIs where a 2× burst at the boundary matters |
| Token bucket | Bucket refills at a steady rate, allows short bursts | General per-user API traffic |
| Concurrency | N requests in flight at once, no time window | Expensive endpoints (exports, reports, AI calls) |
builder.Services.AddRateLimiter(options => options.AddPolicy("public", http =>
RateLimitPartition.GetSlidingWindowLimiter(RateLimitKeys.ForIp(http), _ => new SlidingWindowRateLimiterOptions
{
PermitLimit = 60,
Window = TimeSpan.FromMinutes(1),
SegmentsPerWindow = 6,
QueueLimit = 0,
})));
AddFixedWindowLimiter, AddSlidingWindowLimiter, AddTokenBucketLimiter and AddConcurrencyLimiter create one shared bucket for the policy. Use AddPolicy with RateLimitPartition when the limit is per caller, which is almost always.
The middleware keeps counters in memory, per process. With three instances behind a round-robin load balancer:
Pick one of these deliberately:
limit_req, YARP) and keep the in-app limiter as a per-instance safety net.PartitionedRateLimiter<HttpContext> so the middleware and policies stay the same.Configure forwarded headers on every instance, or the per-IP partition sees only the load balancer.
// BAD — one noisy client uses up the limit for every user
options.AddFixedWindowLimiter("api", limiter => { limiter.PermitLimit = 1000; limiter.Window = TimeSpan.FromMinutes(1); });
// GOOD — partition per caller
options.AddPolicy("api", http => RateLimitPartition.GetFixedWindowLimiter(RateLimitKeys.ForCaller(http),
_ => new FixedWindowRateLimiterOptions { PermitLimit = 100, Window = TimeSpan.FromMinutes(1) }));
// BAD — clients see "service unavailable" and retry immediately
builder.Services.AddRateLimiter(options => options.AddPolicy("api", http => RateLimitPartition.GetNoLimiter("none")));
// GOOD — 429 plus Retry-After from the lease (see the registration pattern)
builder.Services.AddRateLimiter(options => options.RejectionStatusCode = StatusCodes.Status429TooManyRequests);
// BAD — 100 password guesses a minute per user is a brute-force allowance
endpoints.MapPost("/login", (LoginRequest request) => TypedResults.Ok()).RequireRateLimiting("api");
// GOOD — a dedicated, IP-partitioned policy
endpoints.MapPost("/login", (LoginRequest request) => TypedResults.Ok()).RequireRateLimiting(RateLimitPolicies.Auth);
// BAD — no forwarded headers: every client shares the load balancer's address and one bucket
app.UseRateLimiter();
// GOOD — real client IP first, then the limiter
app.UseForwardedHeaders();
app.UseRateLimiter();
| Scenario | Recommendation |
|---|---|
| General API traffic | GlobalLimiter with a per-caller token bucket |
| Login, token, password reset, sign-up | Fixed window, per IP, 5–10 per minute, RequireRateLimiting("auth") |
| Expensive endpoint (export, report, LLM call) | Concurrency limiter per user |
| Public anonymous API | Sliding window per IP |
| Health and readiness probes | .DisableRateLimiting() |
| Rejected request | 429, Retry-After, ProblemDetails with code: rate-limited |
| Several instances, approximate limits are fine | Divide limits by instance count |
| Several instances, the limit is a contract | Gateway limit, or a Redis-backed PartitionedRateLimiter |
| Behind a proxy | Forwarded headers before UseRateLimiter (api-hardening) |
| Retrying calls to other services | Use the resilience skill |
MOmorluto/rea485k近 7 天新增 9,215 个 star
MAmattpocock/skills336k近 7 天新增 5,004 个 star
MAmattpocock/skills336k近 7 天新增 5,004 个 star
MAmattpocock/skills336k近 7 天新增 5,004 个 star
MAmattpocock/skills336k近 7 天新增 5,004 个 star