Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

rate-limiting

БесплатноБез исполняемых скриптовНе проверен

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…

codewithmukeshот codewithmukesh★ 858 звёзд на GitHub

Об этом скилле

Rate Limiting

Core Principles

  1. Use the built-in middleware. 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.
  2. Partition by who is calling. One shared bucket lets a single client lock everyone out. Partition by user ID when signed in and by client IP otherwise. The IP is only real after forwarded headers are configured (api-hardening); without that, every request shares the load balancer's IP.
  3. Auth endpoints get the strictest limit. Login, token, password reset and sign-up are where brute force and credential stuffing land. Give them a small, IP-partitioned policy separate from the general API limit.
  4. Reject with 429 and tell the client when to retry. Set 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.
  5. The limiter is per instance. Counters live in each process's memory, so three instances allow three times the limit. Plan for that, or enforce the hard limit at the gateway.

Patterns

Registration with a global limit, named policies and a 429 response

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.

Applying policies to endpoints

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.

Pipeline order

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

Полный SKILL.md на GitHub

Установить rate-limiting в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл rate-limiting?

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).

Как установить скилл rate-limiting?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл rate-limiting запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить rate-limiting с