Lesson 4 of 9
Graceful Shutdown & Health Checks
Graceful shutdown ensures in-flight requests complete when Kubernetes sends SIGTERM. Health checks (/health/live and /health/ready) tell the load balancer when the pod is ready to serve traffic - preventing requests from being routed to a starting-up or shutting-down pod.
Liveness, Readiness & Health Check Configuration
using Microsoft.Extensions.Diagnostics.HealthChecks;
// ━━ Health checks registration ━━
builder.Services
.AddHealthChecks()
// Database health - is SQL Server reachable and responding?
.AddSqlServer(
connectionString: builder.Configuration.GetConnectionString("DefaultConnection")!,
healthQuery: "SELECT 1",
name: "sql-server",
failureStatus: HealthStatus.Unhealthy,
tags: ["ready"]) // only on readiness probe
// Redis health
.AddRedis(
builder.Configuration.GetConnectionString("Redis")!,
name: "redis",
failureStatus: HealthStatus.Degraded, // degraded ≠ unhealthy - app still works without cache
tags: ["ready"])
// Custom health check - business-level check
.AddCheck<OrderQueueHealthCheck>(
"order-queue",
failureStatus: HealthStatus.Degraded,
tags: ["ready"])
// Disk space - liveness
.AddDiskStorageHealthCheck(
setup => setup.AddDrive("C:\", minimumFreeMegabytes: 512),
name: "disk-space",
tags: ["live"]);
// ━━ Map health endpoints ━━
app.MapHealthChecks("/health", new HealthCheckOptions
{
// Aggregate: Healthy if ALL checks pass
ResponseWriter = WriteHealthReport
});
app.MapHealthChecks("/health/live", new HealthCheckOptions
{
// Liveness: only "live" tagged checks - is the process alive?
Predicate = check => check.Tags.Contains("live"),
ResponseWriter = WriteHealthReport
});
app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
// Readiness: only "ready" tagged checks - can the pod serve traffic?
Predicate = check => check.Tags.Contains("ready"),
ResponseWriter = WriteHealthReport
});
// ━━ Pretty JSON health report ━━
static Task WriteHealthReport(HttpContext ctx, HealthReport report)
{
ctx.Response.ContentType = "application/json";
var result = new
{
status = report.Status.ToString(),
checks = report.Entries.Select(e => new
{
name = e.Key,
status = e.Value.Status.ToString(),
description = e.Value.Description,
duration = e.Value.Duration.TotalMilliseconds
}),
totalDuration = report.TotalDuration.TotalMilliseconds
};
return ctx.Response.WriteAsJsonAsync(result);
}
// ━━ Custom health check ━━
public class OrderQueueHealthCheck(IBackgroundTaskQueue queue)
: IHealthCheck
{
public Task<HealthCheckResult> CheckHealthAsync(
HealthCheckContext context, CancellationToken ct = default)
{
var depth = queue.Count;
return Task.FromResult(
depth < 1000
? HealthCheckResult.Healthy($"Queue depth: {depth}")
: HealthCheckResult.Degraded($"Queue backlog high: {depth} items"));
}
}
// ━━ Graceful shutdown ━━
builder.Services.Configure<HostOptions>(options =>
{
options.ShutdownTimeout = TimeSpan.FromSeconds(30); // wait up to 30s for in-flight requests
});
// On SIGTERM (Kubernetes pod stop):
// 1. Kubernetes sends SIGTERM
// 2. App stops accepting new requests (Kestrel drain)
// 3. In-flight requests complete (up to 30s)
// 4. BackgroundService.StopAsync is called with CancellationToken
// 5. Process exits cleanly
app.Lifetime.ApplicationStopping.Register(() =>
{
Console.WriteLine("Application is shutting down gracefully...");
});
interface IBackgroundTaskQueue { int Count { get; } }
interface IApplicationBuilder { Microsoft.AspNetCore.Hosting.IApplicationLifetime Lifetime { get; } }
interface IApplicationLifetime { System.Threading.CancellationToken ApplicationStopping { get; } }
IApplicationBuilder app = null!;Tip
Tip
Practice Graceful Shutdown Health Checks in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
.NET provides a unified platform for building various application types
Practice Task
Note
Practice Task - (1) Write a working example of Graceful Shutdown Health Checks from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Graceful Shutdown Health Checks is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.
Finished this lesson?