Graceful Shutdown in ASP.NET Core Services

SIGTERM handling, draining in-flight requests, and the 30-second window Kubernetes gives you.

Pods killed mid-request caused 502s during every deploy until we implemented proper shutdown.

The Pattern

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

app.Lifetime.ApplicationStopping.Register(() =>
{
    // Stop accepting new work
    _healthCheck.MarkNotReady();
});

Kubernetes Alignment

  • terminationGracePeriodSeconds: 30
  • preStop sleep 5s (remove from endpoints before drain)
  • App drain: wait for in-flight HTTP to complete (max 25s)
  • Force kill at 30s

Readiness probe must flip before SIGTERM for zero-downtime rolls. The preStop hook exists because endpoint updates lag behind the signal.

reliability , aspnetcore , kubernetes · .NET , Kubernetes

More in Backend Engineering