ASP.NET Core  

ASP.NET Core Health Checks and Monitoring with Prometheus + Grafana

🔍 Introduction

In modern cloud-native applications, health monitoring is crucial for maintaining uptime, detecting failures early, and ensuring smooth operations.
ASP.NET Core provides a built-in Health Checks framework that integrates seamlessly with tools like Prometheus and Grafana for comprehensive monitoring and visualization.

In this article, we’ll cover:

  • Setting up Health Checks in ASP.NET Core

  • Exposing metrics to Prometheus

  • Visualizing data in Grafana

⚙️ Step 1: Setting Up Health Checks in ASP.NET Core

ASP.NET Core offers an extensible API for creating and monitoring health endpoints.

✅ Install the Required NuGet Packages

dotnet add package Microsoft.Extensions.Diagnostics.HealthChecks
dotnet add package AspNetCore.HealthChecks.UI
dotnet add package AspNetCore.HealthChecks.Prometheus

🧠 Step 2: Configure Health Checks in Program.cs

var builder = WebApplication.CreateBuilder(args);

// Register Health Checks
builder.Services.AddHealthChecks()
    .AddSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"), name: "SQL Server")
    .AddRedis(builder.Configuration["Redis:ConnectionString"], name: "Redis")
    .AddCheck("CustomCheck", () =>
    {
        var healthy = true; // You can add custom logic here
        return healthy
            ? HealthCheckResult.Healthy("Everything is OK")
            : HealthCheckResult.Unhealthy("Something went wrong");
    });

var app = builder.Build();

// Map health endpoints
app.MapHealthChecks("/health");
app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
    Predicate = check => check.Tags.Contains("ready")
});
app.MapHealthChecks("/health/live", new HealthCheckOptions
{
    Predicate = _ => false
});

// Prometheus endpoint
app.MapMetrics(); // For Prometheus scraping

app.Run();

🧩 Explanation

  • /health → General endpoint for all health checks

  • /health/ready → Readiness probe for Kubernetes

  • /health/live → Liveness probe for container status

  • /metrics → Prometheus metrics endpoint

📦 Step 3: Exposing Metrics to Prometheus

Prometheus can scrape data from your ASP.NET Core app via the /metrics endpoint.

🐳 Example Prometheus Configuration (prometheus.yml)

global:
  scrape_interval: 5s

scrape_configs:
  - job_name: 'aspnetcore_app'
    static_configs:
      - targets: ['host.docker.internal:5000']

Then run Prometheus with Docker:

docker run -d -p 9090:9090 -v ./prometheus.yml:/etc/prometheus/prometheus.yml prom/prometheus

Prometheus will start scraping data from your ASP.NET Core app every 5 seconds.

📊 Step 4: Visualizing Metrics with Grafana

Grafana provides beautiful dashboards for monitoring metrics collected by Prometheus.

▶️ Run Grafana via Docker

docker run -d -p 3000:3000 grafana/grafana

➕ Add Prometheus as a Data Source

  1. Open Grafana → Settings → Data Sources → Add new

  2. Select Prometheus

  3. Set the URL: http://host.docker.internal:9090

  4. Save & Test

📈 Create a Dashboard

  • Add a new panel.

  • Query metrics such as:

    • http_requests_received_total

    • dotnet_gc_heap_size_bytes

    • dotnet_total_memory_bytes

    • aspnetcore_healthcheck_status

You can visualize request rates, memory usage, GC stats, and health statuses.

🧩 Step 5: Kubernetes Integration (Optional)

Health checks integrate seamlessly with Kubernetes liveness and readiness probes:

livenessProbe:
  httpGet:
    path: /health/live
    port: 80
  initialDelaySeconds: 30
  periodSeconds: 10

readinessProbe:
  httpGet:
    path: /health/ready
    port: 80
  initialDelaySeconds: 5
  periodSeconds: 10

This ensures your container is only marked as ready when the app is fully operational.

🚨 Step 6: Alerting and Thresholds

You can configure Prometheus alert rules for proactive notifications.

Example

groups:
  - name: HealthAlerts
    rules:
      - alert: AppUnhealthy
        expr: aspnetcore_healthcheck_status{status="Unhealthy"} > 0
        for: 1m
        labels:
          severity: critical
        annotations:
          summary: "Application is unhealthy"

Integrate with tools like Slack, PagerDuty, or Email for real-time alerts.

🚀 Benefits of ASP.NET Core Health Checks with Prometheus + Grafana

  • ✅ Real-time insight into system health

  • ✅ Unified monitoring for microservices

  • ✅ Scalable and extensible monitoring architecture

  • ✅ Easy integration with container orchestration tools

  • ✅ Customizable dashboards for teams and management

🧭 Conclusion

By integrating ASP.NET Core Health Checks with Prometheus and Grafana, you create a robust observability layer that improves system reliability and visibility.

This setup not only helps detect issues early but also enables data-driven performance optimization across environments.