Skip to main content

How to Let Requests Finish When an ASP.NET Core App Shuts Down (C#)

· 16 min read
Jagdish Kumawat
Founder @ Dewiride

When an ASP.NET Core app stops, it doesn't drop the requests it's still answering straight away: it stops taking new ones and gives the rest 30 seconds. A request that needs longer is cut off, and the caller gets an error instead of an answer. Here's that happening to a 40-second request, and the one setting that lets it finish.

Apps stop more often than you might think. You press Ctrl+C while you work on one. A hosting platform stops it when it scales in or replaces it with a new version, and it does that by sending the app the signal SIGTERM. ASP.NET Core handles Ctrl+C and SIGTERM the same way: it shuts down gracefully, within a time limit called the shutdown timeout. This guide shows what that limit does to a slow request, and two ways to change it.

Syntax​

In Program.cs, before builder.Build():

Syntax
builder.Services.Configure<HostOptions>(options =>
{
options.ShutdownTimeout = TimeSpan.FromSeconds(<seconds>);
});

Or, without changing the code, as an environment variable that is set when the app starts:

Syntax
DOTNET_SHUTDOWNTIMEOUTSECONDS=<seconds>
PartWhat it is
builder.Services.Configure<HostOptions>Changes the options of the host, the part of ASP.NET Core that starts and stops the app
optionsThe host's options, a HostOptions object
ShutdownTimeoutSpecifies the amount of time to wait for the host to shut down. The default is 30 seconds
TimeSpan.FromSeconds(<seconds>)The limit. <seconds> is how long requests that are still running get to finish after the app is told to stop
DOTNET_SHUTDOWNTIMEOUTSECONDSThe same limit from an environment variable: the host setting shutdownTimeoutSeconds with the DOTNET_ prefix. ASPNETCORE_SHUTDOWNTIMEOUTSECONDS works too
<seconds> in the variableA whole number of seconds. Microsoft lists the setting's type as int

Step 4 shows how to set the variable in bash, zsh and PowerShell.

The Example​

SlowReport is a small web app with one address, /report, that takes 40 seconds to answer, like a report that reads a lot of data. Each run sends it one request and stops the app while that request is still being answered: first as the app comes, then with the limit raised to 60 seconds in code, and then with the environment variable instead.

Step 1: Create the App​

Terminal
dotnet new web --no-https -n SlowReport
cd SlowReport

dotnet new web creates an empty ASP.NET Core app from the template called ASP.NET Core Empty. --no-https leaves HTTPS out, so the example needs no development certificate, and -n SlowReport names the project and its folder. cd moves into that folder. The first command prints:

Output
The template "ASP.NET Core Empty" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/SlowReport/SlowReport.csproj:
Restore succeeded.

Replace everything in Program.cs with this:

Program.cs
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/report", async () =>
{
app.Logger.LogInformation("Report started.");
await Task.Delay(TimeSpan.FromSeconds(40));
app.Logger.LogInformation("Report finished.");
return "Your report is ready.";
});

app.Run();

What each part does:

  • WebApplication.CreateBuilder(args) and builder.Build() set up the app, as in every new ASP.NET Core project.
  • app.MapGet("/report", ...) answers GET requests to /report with the code after it.
  • app.Logger.LogInformation writes a line to the terminal under the app's name, SlowReport, so you can see when the report starts and when it finishes.
  • await Task.Delay(TimeSpan.FromSeconds(40)) waits 40 seconds. It stands in for slow work, such as a big database query.
  • The text it returns, Your report is ready., is the answer the caller gets.
  • app.Run() starts the app and keeps it running until it's told to stop.

Step 2: Stop the App While a Request Is Running​

You need two terminals. In the first one, in the SlowReport folder, start the app:

Terminal 1
dotnet run --no-launch-profile --urls http://localhost:5310

dotnet run builds the app and starts it. --no-launch-profile skips Properties/launchSettings.json, where dotnet new picked a random port, and --urls makes the app listen on port 5310 instead. How to Run an ASP.NET Core App on a Fixed Port explains both. Wait until it prints Application started. Press Ctrl+C to shut down.

In the second terminal, ask for the report:

Terminal 2
curl -sS -w '\n%{http_code} after %{time_total}s\n' http://localhost:5310/report

curl sends a GET request and prints the answer. -sS hides its progress meter but still shows errors, and -w adds a last line with the HTTP status code and how long the request took. In PowerShell, Invoke-RestMethod sends the request and prints the answer.

Terminal 2 now waits for the report. Straight away, while it's still waiting, go back to Terminal 1 and press Ctrl+C. Terminal 1 shows:

Output (Terminal 1)
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://localhost:5310
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
Content root path: /Users/you/source/SlowReport
info: SlowReport[0]
Report started.
^Cinfo: Microsoft.Hosting.Lifetime[0]
Application is shutting down...

