skip to content

In an ASP.NET Core 10 API, a stock report endpoint has a 30-second request timeout but still runs for minutes. What does the timeout middleware actually do, and why might it not stop the work?

level: seniorimportance: should knowfreq 40%

answer

  1. AddRequestTimeouts + UseRequestTimeouts
  2. no DefaultPolicy unless you set one
  3. cancels HttpContext.RequestAborted, kills nothing
  4. 504 unless TimeoutStatusCode
  5. skipped while a debugger is attached

basics

~20 s

The request timeouts middleware only cancels HttpContext.RequestAborted when the limit passes; if that cancellation surfaces as an exception before the response starts, it answers 504. Code that ignores the token keeps running, and nothing fires with a debugger attached.

solid answer

~50 s

In ASP.NET Core 10 you register `AddRequestTimeouts` (no `DefaultPolicy` by default, so nothing times out until you configure it), call `UseRequestTimeouts()` after routing, and attach a limit with `WithRequestTimeout(TimeSpan.FromSeconds(30))`, a named policy, or `[RequestTimeout(30_000)]`, whose integer is **milliseconds**. When the time passes, the middleware cancels a token linked into `HttpContext.RequestAborted`; it does not abort the connection or stop a thread. If the handler passed that token to EF Core or `HttpClient`, an `OperationCanceledException` bubbles up and, provided the response has not started, the middleware writes 504 or the policy's `TimeoutStatusCode`. The endpoint keeps running when it never observes the token, catches the cancellation and returns normally, or blocks synchronously; nothing fires while a debugger is attached or on endpoints marked `DisableRequestTimeout`, and an endpoint's own limit is invisible when `UseRequestTimeouts` runs before an explicit `UseRouting`.

code

csharp · 16 lines
csharp
builder.Services.AddRequestTimeouts(o =>
    o.AddPolicy("Reports", new RequestTimeoutPolicy
    {
        Timeout = TimeSpan.FromSeconds(30),
        TimeoutStatusCode = StatusCodes.Status503ServiceUnavailable
    }));

var app = builder.Build();
app.UseRequestTimeouts();

app.MapGet("/api/reports/stock-ageing",
        async (WarehouseDb db, CancellationToken ct) =>
            TypedResults.Ok(await db.StockAgeing.ToListAsync(ct)))
   .WithRequestTimeout("Reports");

app.Run();

go deeper

for a junior

Know that request timeouts must be registered and configured, and that they work by cancelling the request's CancellationToken.

for a middle

Configure policies, WithRequestTimeout and [RequestTimeout] correctly, including the milliseconds unit, and explain the 504 path.

for a senior

Diagnose a timeout that never stops work: ignored or swallowed tokens, debugger, placement before routing, opted-out endpoints.

for a principal

Set timeout budgets across endpoints and downstream calls so cancellation propagates end to end instead of piling up work.

