In ASP.NET Core 10, why does a request the rate limiter rejects get 503, and how do you send 429 with a Retry-After value instead?
answer
- a property default, not a protocol rule
- RejectionStatusCode = Status503ServiceUnavailable
- status set before OnRejected runs
- Lease.TryGetMetadata(MetadataName.RetryAfter, ...)
- policy OnRejected beats options OnRejected
basics
~10 sRateLimiterOptions.RejectionStatusCode defaults to StatusCodes.Status503ServiceUnavailable. Set it to Status429TooManyRequests, and in OnRejected read MetadataName.RetryAfter from context.Lease to write a Retry-After header.
solid answer
~40 sThe middleware sets `context.Response.StatusCode = options.RejectionStatusCode` on every rejection, and that property is initialised to `StatusCodes.Status503ServiceUnavailable` in ASP.NET Core 10, so clients and dashboards see an outage rather than a client-side quota error. Set `options.RejectionStatusCode = StatusCodes.Status429TooManyRequests`. For headers or a body, assign `options.OnRejected = async (context, token) => { ... }`: the status code is already set when it runs, so whatever it writes wins. Inside, `context.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter)` returns how long until a permit is likely, which you write as `Retry-After` in seconds. Window and token bucket leases can carry that metadata; a concurrency limiter's lease never does. A policy's own `OnRejected` (from `IRateLimiterPolicy<T>`) replaces the options-level one when that endpoint's policy rejected, but not when the global limiter did.
code
csharp · 25 linesusing System.Globalization;
using System.Threading.RateLimiting;
builder.Services.AddRateLimiter(options =>
{
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.OnRejected = async (context, cancellationToken) =>
{
if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter))
{
context.HttpContext.Response.Headers.RetryAfter =
((int)Math.Ceiling(retryAfter.TotalSeconds)).ToString(CultureInfo.InvariantCulture);
}
await context.HttpContext.Response.WriteAsync(
"Free tier limit reached. Try again later.", cancellationToken);
};
options.AddFixedWindowLimiter("free", o =>
{
o.PermitLimit = 60;
o.Window = TimeSpan.FromMinutes(1);
});
});go deeper
Remember the surprise: rejected requests get 503 unless RejectionStatusCode is set to 429.
Explain the order inside the middleware: status set from RejectionStatusCode, then OnRejected, so the callback's status wins; know where RetryAfter metadata comes from.
Handle the edges: no RetryAfter on concurrency leases, global versus policy OnRejected, cancelled queued requests, and metrics that separate throttling from outages.
Define one rejection contract across services, status, headers and body, so clients and alerting treat throttling consistently and never page anyone for a quota.
## Where the 503 comes from When the rate limiting middleware cannot get a permit for a request, it does not throw and it does not write a body. It sets the response status from **`RateLimiterOptions.RejectionStatusCode`** and returns without calling the rest of the pipeline. In ASP.NET Core 10 that property is declared as: ```csharp public int RejectionStatusCode { get; set; } = StatusCodes.Status503ServiceUnavailable; ``` So the default is a plain property initializer. Interviewers ask about it because the default surprises people: a client throttled by your free tier receives **503 Service Unavailable**, which monitoring and client libraries usually read as "the server is down", not "you are calling too often". The ASP.NET Core docs' own samples switch it to **429 Too Many Requests**. ## Changing the status The one-line fix: ```csharp builder.Services.AddRateLimiter(options => { options.RejectionStatusCode = StatusCodes.Status429TooManyRequests; }); ``` ## OnRejected: headers and a body `RateLimiterOptions.OnRejected` is a `Func<OnRejectedContext, CancellationToken, ValueTask>`. `OnRejectedContext` exposes: - **`HttpContext`** — the rejected request, so you can set headers, log, or write a body; - **`Lease`** — the failed `RateLimitLease`, which may carry metadata from the limiter. Order matters and is fixed by the middleware: 1. The middleware sets `Response.StatusCode` to `RejectionStatusCode`. 2. It picks a callback: the endpoint policy's `OnRejected` if the **endpoint** policy rejected and that policy defines one, otherwise `RateLimiterOptions.OnRejected`. 3. It invokes the callback with `context.RequestAborted` as the token. Because the status is set first, anything `OnRejected` assigns to `StatusCode` overrides `RejectionStatusCode`. ## Reading Retry-After from the lease `System.Threading.RateLimiting` defines `MetadataName.RetryAfter` (a `MetadataName<TimeSpan>`) and `MetadataName.ReasonPhrase`. Use the generic `TryGetMetadata` on the lease: | Limiter kind | `RetryAfter` on a failed lease? | |---|---| | Fixed window | usually — time until enough windows have passed | | Sliding window | usually | | Token bucket | usually — time until enough tokens are replenished | | Concurrency | no — it cannot know when a running request will finish | When the metadata is missing, omit the header rather than inventing a number. What `Retry-After` means to clients, and its date versus seconds formats, is HTTP semantics; the ASP.NET Core part is getting the value out of the lease. ## Edge cases worth knowing - **Global versus endpoint rejection**: if `GlobalLimiter` refused the request, the options-level `OnRejected` runs even when the endpoint's policy has its own. - **Cancelled while queued**: if the client disconnects while waiting in a limiter's queue, the middleware logs at debug level and returns **without** calling `OnRejected`. - **Logging and metrics**: each rejection writes a debug-level "Rate limits exceeded" log and is counted on the `Microsoft.AspNetCore.RateLimiting` meter (`aspnetcore.rate_limiting.requests` with an `aspnetcore.rate_limiting.result` tag), so dashboards can separate throttling from real failures. - **Body**: nothing is written by default. If clients expect a JSON error, write it in `OnRejected`. ## For the weather API's free tier Set `RejectionStatusCode` to 429, add `Retry-After` from the lease when it is present, and log the user or IP partition at information level in a per-policy `OnRejected`, so support can answer "why am I blocked?" without turning on debug logs. A short checklist for the rejection path of a public API: 1. **Status**: 429 configured once, at the options level, so global and endpoint rejections agree. 2. **Header**: `Retry-After` only when the lease supplies `RetryAfter`; round up to whole seconds. 3. **Body**: the same error shape the rest of the API returns, written in `OnRejected`, honouring the cancellation token it receives. 4. **Observability**: alert on 5xx rates without counting throttled requests, which is exactly what the 503 default would break. 5. **Test**: an integration test that exceeds the limit once and asserts the status and header, so a refactor cannot quietly bring back the 503.
- OnRejected sets StatusCode to 418 while RejectionStatusCode is 429. Which status does the client see?418. The middleware assigns `RejectionStatusCode` before invoking `OnRejected`, so any status the callback writes replaces it. `RejectionStatusCode` is just the value in place when `OnRejected` is absent or leaves the status alone.
- A policy implements IRateLimiterPolicy<string> with its own OnRejected, and RateLimiterOptions.OnRejected is also set. Which runs?Only one callback runs. If that endpoint's policy rejected the request, the policy's `OnRejected` runs instead of the options-level one. If the `GlobalLimiter` rejected it first, the policy never ran, so the options-level `OnRejected` handles it.
- The ASP.NET Core rate limiter returns 429 Too Many Requests by default.
- OnRejected runs before the status code is set, so RejectionStatusCode overrides it.
- Every lease, including a concurrency limiter's, carries a RetryAfter value.
- The middleware adds a Retry-After header automatically on rejection.
- OnRejected also runs when a queued request is cancelled by the client.
Assumes ASP.NET Core 10, where RateLimiterOptions.RejectionStatusCode is initialised to StatusCodes.Status503ServiceUnavailable, so 429 must be configured explicitly.