Report started. is the request arriving. ^C is how the terminal shows Ctrl+C, and Application is shutting down... is the app beginning to stop. Then nothing more: Report finished. never came, and about 31 seconds after Ctrl+C the app ended. Terminal 2 got this:

Output (Terminal 2)
curl: (56) Recv failure: Connection reset by peer

000 after 31.285464s

A macOS-style terminal window titled Terminal — SlowReport showing a curl request to http://localhost:5310/report that ends with curl: (56) Recv failure: Connection reset by peer and the line 000 after 31.285464s, because the app was stopped while the 40-second report was still running.

The caller got no report. The app closed the connection while the request was still running, which both tools report as "Connection reset by peer", and curl's 000 means that no HTTP status code arrived at all. The 31.3 seconds are the moment before Ctrl+C plus the 30-second limit. I ran the PowerShell command in PowerShell 7.6 on macOS.

That's what Microsoft describes for the end of the limit: If the timeout expires, the pending connections and requests are aborted forcefully, which can cause errors in the logs and to the clients.

Step 3: Give Requests More Time​

Add these lines to Program.cs, between the var builder line and var app = builder.Build();:

Program.cs
builder.Services.Configure<HostOptions>(options =>
{
options.ShutdownTimeout = TimeSpan.FromSeconds(60);
});

HostOptions holds the settings of the host, and ShutdownTimeout is how long it waits for running requests when the app stops. 60 seconds gives the 40-second report room to finish. The lines have to come before builder.Build(): after it, the app stops at startup with an InvalidOperationException.

The complete Program.cs:

Program.cs
var builder = WebApplication.CreateBuilder(args);

builder.Services.Configure<HostOptions>(options =>
{
options.ShutdownTimeout = TimeSpan.FromSeconds(60);
});

var app = builder.Build();

app.MapGet("/report", async () =>
{
app.Logger.LogInformation("Report started.");
await Task.Delay(TimeSpan.FromSeconds(40));
app.Logger.LogInformation("Report finished.");
return "Your report is ready.";
});

app.Run();

A macOS-style code window titled Program.cs — SlowReport showing builder.Services.Configure for HostOptions setting ShutdownTimeout to TimeSpan.FromSeconds(60) before builder.Build(), and a /report endpoint that logs Report started., waits 40 seconds with Task.Delay, logs Report finished. and returns Your report is ready.

Do the same as in Step 2: start the app in Terminal 1 with the same command, ask for the report in Terminal 2, and press Ctrl+C in Terminal 1 while Terminal 2 waits. Terminal 1:

Output (Terminal 1)
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://localhost:5310
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
Content root path: /Users/you/source/SlowReport
info: SlowReport[0]
Report started.
^Cinfo: Microsoft.Hosting.Lifetime[0]
Application is shutting down...
info: SlowReport[0]
Report finished.

A macOS-style terminal window titled Terminal — SlowReport showing dotnet run with --no-launch-profile and --urls http://localhost:5310: the app starts, logs Report started., is stopped with Ctrl+C and logs Application is shutting down..., and then logs Report finished. before it ends.

This time Report finished. came after Application is shutting down...: the app waited for the request. It didn't wait the whole 60 seconds, though. It ended about 39 seconds after Ctrl+C, as soon as the report was done. Microsoft puts it this way: If they're all complete before the timeout, the server returns control to the host sooner. Terminal 2 got the report:

Output (Terminal 2)
Your report is ready.
200 after 40.052716s

Status 200, 40 seconds after it asked: the whole report, even though the app was told to stop 39 seconds before it was ready.

Step 4: Set It Without Changing the Code​

The same limit can come from an environment variable. That suits a server or a hosting platform, where each environment can have its own value without a new build. To try it, take the four lines from Step 3 out of Program.cs again, so that it's back to the code from Step 1. Then start the app with the variable:

Terminal 1
DOTNET_SHUTDOWNTIMEOUTSECONDS=60 dotnet run --no-launch-profile --urls http://localhost:5310

In bash and zsh, NAME=value in front of a command sets the variable for that one command. In PowerShell, $env: sets it for the rest of the session in that window, so every app you start from it afterwards gets it.

Ask for the report in Terminal 2 and press Ctrl+C in Terminal 1, as before. Terminal 1:

Output (Terminal 1)
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://localhost:5310
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
Content root path: /Users/you/source/SlowReport
info: SlowReport[0]
Report started.
^Cinfo: Microsoft.Hosting.Lifetime[0]
Application is shutting down...
info: SlowReport[0]
Report finished.

A macOS-style terminal window titled Terminal — SlowReport showing DOTNET_SHUTDOWNTIMEOUTSECONDS=60 in front of dotnet run with --no-launch-profile and --urls http://localhost:5310, and the same log as with the setting in code: Report started., Ctrl+C, Application is shutting down... and then Report finished.

And Terminal 2:

Output (Terminal 2)
Your report is ready.
200 after 40.052788s

