Kubernetes supports a distinct startupProbe specifically for slow-starting containers, giving the application a longer grace period during initial startup before liveness probing begins (preventing Kubernetes from prematurely killing a container still legitimately warming up) -- implemented in ASP.NET Core by tagging a set of checks representing 'has initial startup work completed' (like cache pre-loading, initial data sync) and exposing them at a separate /health/startup endpoint, distinct from the ongoing /health/live and /health/ready endpoints used after startup completes.
public class StartupCompleteHealthCheck : IHealthCheck {
public static volatile bool IsStartupComplete = false;
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken ct = default) {
return Task.FromResult(IsStartupComplete ? HealthCheckResult.Healthy() : HealthCheckResult.Unhealthy("Still warming up"));
}
}
// A hosted service sets IsStartupComplete = true once cache warming finishes
app.MapHealthChecks("/health/startup", new HealthCheckOptions { Predicate = c => c.Tags.Contains("startup") });
Real-world example
A service with a multi-minute in-memory cache warm-up on startup configures a Kubernetes startupProbe against /health/startup with a generous timeout, preventing Kubernetes from repeatedly killing and restarting the pod during legitimate slow startup, while the separate liveness probe only begins once startup genuinely completes.
Likely follow-ups
How does the startupProbe's failureThreshold interact with the subsequent livenessProbe once startup succeeds?
What's the risk of not having a separate startup probe for a genuinely slow-starting service?
Using WebApplicationFactory, override the DI registration for the dependency being tested (replacing a real database connection with a fake that simulates a failure) via ConfigureTestServices, then issue a request to /health via the test client and assert both the HTTP status code (503 for Unhealthy by default) and, if using a custom JSON response writer, the specific failing check's name in the response body.
public class HealthCheckTests : IClassFixture<WebApplicationFactory<Program>> {
[Fact]
public async Task Health_ReturnsUnhealthy_WhenDatabaseDown() {
var factory = _factory.WithWebHostBuilder(builder => {
builder.ConfigureTestServices(services => {
services.AddHealthChecks().AddCheck("database", () => HealthCheckResult.Unhealthy());
});
});
var client = factory.CreateClient();
var response = await client.GetAsync("/health");
Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode);
}
}
Real-world example
A test suite verifies the /health endpoint correctly returns a 503 status when a simulated database check fails, giving confidence the health check wiring itself is correct before relying on it in a production Kubernetes deployment.
Likely follow-ups
How would you test the interaction between multiple health checks with mixed Healthy/Degraded/Unhealthy statuses?
Should health check logic itself have unit tests separate from this integration-level test?
By default, HealthStatus.Healthy and HealthStatus.Degraded both map to a 200 OK response, while HealthStatus.Unhealthy maps to a 503 Service Unavailable response -- this default mapping can be customized via HealthCheckOptions.ResultStatusCodes if a different status code scheme is needed, but the built-in defaults are designed so load balancers and orchestrators can rely on a simple 200-versus-503 distinction without needing to parse a response body.
A load balancer configured to simply check for a 200 status code from /health automatically stops routing traffic to an instance once its status turns Unhealthy and the endpoint starts returning 503, without needing any custom logic to parse a JSON response body.
Likely follow-ups
Why might you want Degraded to also return a non-200 status in some scenarios?
How do downstream consumers typically differentiate their response to a 503 versus inspecting a detailed JSON body?
Since health endpoints are typically polled very frequently by automated infrastructure (every few seconds by a load balancer or orchestrator), it's common to exclude them from middleware not relevant to that traffic -- achieved by ordering MapHealthChecks appropriately relative to other middleware registrations, or by explicitly checking and skipping the health check path within custom middleware, preventing noisy logs or unnecessary rate-limit consumption from routine health polling.
A team notices their centralized logging system is flooded with thousands of routine health-check log entries per hour, and fixes it by wrapping their logging middleware in UseWhen to skip the /health path entirely, dramatically reducing log noise without losing any meaningful observability.
Likely follow-ups
What other middleware commonly needs similar exclusion for health check paths (rate limiting, authentication)?
How do you balance excluding noise against still wanting to detect abnormal health-check-related traffic patterns?
Register each dependency as a separate named IHealthCheck (database, cache, message queue, external API), letting the built-in HealthCheckService automatically aggregate their statuses into a single overall status using worst-case precedence (Unhealthy > Degraded > Healthy) for the top-level response code, while a custom ResponseWriter exposes the full per-check breakdown in the JSON body -- giving both a simple binary signal for infrastructure (load balancer) and detailed diagnostics for humans investigating an issue, from the exact same underlying check registrations.
builder.Services.AddHealthChecks()
.AddCheck<DatabaseHealthCheck>("database")
.AddCheck<RedisHealthCheck>("cache")
.AddCheck<MessageQueueHealthCheck>("queue");
// Overall status = worst of the three; JSON body via custom ResponseWriter shows each individually
app.MapHealthChecks("/health", new HealthCheckOptions { ResponseWriter = WriteDetailedJson });
Real-world example
An operations dashboard shows an API's overall status as Unhealthy at a glance (driven by worst-case aggregation), while a detailed drill-down view built from the same health check registrations pinpoints that specifically the message queue check is failing while database and cache remain healthy.
Likely follow-ups
How does the aggregation logic handle a mix of Degraded and Unhealthy results across different checks?
Would you ever want a non-worst-case aggregation strategy, and when?