skip to content

During ASP.NET Core shutdown, why doesn't HttpContext.RequestAborted fire for in-flight requests, and when should an endpoint watch ApplicationStopping instead?

level: seniorimportance: should knowfreq 30%

answer

  1. per-request versus process-wide
  2. client disconnect or connection abort
  3. streams hold the drain open
  4. CreateLinkedTokenSource
  5. short writes should just finish

basics

~20 s

RequestAborted means this request's connection is gone, which during shutdown only happens when Kestrel aborts at the ShutdownTimeout. Open-ended endpoints such as streams or long polls should also watch ApplicationStopping and end cleanly; short transactional requests should simply finish.

solid answer

~40 s

`HttpContext.RequestAborted` is a per-request token cancelled when the client disconnects or the server aborts the connection. Graceful shutdown deliberately does not cancel it: Kestrel lets in-flight requests finish and aborts connections only when `HostOptions.ShutdownTimeout` expires. `IHostApplicationLifetime.ApplicationStopping` is the process-wide signal that shutdown has begun. An endpoint that would otherwise run indefinitely, such as a server-sent events stream, a long poll or a slow export, keeps the drain waiting the full timeout and is then cut off mid-response. Link both tokens with `CancellationTokenSource.CreateLinkedTokenSource(ctx.RequestAborted, lifetime.ApplicationStopping)` and end the response cleanly so the client reconnects to a healthy instance. Do not do that for a short seat purchase: cancelling a two-second transaction on shutdown turns a request that would have succeeded into a failure.

code

csharp · 20 lines
csharp
app.MapGet("/concerts/{id:int}/seat-map/stream",
    async (int id, HttpContext ctx, IHostApplicationLifetime lifetime, SeatMapFeed feed) =>
{
    using var cts = CancellationTokenSource.CreateLinkedTokenSource(
        ctx.RequestAborted, lifetime.ApplicationStopping);

    ctx.Response.ContentType = "text/event-stream";
    try
    {
        await foreach (var change in feed.WatchAsync(id, cts.Token))
        {
            await ctx.Response.WriteAsync($"data: {change}\n\n", cts.Token);
            await ctx.Response.Body.FlushAsync(cts.Token);
        }
    }
    catch (OperationCanceledException) when (lifetime.ApplicationStopping.IsCancellationRequested)
    {
        // Shutting down: return normally so the browser reconnects to another instance.
    }
});

go deeper

for a junior

Recall that RequestAborted belongs to one request and fires on disconnect, while ApplicationStopping signals that the whole app is shutting down.

for a middle

Explain why graceful shutdown leaves RequestAborted alone until the timeout, and how a linked token ends a long response early.

for a senior

Decide per endpoint whether shutdown should end the work or let it finish, and find the streams that hold every drain open for the full budget.

for a principal

Set a convention for long-lived connections and idempotent writes so deploys neither strand clients nor cancel committed business work.

## Two different signals | | `HttpContext.RequestAborted` | `IHostApplicationLifetime.ApplicationStopping` | |---|---|---| | Scope | one request | the whole process | | Cancelled when | the client disconnects, or the server aborts the connection | graceful shutdown begins (SIGTERM, Ctrl+C, `StopApplication()`) | | During a normal shutdown | only if Kestrel aborts the connection after `HostOptions.ShutdownTimeout` | at the very start | | Meaning | nobody will read the response | finish up; this instance is going away | Graceful shutdown is designed so in-flight work completes. Kestrel stops accepting new connections and waits; it does **not** cancel `RequestAborted` to hurry requests along. That token is cancelled for a request only when its connection is torn down: by the client, or by Kestrel when the shutdown budget (30 seconds by default) runs out. ## Why long-running endpoints are a problem Consider a concert-ticket API that also serves a **seat-map stream**: each open browser holds a request that writes an update every few seconds and never completes on its own. On SIGTERM: 1. Kestrel waits for every in-flight request, including every open stream. 2. The streams never finish, so the drain lasts the whole `ShutdownTimeout`. 3. At the deadline Kestrel aborts them; the browsers see a broken stream, and the instance spent its entire budget waiting. 4. Background services that stop after the server now have no time left. The same applies to long polls, chunked exports and any loop that only checks `RequestAborted`. ## Watching both tokens The fix is to treat shutdown as a reason to end such responses, using a linked token: ```csharp using var cts = CancellationTokenSource.CreateLinkedTokenSource( ctx.RequestAborted, lifetime.ApplicationStopping); ``` `cts.Token` is cancelled when **either** source is. Pass it to every awaited call in the loop. When it fires because of `ApplicationStopping`, stop writing and let the handler return: the response ends normally, the client's reconnect logic kicks in, and the load balancer sends it to a healthy instance. The drain then completes in milliseconds instead of 30 seconds. ## When not to watch ApplicationStopping Most requests are short and should be left alone: - A seat purchase that reserves, charges and commits in a couple of seconds will finish well inside the budget. Cancelling it on `ApplicationStopping` converts a success into an error and may leave the customer unsure whether they paid. - Database writes passed `ApplicationStopping` can be rolled back halfway through a multi-step operation. - Handlers that already accept a `CancellationToken` parameter in a Minimal API receive `RequestAborted`, which is what they should keep observing. A practical rule: - **Open-ended or long work** (streams, polls, exports longer than the budget): link `ApplicationStopping`. - **Bounded work that fits the budget**: observe only `RequestAborted`, and make the operation idempotent in case the budget is exceeded anyway. ## What the code sees when the budget runs out If Kestrel aborts a connection, `RequestAborted` is cancelled. Awaited calls that received it throw `OperationCanceledException`; the framework treats that as an aborted request rather than an unhandled error. Code that does not observe the token keeps running, but nothing it writes can reach the client any more. Neither outcome is a clean result for the client.

  • In a Minimal API handler, which token does a CancellationToken parameter receive?
    `HttpContext.RequestAborted`. Minimal APIs bind a `CancellationToken` parameter to the request's aborted token, not to `ApplicationStopping`. So a handler written that way keeps running through a graceful shutdown and is only cancelled if the client disconnects or Kestrel aborts the connection at `HostOptions.ShutdownTimeout`.
  • Why is it bad if every endpoint links ApplicationStopping into its database calls?
    Shutdown would cancel short, bounded operations that would have finished inside the 30-second budget, turning successful purchases into errors and possibly interrupting multi-step writes. Graceful shutdown exists so such requests complete; only open-ended or longer-than-budget work should stop early.

  • Kestrel cancels RequestAborted for every request as soon as SIGTERM arrives.
  • A CancellationToken handler parameter is bound to ApplicationStopping.
  • Every request should link ApplicationStopping into its database calls.
  • Streaming endpoints finish on their own during shutdown.
  • ApplicationStopped is the token to watch for ending a response early.