Orchardcore rate limits

From CrestApps/CrestApps.AgentSkills · View interactive version

Orchardcore rate limits is an AI agent skill from the GitHub repository CrestApps/CrestApps.AgentSkills. Skill for the Orchard Core 4.0 Rate Limits module. Covers tenant rate-limit policies with Global, Endpoint and Group targets, fixed window, sliding window, concurrency and token bucket limiters, the seeded default global policy, the CreateOrUpdateRateLimitPolicies recipe step, deployment, built-in r

How to use this skill

Skill file

Orchard Core Rate Limits - Prompt Templates

Throttle Tenant Requests

You are an Orchard Core expert. Generate rate-limit policies, recipes, and module code for the OrchardCore.RateLimits module, which ships with Orchard Core 4.0.

Guidelines

Enabling Rate Limits

{
  "steps": [
    {
      "name": "feature",
      "enable": [
        "OrchardCore.RateLimits"
      ]
    }
  ]
}

Policy Targets

| Target | Matches | Required property |

|---|---|---|

| Global | Every dynamic tenant request | none |

| Endpoint | Requests whose path starts with Path (for example /api matches /api/orders/42) | Path, must start with / |

| Group | Endpoints tagged with a rate-limit group | GroupName |

Limiter Sources

| Source | Data property | Settings | Use for |

|---|---|---|---|

| FixedWindow | FixedWindowRateLimiterData | PermitLimit, WindowSeconds, QueueLimit | Simple "X requests every Y seconds" caps |

| SlidingWindow | SlidingWindowRateLimiterData | PermitLimit, WindowSeconds, SegmentsPerWindow, QueueLimit | Smoother caps without window-boundary bursts |

| Concurrency | ConcurrencyRateLimiterData | PermitLimit, QueueLimit, QueueProcessingOrder | Limiting expensive in-flight work |

| TokenBucket | TokenBucketRateLimiterData | TokenLimit, TokensPerPeriod, ReplenishmentPeriodSeconds, QueueLimit, QueueProcessingOrder | Burst-tolerant APIs with a steady refill |

Use a QueueLimit of 0 to reject excess requests immediately instead of queuing them.

Recipe Step

CreateOrUpdateRateLimitPolicies imports a policies array. Existing policies are matched by PolicyId or by Name (case-insensitive) and updated; others are created.

{
  "steps": [
    {
      "name": "feature",
      "enable": [ "OrchardCore.RateLimits" ]
    },
    {
      "name": "CreateOrUpdateRateLimitPolicies",
      "policies": [
        {
          "Name": "Protect login",
          "Description": "Slows down credential stuffing.",
          "IsEnabled": true,
          "Scope": "Endpoint",
          "Path": "/Login",
          "Limiters": [
            {
              "Id": "[js: uuid()]",
              "Source": "SlidingWindow",
              "Properties": {
                "SlidingWindowRateLimiterData": {
                  "PermitLimit": 10,
                  "WindowSeconds": 60,
                  "SegmentsPerWindow": 6,
                  "QueueLimit": 0
                }
              }
            }
          ]
        },
        {
          "Name": "Public API",
          "IsEnabled": true,
          "Scope": "Endpoint",
          "Path": "/api",
          "Limiters": [
            {
              "Id": "[js: uuid()]",
              "Source": "TokenBucket",
              "Properties": {
                "TokenBucketRateLimiterData": {
                  "TokenLimit": 20,
                  "TokensPerPeriod": 5,
                  "ReplenishmentPeriodSeconds": 10,
                  "QueueLimit": 0
                }
              }
            }
          ]
        },
        {
          "Name": "Authentication group",
          "IsEnabled": false,
          "Scope": "Group",
          "GroupName": "authentication",
          "Limiters": [
            {
              "Id": "[js: uuid()]",
              "Source": "FixedWindow",
              "Properties": {
                "FixedWindowRateLimiterData": {
                  "PermitLimit": 20,
                  "WindowSeconds": 300,
                  "QueueLimit": 0
                }
              }
            }
          ]
        }
      ]
    }
  ]
}

Add All Rate Limit Policies to a deployment plan to export every stored policy. Setup-style exports stamp OwnerId and Author with the tenant admin parameters.

Tagging Endpoints with a Rate-Limit Group

Group policies target endpoint metadata instead of paths. The metadata is harmless when no enabled policy targets the group, so add it freely.

using Microsoft.AspNetCore.Mvc;
using OrchardCore.RateLimits;

namespace MyModule.Controllers;

public sealed class PartnerController : Controller
{
    [HttpPost]
    [RateLimitGroup("authentication", "public-api")]
    public IActionResult Exchange()
    {
        return Ok();
    }
}
routes.MapPost("/api/partner/token", HandleTokenAsync)
    .WithName("Partner.Token")
    .WithRateLimitGroups("authentication", "public-api");

