This post was originally published in Portuguese on my blog: Health checks: liveness e readiness no ASP.NET Core.
We've all shipped a service that answered 200 on the health endpoint while Redis was down. Or, worse, an orchestrator that restarted the container in a loop because the health check depended on the database and the database got slow for two minutes. Both problems have the same root: a single "is it healthy?" trying to answer two different questions.
Two questions, two endpoints
The core idea is to separate liveness from readiness. Liveness asks whether the process is up and not stuck; if the answer is no, restarting fixes it. Readiness asks whether this instance can receive traffic right now; if the answer is no, the right move is to take the instance out of the load balancer and wait, without restarting anything. An external dependency being down is a readiness problem, never a liveness one.
In ASP.NET Core you solve this with tags. Each check is registered with the live or ready tag, and each endpoint filters by them:
builder.Services.AddHealthChecks() .AddCheck("self", () => HealthCheckResult.Healthy(), tags: ["live"]) .AddCheck<RedisHealthCheck>("redis", tags: ["ready"]) .AddCheck<WarmupHealthCheck>("warmup", tags: ["ready"]); The self check doesn't query anything: it only proves the HTTP pipeline is responding. redis and warmup, on the other hand, only count for readiness. The endpoint mapping uses Predicate to choose which checks run on each route:
app.MapHealthChecks("/health/live", new HealthCheckOptions { Predicate = check => check.Tags.Contains("live") }); app.MapHealthChecks("/health/ready", new HealthCheckOptions { Predicate = check => check.Tags.Contains("ready"), ResponseWriter = HealthResponseWriter.WriteAsync }); Notice that /health/live has no ResponseWriter: it returns just the default text and the status code, which is all the orchestrator needs. /health/ready, on the other hand, returns a JSON with the state of each check, which is handy for whoever is debugging. HealthResponseWriter only shows name, status, description and duration, and deliberately leaves the exception out, so infrastructure host and port don't leak to whoever calls the endpoint.
A Redis check with no packages
To keep the example small and easy to run, RedisHealthCheck doesn't use a Redis client: it opens a TcpClient, sends a PING and waits for a +PONG. In production you'd probably reuse the connection the application already has, but the design of the check is the same.
using var client = new TcpClient(); await client.ConnectAsync(settings.Host, settings.Port, timeout.Token); var stream = client.GetStream(); await stream.WriteAsync("PING\r\n"u8.ToArray(), timeout.Token); var buffer = new byte[16]; var read = await stream.ReadAsync(buffer, timeout.Token); var reply = Encoding.ASCII.GetString(buffer, 0, read); The most important part is at the end of the method: the Stopwatch measures the response time and, if it goes over DegradedAfter, the result becomes Degraded instead of Healthy. And any failure becomes Unhealthy, as long as the cancellation didn't come from the caller:
return stopwatch.Elapsed > settings.DegradedAfter ? HealthCheckResult.Degraded($"Redis answered in {stopwatch.ElapsedMilliseconds} ms") : HealthCheckResult.Healthy($"Redis answered in {stopwatch.ElapsedMilliseconds} ms"); } catch (Exception exception) when (!cancellationToken.IsCancellationRequested) { return HealthCheckResult.Unhealthy("Redis is unreachable", exception); } By default, Degraded still returns 200. That's on purpose: a slow Redis is a reason to alert, not to pull the instance out of the load balancer.
Testing without a real Redis
The tests don't depend on any external service. FakeRedisServer is a TcpListener that answers with whatever reply and delay the test asks for, and WebApplicationFactory swaps the options via ConfigureTestServices. Each test creates its own factory, so the WarmupState doesn't leak from one test to another. This is the slow Redis case:
[Fact] public async Task Ready_ReportsDegraded_ButStillReturnsOk_WhenRedisIsSlow() { using var redis = new FakeRedisServer(delay: TimeSpan.FromMilliseconds(300)); using var factory = CreateFactory(redis.Port, warmedUp: true, degradedAfter: TimeSpan.FromMilliseconds(50)); using var client = factory.CreateClient(); var response = await client.GetAsync("/health/ready"); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("Degraded", await ReadStatusAsync(response)); } The other tests cover liveness with Redis down (200), healthy readiness (200), readiness with Redis down (503), readiness during warmup (503), and a guarantee that the body contains neither SocketException nor the Redis address.
Running it with Docker
docker-compose.yml brings up the application and a Redis. The simulated warmup lasts 10 seconds, so you can see readiness returning 503 right after startup:
services: app: build: context: . target: app environment: Redis__Host: redis Warmup__Delay: "00:00:10" ports: - "8080:8080" depends_on: - redis docker compose up --build curl -i http://localhost:8080/health/ready # 503 for the first 10 seconds curl -i http://localhost:8080/health/ready # 200 after warmup docker compose stop redis curl -i http://localhost:8080/health/ready # 503, with redis as Unhealthy curl -i http://localhost:8080/health/live # still 200 To run the tests: docker compose run --rm tests.
Wrapping up
On Kubernetes, /health/live becomes the livenessProbe and /health/ready becomes the readinessProbe; on other orchestrators the logic is the same. The rule of thumb I take from this: if a dependency failure isn't fixed by restarting your process, it doesn't belong in liveness.
The full project, with tests, Dockerfile and compose, is at github.com/dunirvana/programero-csharp.

