LESSON 9 OF 20

9. Health Checks and Health Monitoring with the Aspire Dashboard

In this lesson, you will monitor microservice liveness and readiness, check SQL Server, Redis, and RabbitMQ dependencies, and interpret the results in the Aspire Dashboard.

45 dk 23

Introduction

In a distributed system, a running process is not necessarily ready to receive traffic. For example, the Catalog service may be running while its SQL Server connection is unavailable. Redis may still be starting, or RabbitMQ may have lost its connection. In these situations, checking only whether the process exists is not enough.

This lesson uses ASP.NET Core health checks to distinguish between liveness and readiness. Liveness indicates whether the application process is still responsive. Readiness indicates whether the application is ready to receive traffic together with its required dependencies. We will then connect these checks to the Aspire application model and inspect the results through the Aspire Dashboard.

Our example assumes that Catalog, Order, and Inventory services depend on resources such as SQL Server, Redis, and RabbitMQ. The goal is not to check every dependency indiscriminately, but to design checks that accurately represent the service's operating conditions.

Health check concepts

Liveness versus readiness

A liveness check answers this question: “Is the application still running?” It normally validates the process, its basic execution loop, or a lightweight self-check. If liveness fails, an orchestrator may consider restarting the service.

A readiness check answers a different question: “Is the application ready to receive traffic?” If a database, cache, message broker, or startup operation is unavailable, the service may be running but not ready. When readiness fails, stopping new traffic is usually preferable to immediately restarting the process.

CheckMeaningTypical response to failure
LivenessIs the process responsive?Consider restarting the process.
ReadinessIs the service ready with its dependencies?Temporarily stop sending traffic.

The common Aspire approach uses /health for readiness and /alive for liveness. Keeping these concepts separate also makes a later transition to platforms such as Kubernetes easier.

Adding ASP.NET Core health checks

Start by registering health checks in the service project. The following example uses the minimal hosting model in an ASP.NET Core Web API application:

using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.Diagnostics.HealthChecks;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddHealthChecks()
    .AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]);

var app = builder.Build();

app.MapControllers();

app.MapHealthChecks("/health");
app.MapHealthChecks("/alive", new HealthCheckOptions
{
    Predicate = check => check.Tags.Contains("live")
});

app.Run();

The self check is registered with the live tag. Therefore, /alive executes this check. The /health endpoint has no predicate, so it executes all registered checks. Dependency checks consequently become part of readiness.

In a real solution, avoid duplicating this configuration in every service. A shared ServiceDefaults project can contain common extension methods. However, each service still needs to expose the health endpoints in its own HTTP pipeline.

Checking SQL Server, Redis, and RabbitMQ

SQL Server

A SQL Server check should verify more than an open TCP port. It should confirm that the application can actually connect to the database. When the Aspire SQL Server client integration is used, the integration can provide connection, telemetry, and health check configuration. Ensure that the client integration package and connection string configuration match the resource name used by the AppHost.

builder.Services.AddHealthChecks()
    .AddCheck("self", () => HealthCheckResult.Healthy(), ["live"])
    .AddSqlServer(
        connectionString: builder.Configuration.GetConnectionString("catalogdb")!,
        name: "sqlserver",
        tags: ["ready"]);

The required health check package must be installed in the service project. If the Aspire client integration already registers the SQL Server check, do not register an identical check a second time. Otherwise, the Dashboard may display duplicate dependency entries.

Redis

A Redis check verifies that the cache server is reachable. Redis is often not the system of record, so you must decide whether the service can safely operate without it. In this lesson, Redis is treated as a readiness dependency:

builder.Services.AddHealthChecks()
    .AddRedis(
        connectionString: builder.Configuration.GetConnectionString("cache")!,
        name: "redis",
        tags: ["ready"]);

If the application can safely operate without the cache, you may keep the Redis check outside readiness and expose it as a separate diagnostic check. For a critical Order or Inventory service, however, including Redis in readiness may be appropriate if the cache is required for correct operation.

RabbitMQ

A RabbitMQ check should verify that the broker can be reached and that a channel can be created. The Aspire RabbitMQ client integration can register this check automatically. With manual registration, the check can be added as follows:

builder.Services.AddHealthChecks()
    .AddRabbitMQ(
        rabbitConnectionString: builder.Configuration.GetConnectionString("messaging")!,
        name: "rabbitmq",
        tags: ["ready"]);

A successful broker connection does not prove that message consumers are functioning. The connection may work while a background consumer service has failed to start. For critical consumers, add an application-specific IHealthCheck or expose a state maintained by the consumer.

Creating a shared registration method

To avoid repeating the same configuration in multiple services, create a shared extension method. The following example skips a check when its connection string is missing. In production, you may instead want a missing required setting to prevent the application from starting.

public static class HealthCheckExtensions
{
    public static IServiceCollection AddApplicationHealthChecks(
        this IServiceCollection services,
        IConfiguration configuration)
    {
        var checks = services.AddHealthChecks()
            .AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]);

        var sql = configuration.GetConnectionString("catalogdb");
        if (!string.IsNullOrWhiteSpace(sql))
        {
            checks.AddSqlServer(sql, name: "sqlserver", tags: ["ready"]);
        }

        var redis = configuration.GetConnectionString("cache");
        if (!string.IsNullOrWhiteSpace(redis))
        {
            checks.AddRedis(redis, name: "redis", tags: ["ready"]);
        }

        var rabbit = configuration.GetConnectionString("messaging");
        if (!string.IsNullOrWhiteSpace(rabbit))
        {
            checks.AddRabbitMQ(rabbit, name: "rabbitmq", tags: ["ready"]);
        }

        return services;
    }
}

