Graceful SIGTERM Shutdown & `IHostApplicationLifetime`
1Concept
When Kubernetes scales down or restarts pods, it sends a `SIGTERM` signal. ASP.NET Core gives the application a grace period (default 30s) to finish in-flight HTTP requests and flush message buffers before `SIGKILL`.
2Architecture Diagram
Kubernetes sends SIGTERM
│
[ IHostApplicationLifetime.ApplicationStopping Triggered ]
├── Kestrel stops accepting new HTTP connections
├── In-flight HTTP requests complete cleanly
└── Channels & Background workers flush buffers to disk
│
[ Process Exits Code 0 (Zero Dropped User Transactions!) ]3Code Example
C# 13 & .NET 9
using System;
public class GracefulShutdownConceptDemo
{
public static void Main()
{
Console.WriteLine("Graceful shutdown registration:");
Console.WriteLine("app.Lifetime.ApplicationStopping.Register(() => {");
Console.WriteLine(" Console.WriteLine("Flushing message queues before container termination...");");
Console.WriteLine("});");
}
}4Expected Output
Graceful shutdown registration:
app.Lifetime.ApplicationStopping.Register(() => {
Console.WriteLine("Flushing message queues before container termination...");
});5Key Takeaways
- ✓Register teardown tasks on `IHostApplicationLifetime.ApplicationStopping`.
- ✓Configure Kubernetes `terminationGracePeriodSeconds: 60` for long batch operations.
- ✓Ensures zero dropped HTTP requests during rolling cluster deployments.