The same result as Step 3, with no change to the code. ASPNETCORE_SHUTDOWNTIMEOUTSECONDS=60 worked the same way in my run: Microsoft lists both prefixes, DOTNET_ and ASPNETCORE_, for the host's settings.

What Happens When an ASP.NET Core App Stops​

Microsoft's documentation of the .NET Generic Host, which runs every ASP.NET Core app, describes the order:

  1. A signal to stop arrives. Ctrl+C, or SIGTERM, which other apps send to stop yours (docker stop is Microsoft's example). The host's console lifetime listens for both and attempts to stop the host gracefully.
  2. The app is told. The host signals ApplicationStopping, which your own code can listen to, and asks the web server, Kestrel, to stop, with the shutdown timeout.
  3. New connections are refused. In Microsoft's words, Kestrel and Http.Sys close their port bindings and stop accepting new connections.
  4. Running requests get the rest of the timeout. When the last one finishes, the app ends. When the time runs out first, the rest are cut off.

You can watch the third step happen. In another run with Step 3's code, I sent a second request 2 seconds after Ctrl+C, while the first one was still running:

Output
curl: (7) Failed to connect to localhost port 5310 after 0 ms: Couldn't connect to server

000 after 0.000364s

The new request was refused at once, and the first one still got its report, 40 seconds after it started.

The shutdown timeout only applies when the app is asked to stop. A crash, or a forced stop with SIGKILL, ends the process without it. About those, Microsoft says: The hosting code isn't responsible for handling these scenarios.

Choose the Limit​

  • Longer than your slowest request. Here the report takes 40 seconds and the limit is 60. A limit far above your slowest request only makes a stuck request hold up the shutdown longer.
  • Shorter than whatever stops the app. A hosting platform waits only so long after SIGTERM before it ends the app with SIGKILL. Azure Container Apps, for example: If your application doesn't respond within 30 seconds to the SIGTERM message, then SIGKILL terminates your container. Its setting for that wait, terminationGracePeriodSeconds, defaults to 30 seconds, and Microsoft's advice for it is: Set this value longer than the expected cleanup time for your process. So a 60-second shutdown timeout needs a grace period of more than 60 seconds there. I didn't run this example on a hosting platform: this part is what Microsoft documents.

Common Mistakes​

MistakeWhat happensDo this instead
A shutdown timeout shorter than your slowest requestRequests still running when the app stops are cut off, and the caller gets a connection errorSet the timeout above your slowest request
Configure<HostOptions> after builder.Build()The app stops at startup with The service collection cannot be modified because it is read-onlyPut it before builder.Build()
Setting the environment variable in a different terminal from the one that starts the appThe app only gets the variables of the terminal it starts from, so the default 30 seconds appliesSet it in the terminal that runs dotnet run, or where your server starts the app
A shutdown timeout longer than the platform's grace periodThe platform ends the app with SIGKILL before the timeout is upMake the platform's grace period longer than the shutdown timeout
Counting on the timeout after a crash or a forced killNothing waits: the host doesn't handle thoseKeep long work in a form that can be retried

Troubleshooting​

SymptomLikely causeFix
Callers get Connection reset by peer or Unable to read data from the transport connection when you stop or redeploy the appTheir requests were still running when the shutdown timeout ran outRaise ShutdownTimeout above your slowest request
Requests are still cut off after about 30 secondsThe new value didn't reach the appCheck that the code comes before builder.Build(), or that the variable is set where the app starts
curl: (7) Failed to connect right after Ctrl+CThe app has stopped taking new connections, as it shouldSend new requests to another copy of the app before you stop this one

FAQ​

What is the default shutdown timeout?​

30 seconds. Microsoft notes that in .NET 5 and earlier it was 5 seconds.

Does the app always wait for the whole timeout?​

No. It ends as soon as the last request finishes. In Step 3 that was about 39 seconds after Ctrl+C, not 60.

Do new requests get in while the app waits?​

No. From the moment shutdown starts, new connections are refused: the second request in the run above failed after 0 ms.

Does this also work when Docker or a hosting platform stops the app?​

They send SIGTERM, and Microsoft lists SIGTERM among the signals that make the host shut down gracefully, the same way as Ctrl+C. I tested with Ctrl+C. Check how long the platform waits before it forces the app to stop, as in Choose the Limit.

Does the timeout cover background services too?​

Yes. Microsoft lists it among what the host does during the timeout: Attempts to stop hosted services, logging errors for services that fail to stop. And its advice: If services require more time to stop, increase the timeout.

Conclusion​

ASP.NET Core gives requests that are still running 30 seconds when it stops, and cuts off the rest. Raise ShutdownTimeout with Configure<HostOptions> before builder.Build(), or set DOTNET_SHUTDOWNTIMEOUTSECONDS, to a value above your slowest request, and make sure whatever stops the app waits longer than that.

Additional Resources​