skip to content

An ASP.NET Core 10 service always takes 30 seconds to stop and sometimes loses work on redeploy; how do HostOptions.ShutdownTimeout and the stop order explain it, and what do you change?

level: seniorimportance: should knowfreq 32%

answer

  1. one budget for the whole StopAsync
  2. 30 s is the default, not a target
  3. something holds the drain open
  4. shutdownTimeoutSeconds or Configure<HostOptions>
  5. Some connections failed to close gracefully

basics

~20 s

A stop lasting exactly 30 seconds means something consumed HostOptions.ShutdownTimeout: an open request, a blocking stopping callback or a hosted service. Lost work means that budget, or the platform's kill deadline, ran out. Fix the holder, then size the timeout.

solid answer

~40 s

`HostOptions.ShutdownTimeout` (30 seconds in .NET 10) is one cancellation budget for the host's whole `StopAsync`. `WebApplication` stops the server first, so Kestrel's drain spends from it before your hosted services get their `StopAsync`. A stop that always takes the full 30 seconds means something never finished: a long-lived request such as a stream, a slow `ApplicationStopping` callback, or a hosted service ignoring its token. Kestrel's `Debug` log `Some connections failed to close gracefully during server shutdown.` confirms the drain hit the deadline and aborted connections. Lost work follows: aborted requests, background services left with no budget, or the platform killing the process first. Fix the holder, then size the timeout with `builder.Services.Configure<HostOptions>(o => o.ShutdownTimeout = ...)` or the `shutdownTimeoutSeconds` setting, keeping it below the platform's kill deadline.

code

csharp · 12 lines
csharp
var builder = WebApplication.CreateBuilder(args);

// Slowest purchase ~5 s + outbox flush ~10 s; platform kills after 60 s
builder.Services.Configure<HostOptions>(o => o.ShutdownTimeout = TimeSpan.FromSeconds(45));

var app = builder.Build();
var sw = new System.Diagnostics.Stopwatch();
app.Lifetime.ApplicationStopping.Register(() => sw.Start());
app.Lifetime.ApplicationStopped.Register(() =>
    app.Logger.LogInformation("Shutdown took {Ms} ms", sw.ElapsedMilliseconds));

app.Run();

go deeper

for a junior

Recall that HostOptions.ShutdownTimeout limits how long a graceful stop may take and that its default is 30 seconds.

for a middle

Explain that one token covers the server drain and every hosted service, and show the ways to set the value.

for a senior

Diagnose a full-budget stop from logs, remove what holds the drain open, and size the timeout below the platform's kill deadline.

for a principal

Balance rollout speed against aborted work across services, and standardise how shutdown budgets and grace periods are set.

## One budget, shared When shutdown starts, the host's `StopAsync` creates a single cancellation token that fires after **`HostOptions.ShutdownTimeout`**. In .NET 10 the default is **30 seconds** (it was 5 seconds in .NET 5 and earlier). That token is handed to every stop step in turn: 1. `ApplicationStopping` callbacks (synchronous; they run before the token matters, but their time counts against the platform's deadline). 2. The **web server**: `WebApplication` registers the server's hosted service last, so it is stopped first. Kestrel stops accepting, asks connections to close, and waits for in-flight requests until the token fires; then it aborts them. 3. **Your hosted services**, in reverse registration order, each receiving the same token. A `BackgroundService` waits for its `ExecuteAsync` to finish or for the token, whichever comes first. 4. `ApplicationStopped` callbacks, then `app.Run()` returns. The timeout is not a hard kill. When it fires, Kestrel aborts connections and well-behaved services stop waiting, but a custom `IHostedService` that ignores the token can still hold `StopAsync` open. The hard kill comes from outside: the platform's grace period. ## Reading "always exactly 30 seconds" A stop that consistently takes the full budget means the drain or a stop step never completed by itself. Usual causes: - **Open-ended requests**: server-sent events, long polls or exports keep connections busy until Kestrel aborts them at the deadline. - **A blocking `ApplicationStopping` callback**, such as a synchronous flush or a `.Wait()` on a network call. - **A hosted service** that does not observe its cancellation token in `StopAsync`. How to confirm: - Enable `Debug` for `Microsoft.AspNetCore.Server.Kestrel.Connections`; `Some connections failed to close gracefully during server shutdown.` means the drain reached the deadline. - Timestamp the lifetime events with `ApplicationStopping` and `ApplicationStopped` callbacks to see where the time goes. ## Why work gets lost | Symptom | Cause | |---|---| | Clients see dropped connections during deploys | requests still running at the deadline were aborted | | Queued background work is never processed | the server used the whole budget, so background services got a cancelled token on arrival | | `ApplicationStopped` logging never appears | the platform killed the process before shutdown completed | ## What to change 1. **Remove the holder.** End streams and long polls on `ApplicationStopping`; make stopping callbacks quick; make hosted services honour their token. 2. **Size the timeout to real work.** It should exceed the slowest legitimate request plus the background flush, and stay **below** the platform's kill deadline so the app, not SIGKILL, decides what is aborted. 3. **Set it explicitly** rather than relying on the default: - in code: `builder.Services.Configure<HostOptions>(o => o.ShutdownTimeout = TimeSpan.FromSeconds(45));` - with the host builder: `builder.Host.ConfigureHostOptions(o => o.ShutdownTimeout = ...)`; - by configuration: the `shutdownTimeoutSeconds` host setting, for example the `DOTNET_SHUTDOWNTIMEOUTSECONDS` environment variable. 4. **Make writes idempotent**, so a purchase cut off at the deadline can be retried safely. ## Trade-offs - A longer timeout drains more work but slows every rollout, because each instance takes longer to go away. - A shorter one speeds deploys but aborts more in-flight requests. - `Timeout.InfiniteTimeSpan` disables the host's deadline entirely; the platform's kill then decides, without any orderly abort.

  • Does ShutdownTimeout forcibly kill hosted services that ignore it?
    No. It cancels the token passed to `StopAsync`. Kestrel then aborts connections and `BackgroundService.StopAsync` stops waiting for `ExecuteAsync`, but a custom `IHostedService` that never observes the token can keep `StopAsync` running. The process is only killed from outside, by the platform after its grace period.
  • Why should ShutdownTimeout be shorter than the platform's grace period?
    So the application decides what is aborted and still reaches `ApplicationStopped`, final logging and disposal. If the platform's SIGKILL arrives first, everything stops at once with no cleanup, and work the host would have aborted cleanly is simply lost.

  • ShutdownTimeout applies to each hosted service separately.
  • Raising ShutdownTimeout is the fix for every slow shutdown.
  • When ShutdownTimeout fires, the host kills the process.
  • HostOptions.ShutdownTimeout defaults to 5 seconds in .NET 10.
  • Background services always get a fresh 30 seconds after Kestrel drains.

Assumes ASP.NET Core 10 on .NET 10: HostOptions.ShutdownTimeout defaults to 30 seconds (5 seconds in .NET 5 and earlier) and is read from the shutdownTimeoutSeconds host setting.