Call builder.Services.AddApplicationHealthChecks(builder.Configuration) from Program.cs. The essential design is that the self check has the liveness tag, while external dependencies have the readiness tag.

Connecting endpoints in the Aspire AppHost

Once the service endpoints are available, the AppHost can monitor the service readiness endpoint over HTTP. The Catalog API can be modeled as follows:

var builder = DistributedApplication.CreateBuilder(args);

var sql = builder.AddSqlServer("sql")
    .AddDatabase("catalogdb");

var redis = builder.AddRedis("cache");
var rabbit = builder.AddRabbitMQ("messaging");

var catalogApi = builder.AddProject<Projects.CatalogApi>("catalog-api")
    .WithReference(sql)
    .WithReference(redis)
    .WithReference(rabbit)
    .WithHttpHealthCheck("/health")
    .WaitFor(sql)
    .WaitFor(redis)
    .WaitFor(rabbit);

builder.Build().Run();

WithHttpHealthCheck("/health") tells the AppHost to monitor the service readiness endpoint. WaitFor controls startup ordering and waits for a resource or dependency to become ready. These concepts are related but not identical: the AppHost observes resource readiness for orchestration, while the service endpoint communicates the application's own readiness decision.

When hosting integrations for SQL Server, Redis, and RabbitMQ are used, the health state of those resources is also available in the Dashboard. The API's HTTP health check adds another layer: it shows whether the API is ready together with its dependencies.

Reading the Aspire Dashboard

When the AppHost runs, the Resources view lists projects, containers, and infrastructure resources. Do not interpret “Running” as automatically meaning “Healthy.” A container may be running while its health check is failing.

  1. Open the Resources view: Locate the Catalog API, SQL Server, Redis, and RabbitMQ resources.
  2. Inspect the State column: Distinguish starting, running, waiting, and error states.
  3. Open health details: Read the name and message of the failed check.
  4. Review the dependency graph: Confirm that references between the API and resources are correct.
  5. Inspect logs and traces: Determine whether the failure is caused by connectivity, authentication, or a timeout.

For example, if Redis is running but the Catalog API's redis check fails, verify that the connection string resolves correctly from inside the service container or process. For RabbitMQ, check the username, password, virtual host, and port. For SQL Server, remember that the existence of a database does not prove that the application is using the correct connection string.

Writing a custom health check

Built-in integration checks are sufficient for many infrastructure dependencies. When you need to verify application-specific startup or background processing, implement IHealthCheck:

public sealed class MessageConsumerHealthCheck : IHealthCheck
{
    private readonly ConsumerState _state;

    public MessageConsumerHealthCheck(ConsumerState state)
    {
        _state = state;
    }

    public Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context,
        CancellationToken cancellationToken = default)
    {
        return Task.FromResult(
            _state.IsRunning
                ? HealthCheckResult.Healthy("Consumer is running")
                : HealthCheckResult.Unhealthy("Consumer is not running"));
    }
}

Register it as a readiness check:

builder.Services.AddSingleton<ConsumerState>();
builder.Services.AddHealthChecks()
    .AddCheck<MessageConsumerHealthCheck>(
        "message-consumer",
        tags: ["ready"]);

Custom checks should not generate excessive traffic to remote systems. Add sensible timeouts, keep them fast, and never include secrets in failure messages.

Common mistakes

  • Putting every dependency in liveness: Restarting a process because a database is temporarily unavailable can create a restart loop.
  • Checking only a port: An open port does not guarantee valid credentials, a correct database name, or a usable broker channel.
  • Publishing health endpoints without protection: In production, evaluate authorization, host filtering, and other access controls.
  • Running expensive queries: Health checks should be fast and bounded by timeouts.
  • Treating every resource as mandatory: Do not mark a service not ready because of an optional cache or broker.
  • Confusing Running with Healthy: Process state and application readiness are different signals.

Practice exercise

Apply the following exercise to the Order API:

  1. Add /health and /alive endpoints.
  2. Register SQL Server, Redis, and RabbitMQ checks with the ready tag.
  3. Add WithHttpHealthCheck("/health") to the Order API in the AppHost.
  4. Stop the RabbitMQ container and observe which resources become not ready in the Dashboard.
  5. Start RabbitMQ again and wait for the status to return to Healthy.
  6. Temporarily move the RabbitMQ check to the liveness tag and explain the behavioral difference.

Finally, answer this question: when RabbitMQ is unavailable, should the entire Order API stop receiving traffic, or should only messaging features be disabled? The answer depends on the service boundary and business requirements.

Conclusion

Health checks in distributed systems answer more than “Is the application running?” Separating liveness from readiness allows restart decisions and traffic-routing decisions to remain independent. SQL Server, Redis, and RabbitMQ can contribute to service readiness, while the Aspire AppHost manages resource startup and service endpoint monitoring through one application model.

In later lessons, we will evaluate these health signals together with logs, metrics, and distributed traces. This makes the Dashboard useful not only for seeing whether a resource is running, but also for understanding why the system became unhealthy.

Sources