Use WithRateLimitGroup("name") for a single group. The attribute and extensions live in OrchardCore.RateLimits.Core.

Registering Built-In Limits from a Module

Register limits only when the Rate Limits feature is enabled. Route limits match the endpoint route name and, optionally, the HTTP method, so GET and POST actions sharing a route name do not share a budget.

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using OrchardCore.Modules;
using OrchardCore.RateLimits;

namespace MyModule;

[RequireFeatures("OrchardCore.RateLimits")]
public sealed class RateLimitsStartup : StartupBase
{
    public override void ConfigureServices(IServiceCollection services)
    {
        services.Configure<RateLimitsOptions>(options =>
        {
            options.AddRouteRateLimit(
                routeName: "Partner.Token",
                httpMethod: HttpMethods.Post,
                partitioner: RateLimitPartitionHelpers.CreateSlidingWindowPerIpPolicy(
                    policyName: "partner-token",
                    permitLimit: 10));

            options.AddRouteRateLimit(
                routeName: "PartnerSignup",
                httpMethod: HttpMethods.Post,
                partitioner: RateLimitPartitionHelpers.CreateFixedWindowPerIpPolicy(
                    policyName: "partner-signup",
                    permitLimit: 3,
                    window: TimeSpan.FromMinutes(1)));

            options.AddGroupRateLimit(
                groupName: "public-api",
                partitioner: RateLimitPartitionHelpers.CreateSlidingWindowPerIpPolicy(
                    policyName: "public-api",
                    permitLimit: 60));
        });
    }
}
services.Configure<RateLimitsOptions>(options =>
{
    options.AddRouteRateLimit(
        routeName: "ExportReport",
        httpMethod: HttpMethods.Post,
        partitioner: RateLimitPartitionHelpers.CreateFixedWindowPolicy(
            policyName: "report-export",
            permitLimit: 5,
            window: TimeSpan.FromMinutes(1),
            partitionKeySelector: RateLimitPartitionHelpers.GetClientPartitionKey));

    options.AddRouteRejectionHandler("ExportReport", async (context, cancellationToken) =>
    {
        await context.HttpContext.Response.WriteAsJsonAsync(new { error = "too_many_requests" }, cancellationToken);
    });
});

Built-In Limits Shipped by Orchard Core

| Feature | Endpoint (POST) | Limit | Counted against |

|---|---|---|---|

| Users | Login | 100 per minute, sliding (password-authentication) | IP, shared with external login linking and the OpenID password grant |

| Users | Resend confirmation email | 2 per minute, fixed (email-confirmation) | User who passed the password check |

| Users: External Authentication | LinkExternalLogin | 100 per minute, sliding (password-authentication) | IP, shared with login |

| Users: External Authentication | RegisterExternalLogin | 20 per minute, sliding (user-registration) | IP, shared with registration |

| Users: User Registration | Register | 20 per minute, sliding (user-registration) | IP |

| Users: Reset Password | Forgot password, reset password | 20 per minute, sliding (password-recovery) | IP, shared by both |

| Users: Two-Factor Authentication | Two-factor code / recovery code | 5 / 3 per minute, sliding (two-factor-authentication / two-factor-recovery) | User who passed the password check |

| Users: Email and SMS Authenticators | Send code | 2 per minute, fixed (two-factor-code-send) | User who passed the password check, shared by both |

| OpenID Authorization Server | Access.Token (/connect/token), password grant only | 100 per minute, sliding (password-authentication) | IP, shared with login. Rejections get an OAuth 2.0 slow_down error with Retry-After |

Policies that share a policy name, such as password-authentication, share the same budget. The names are in OrchardCore.Users.UserRateLimiterPolicyNames. Anonymous sign-in limits are generous on purpose: account lockout and the one-email-per-minute limits on password reset and confirmation emails protect each account. The other OpenID grants (codes, refresh tokens, client credentials) are not limited, since a single server often requests tokens for many users.

GraphQL (/api/graphql) and the health check URL are mapped as endpoints, so an Endpoint policy on their path limits them.

Troubleshooting

| Symptom | Check |

|---|---|

| Every client is throttled together | The proxy IP is used as the partition key; configure forwarded headers and known proxies. |

| Users of an office are throttled while signed out | Anonymous visitors share their IP budget; raise the global or endpoint limit. |

| Policy edits are rejected | Enabled policies only accept name and description changes; disable the policy first. |

| Endpoint policy never matches | Path must start with / and is a prefix of the tenant-relative request path. |

| Group policy never matches | The endpoint lacks [RateLimitGroup] or WithRateLimitGroups() metadata with the same name. |

| Recipe import fails | Endpoint policies need Path, group policies need GroupName, and the step needs a policies array. |

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.