How would you implement graceful shutdown handling in Kestrel/ASP.NET Core to ensure in-flight requests complete before a container or process terminates during a deployment or scale-down event?
Short answer
ASP.NET Core listens for SIGTERM (the standard signal orchestrators like Kubernetes send before force-killing a container) and begins graceful shutdown, stopping acceptance of new connections while allowing in-flight requests up to a configurable grace period…
Advertisement
AModel answer
ASP.NET Core listens for SIGTERM (the standard signal orchestrators like Kubernetes send before force-killing a container) and begins graceful shutdown, stopping acceptance of new connections while allowing in-flight requests up to a configurable grace period (Host.ConfigureHostOptions's ShutdownTimeout, and Kubernetes' own terminationGracePeriodSeconds) to complete before the process actually exits -- IHostApplicationLifetime's ApplicationStopping token lets application code (like a background worker) hook into this shutdown sequence to clean up gracefully rather than being abruptly killed mid-operation.
builder.Host.ConfigureHostOptions(options => {
options.ShutdownTimeout = TimeSpan.FromSeconds(30);
});
public class GracefulWorker(IHostApplicationLifetime lifetime) : BackgroundService {
protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
lifetime.ApplicationStopping.Register(() => Console.WriteLine("Shutdown initiated, finishing current work..."));
while (!stoppingToken.IsCancellationRequested) { /* ... */ }
}
}Real-world example
A Kubernetes deployment configures a 30-second terminationGracePeriodSeconds matching the application's own ShutdownTimeout, ensuring in-flight API requests get a full 30 seconds to complete during a rolling deployment's pod termination, rather than being abruptly cut off mid-request.
Likely follow-ups
- What happens to requests that are still in-flight when the grace period expires?
- How does readiness probe behavior interact with graceful shutdown to stop new traffic from arriving during the shutdown window?
Related topics