## Setting it up The request timeouts middleware arrived in .NET 8 and lives in `Microsoft.AspNetCore.Http.Timeouts`. It needs a service registration, a pipeline call and at least one limit: ```csharp builder.Services.AddRequestTimeouts(options => { options.DefaultPolicy = new RequestTimeoutPolicy { Timeout = TimeSpan.FromSeconds(10) }; options.AddPolicy("Reports", TimeSpan.FromSeconds(30)); }); app.UseRouting(); app.UseRequestTimeouts(); ``` `RequestTimeoutOptions.DefaultPolicy` is `null` by default, so adding the middleware changes nothing until you set a default or mark endpoints. Because it reads endpoint metadata, it must run **after** routing; with an explicit `UseRouting`, place it after that call. ## Attaching a limit to an endpoint | Way | Example | Notes | |---|---|---| | Minimal API, fixed time | `.WithRequestTimeout(TimeSpan.FromSeconds(30))` | adds a `RequestTimeoutPolicy` as metadata | | Minimal API, named policy | `.WithRequestTimeout("Reports")` | unknown name throws `InvalidOperationException` at request time | | Controller or page | `[RequestTimeout("Reports")]` or `[RequestTimeout(30_000)]` | the integer constructor takes **milliseconds** | | Opt out | `.DisableRequestTimeout()` or `[DisableRequestTimeout]` | also cancels the default policy | Policy metadata wins over the attribute, the attribute wins over `DefaultPolicy`, and a disable marker wins over everything. Inside a handler, `IHttpRequestTimeoutFeature.DisableTimeout()` cancels a timeout that has not fired yet, for example once a long export has started streaming. ## Applying a policy to a whole group `WithRequestTimeout` is an extension on `IEndpointConventionBuilder`, so it works on a route group as well as on a single endpoint: ```csharp var reports = app.MapGroup("/api/reports"); reports.WithRequestTimeout("Reports"); // returns IEndpointConventionBuilder, so keep the group variable reports.MapGet("/stock-ageing", GetStockAgeing); reports.MapGet("/slow-movers", GetSlowMovers) .WithRequestTimeout(TimeSpan.FromSeconds(60)); ``` The slow-movers endpoint carries both a policy name (from the group) and a `RequestTimeoutPolicy` (its own call); policy metadata wins, so it gets 60 seconds. Be careful with that rule in reverse: a `TimeSpan` set on a group outranks a named policy attribute on one endpoint inside it. ## What happens when the time is up 1. The middleware created a `CancellationTokenSource` with the timeout, linked it to the original `RequestAborted`, and set `HttpContext.RequestAborted` to the linked token. 2. When the timeout elapses, that token is **cancelled**. The connection is not aborted and no thread is interrupted. 3. If code observing the token throws `OperationCanceledException` up to the middleware, and the response **has not started**, it clears the response and sets `TimeoutStatusCode` from the policy, or **504 Gateway Timeout**. A `WriteTimeoutResponse` delegate on the policy can write a body. 4. If the response has already started, the exception is rethrown. Cancellation is **cooperative**: only code that receives the token can stop. A custom body is written by the policy's delegate, for example `WriteTimeoutResponse = ctx => ctx.Response.WriteAsJsonAsync(new { error = "report took too long" })`, which the middleware calls after setting the status code. ## Why the report keeps running - **The token is never passed on.** `ToListAsync()` without `ct`, a `Thread.Sleep`, or a CPU loop that never checks the token runs to completion; the client eventually gets a late 200. - **The handler swallows the cancellation.** A `catch (Exception)` that logs and returns `Ok(partial)` turns the timeout into a normal response. - **A debugger is attached.** The middleware skips its work entirely while `Debugger.IsAttached`, so timeouts never fire under F5. - **The middleware cannot see the endpoint.** Placed before an explicit `UseRouting`, it sees no metadata and only `DefaultPolicy` applies. - **The unit is wrong.** `[RequestTimeout(30)]` is 30 milliseconds, not 30 seconds; the opposite mistake makes a limit 1,000 times too long. - **The endpoint opted out**, or the request was already aborted by the client. The Kestrel limits are a different layer: `KeepAliveTimeout` and `RequestHeadersTimeout` police connections and header arrival, not how long a handler may run. ## What interviewers listen for - No timeout until you configure one, and the debugger exemption. - Cancel the token, then 504 only if the cancellation surfaces before the response starts. - Passing `HttpContext.RequestAborted` (or the bound `CancellationToken`) into every awaited call.

  • How is the request timeouts middleware different from Kestrel's timeouts?
    Kestrel's limits such as `KeepAliveTimeout` (130 seconds) and `RequestHeadersTimeout` (30 seconds) govern connections and how fast headers arrive; they never limit how long your handler runs. The request timeouts middleware is per endpoint and only cancels `HttpContext.RequestAborted`, leaving it to the handler to stop and to the middleware to answer 504.
  • A long CSV export should be limited while it builds the data but not while it streams. How?
    Keep the timeout for the query phase, then call `context.Features.Get<IHttpRequestTimeoutFeature>()?.DisableTimeout()` once streaming begins. A timeout cannot be cancelled after it has fired, and after the response has started the middleware could not send a 504 anyway, so disabling it avoids cancelling a healthy stream.
  • Why does the timeout never fire when you debug the API from the IDE?
    The middleware returns straight to the next delegate when `Debugger.IsAttached` is true, the same convention Kestrel follows for its own timeouts, so breakpoints do not trigger timeouts. To test a timeout, run the app without the debugger, for example with `dotnet run`.

  • When the timeout fires, ASP.NET Core aborts the thread running the handler.
  • Adding UseRequestTimeouts gives every endpoint a default timeout.
  • [RequestTimeout(30)] limits the action to 30 seconds.
  • The middleware answers 408 Request Timeout when the limit is reached.
  • Kestrel's KeepAliveTimeout already limits how long a handler may run.

Assumes ASP.NET Core 10; the request timeouts middleware, [RequestTimeout] and WithRequestTimeout arrived in .NET 8 and behave the same in 10.