Course contentsShow
← C#
Lesson 1834 of 1,90817. Deployment and Cloud ArchitectureFree lesson

Health Check Integration via ASP.NET Core Middleware

Implement and expose live health probes for orchestration frameworks like Kubernetes.

In this lesson, you will learn how to bridge your custom health logic with container orchestration platforms like Kubernetes using ASP.NET Core middleware.

When running applications in a cluster, the orchestrator needs to know if your pod is healthy (liveness) or ready to accept traffic (readiness). Rather than writing complex custom listeners, we leverage the built-in ASP.NET Core health check middleware, which maps your IHealthCheck implementations to specific HTTP endpoints.

Configuring the Middleware Pipeline

To expose these probes, you must register the service and map the endpoints in your Program.cs. Kubernetes probes are typically configured to look for specific paths (like /healthz or /ready).

// 1. Register health checks in the DI container
builder.Services.AddHealthChecks()
    .AddCheck<DatabaseHealthCheck>("sql-db")
    .AddCheck<ExternalApiHealthCheck>("payment-gateway");

var app = builder.Build();

// 2. Map endpoints to middleware
app.MapHealthChecks("/healthz/live", new HealthCheckOptions {
    Predicate = _ => false // Liveness: Is the process alive?
});

app.MapHealthChecks("/healthz/ready", new HealthCheckOptions {
    Predicate = check => check.Tags.Contains("ready") // Readiness: Is it ready for traffic?
});

The Kubernetes Integration Pattern

By defining Predicate logic, you differentiate between a simple "is the process running" check and a "are my dependencies ready" check.

  • Liveness Probes: The orchestrator uses these to kill and restart unresponsive containers. Keep these lightweight; if your liveness check performs a deep database query that times out, you might trigger a "death spiral" where the cluster constantly restarts your pods.
  • Readiness Probes: The orchestrator uses these to stop sending traffic to a pod during startup or when it is overloaded. This is where you include your IHealthCheck logic regarding database availability and external service connectivity.

When the middleware executes, it runs your registered checks and returns a 200 OK (Healthy), 503 Service Unavailable (Unhealthy), or 400-range codes depending on the state. Orchestrators interpret these codes to decide whether to route traffic or restart the instance.

Key Takeaway: Decouple your liveness and readiness probes using middleware predicates to ensure the orchestrator only restarts containers that are truly broken, rather than those waiting on external dependencies.