| Memory-Management-GC :👈 | 👉:Building-Cloud-Native-Core-Applications |
ASP.NET Core Health Checks, Readiness and Liveness Probes |
ASP.NET Core Health Checks, Readiness and Liveness Probes
1. Introduction
Health checks help us determine whether an ASP.NET Core application and its dependencies are functioning correctly.
In production environments, simply knowing that an application is running is not enough. We also need to know whether it can accept requests and communicate with required services such as databases, Redis, RabbitMQ, and external APIs.
ASP.NET Core provides a built-in Health Checks framework to monitor application health.
Why do we need health checks?
- Determine whether an application is running.
- Determine whether an application can accept traffic.
- Check database connectivity.
- Monitor Redis, RabbitMQ, and other dependencies.
- Support Kubernetes container orchestration.
- Support load balancer health monitoring.
- Improve microservices monitoring.
- Detect failures and help automate recovery.
2. What Is a Health Check?
A health check is an endpoint that reports the current health status of an application.
For example:
GET /health
A successful response might look like:
Healthy
A health check can also return a structured response containing information about individual dependencies.
Basic health check flow
3. Types of Health Checks
There are three important health concepts used in production applications:
- Liveness Probe
- Readiness Probe
- Startup Probe
4. Liveness Probe
A liveness probe determines whether an application process is alive and should continue running.
It answers this question:
Is the application still running, or is it stuck in a state from which it cannot recover?
Example
Imagine an ASP.NET Core application running inside a Kubernetes pod.
The application process becomes stuck because of an internal problem. It is no longer able to make progress.
Kubernetes checks the liveness endpoint. If the probe repeatedly fails, Kubernetes can restart the container.
Liveness endpoint
GET /health/live
Expected response:
HTTP 200 OK
Healthy
Important considerations
- Liveness should primarily check whether the application process is functioning.
- Do not normally include database or external service checks.
- A temporary database outage should not automatically cause the application to restart.
- Keep liveness checks lightweight and reliable.
5. Readiness Probe
A readiness probe determines whether an application is ready to receive traffic.
It answers this question:
Can this application instance safely handle incoming requests right now?
Example
Imagine a new ASP.NET Core pod has started.
The application process is running, but it is still loading configuration or establishing required connections.
During this period, the application should not receive normal traffic.
Once initialization is complete and required dependencies are available, the readiness endpoint returns healthy.
Readiness endpoint
GET /health/ready
Readiness checks may include
- Database connectivity.
- Required configuration initialization.
- Required message broker connectivity.
- Required external service availability.
- Application initialization completion.
Only include dependencies whose availability is genuinely necessary for the application to serve its intended traffic.
6. Startup Probe
A startup probe determines whether an application has completed its startup process.
It is useful for applications that take a long time to initialize.
For example, an application might need to:
- Load configuration.
- Initialize required components.
- Load machine learning models.
- Perform initial application setup.
Kubernetes can delay liveness and readiness checks until the startup probe succeeds.
7. Difference Between Liveness, Readiness and Startup
| Feature | Liveness | Readiness | Startup |
|---|---|---|---|
| Purpose | Checks whether the application is alive. | Checks whether the application can receive traffic. | Checks whether initialization is complete. |
| Endpoint example | /health/live | /health/ready | /health/startup |
| Database check | Normally no. | When required for serving traffic. | Only if required for startup. |
| Failure action | May restart container. | Removes instance from service traffic. | May restart container after configured failures. |
| Primary concern | Process health. | Traffic eligibility. | Initialization. |
Visual comparison
8. Implementing Health Checks in ASP.NET Core
ASP.NET Core includes health check support through the Microsoft.Extensions.Diagnostics.HealthChecks framework.
For a standard ASP.NET Core Web API project, health check services can be registered using the built-in dependency injection system.
Step 1: Register health checks
In Program.cs:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddHealthChecks();
var app = builder.Build();
app.MapControllers();
app.MapHealthChecks("/health");
app.Run();
Step 2: Run the application
dotnet run
Step 3: Test the endpoint
GET https://localhost:5001/health
The health check endpoint returns HTTP 200 when the registered checks report healthy.
9. Configure Separate Liveness and Readiness Endpoints
In a production application, it is better to expose separate endpoints for different probe purposes.
Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHealthChecks();
var app = builder.Build();
// Liveness: checks whether the application is running.
app.MapHealthChecks("/health/live", new HealthCheckOptions
{
Predicate = check => check.Tags.Contains("live")
});
// Readiness: checks whether required dependencies are available.
app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
Predicate = check => check.Tags.Contains("ready")
});
app.Run();
In this example, we use tags to decide which health checks run for each endpoint.
We must register checks with the corresponding tags. Otherwise, the endpoints may not execute the intended checks.
10. Add Custom Health Checks
Sometimes we need to check application-specific conditions that are not covered by built-in health checks.
For example:
- Whether a required configuration has loaded.
- Whether an internal background service is operational.
- Whether an important initialization process has completed.
- Whether a required local resource is available.
Create a custom health check
using Microsoft.Extensions.Diagnostics.HealthChecks;
public class ApplicationHealthCheck : IHealthCheck
{
public Task<HealthCheckResult> CheckHealthAsync(
HealthCheckContext context,
CancellationToken cancellationToken = default)
{
bool isHealthy = true;
if (isHealthy)
{
return Task.FromResult(
HealthCheckResult.Healthy(
"Application is functioning."));
}
return Task.FromResult(
HealthCheckResult.Unhealthy(
"Application is not functioning."));
}
}
Register the custom check
builder.Services.AddHealthChecks()
.AddCheck<ApplicationHealthCheck>(
"application",
tags: new[] { "live", "ready" });
Now the custom check can be executed by both endpoints.
11. Database Health Check
In many applications, the database is a critical dependency.
We may need to check whether the application can communicate with SQL Server.
Install the SQL Server health check package
dotnet add package AspNetCore.HealthChecks.SqlServer
Configure the connection string
appsettings.json:
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=MyAppDb;User Id=appuser;Password=YourPassword;TrustServerCertificate=True;"
}
}
Use secure configuration providers for production credentials. Do not commit real database passwords to source control.
Register the SQL Server health check
var connectionString =
builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddHealthChecks()
.AddSqlServer(
connectionString!,
name: "sql-server",
tags: new[] { "ready" });
Now the readiness endpoint can check SQL Server connectivity.
The health check verifies connectivity, not the correctness of every database operation or the availability of all application data.
12. Redis Health Check
If an application depends on Redis, we may also need to monitor Redis connectivity.
Install package
dotnet add package AspNetCore.HealthChecks.Redis
Register Redis health check
var redisConnection =
builder.Configuration.GetConnectionString("Redis");
builder.Services.AddHealthChecks()
.AddRedis(
redisConnection!,
name: "redis",
tags: new[] { "ready" });
This checks whether the application can communicate with Redis using the configured connection.
13. RabbitMQ Health Check
In microservices, RabbitMQ is commonly used for asynchronous communication.
If the application requires RabbitMQ to process or publish messages, its availability may be part of readiness.
One option is to create a custom health check using the RabbitMQ client already used by the application.
Example custom RabbitMQ health check
using Microsoft.Extensions.Diagnostics.HealthChecks;
using RabbitMQ.Client;
public class RabbitMqHealthCheck : IHealthCheck
{
private readonly IConnection _connection;
public RabbitMqHealthCheck(IConnection connection)
{
_connection = connection;
}
public Task<HealthCheckResult> CheckHealthAsync(
HealthCheckContext context,
CancellationToken cancellationToken = default)
{
if (_connection.IsOpen)
{
return Task.FromResult(
HealthCheckResult.Healthy(
"RabbitMQ connection is open."));
}
return Task.FromResult(
HealthCheckResult.Unhealthy(
"RabbitMQ connection is unavailable."));
}
}
Register it using dependency injection:
builder.Services.AddHealthChecks()
.AddCheck<RabbitMqHealthCheck>(
"rabbitmq",
tags: new[] { "ready" });
This example assumes an application-managed RabbitMQ connection registered with the dependency injection container.
For production, use a resilient connection lifecycle and avoid creating a new RabbitMQ connection on every health check request. Also distinguish between connection availability and the ability to publish or consume messages successfully.
14. External API Health Check
Some applications depend on external services such as payment gateways, shipping services, or identity providers.
We can create a custom health check using HttpClient.
Example
public class ExternalApiHealthCheck : IHealthCheck
{
private readonly HttpClient _httpClient;
public ExternalApiHealthCheck(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<HealthCheckResult> CheckHealthAsync(
HealthCheckContext context,
CancellationToken cancellationToken = default)
{
try
{
using var response = await _httpClient.GetAsync(
"/health",
cancellationToken);
if (response.IsSuccessStatusCode)
{
return HealthCheckResult.Healthy(
"External API is available.");
}
return HealthCheckResult.Unhealthy(
"External API returned an unsuccessful response.");
}
catch (Exception)
{
return HealthCheckResult.Unhealthy(
"External API is unavailable.");
}
}
}
Register a named or typed HttpClient and inject it into the health check.
For example:
builder.Services.AddHttpClient<ExternalApiHealthCheck>(
client =>
{
client.BaseAddress =
new Uri("https://example.com");
client.Timeout = TimeSpan.FromSeconds(3);
});
builder.Services.AddHealthChecks()
.AddCheck<ExternalApiHealthCheck>(
"external-api",
tags: new[] { "ready" });
Use a dedicated lightweight health endpoint where possible. Avoid making expensive external calls on every probe.
15. Complete Production-Style Health Check Configuration
The following example combines a liveness check, a custom application readiness check, and a SQL Server readiness check.
Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var connectionString =
builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddHealthChecks()
.AddCheck(
"self",
() => HealthCheckResult.Healthy(
"Application process is responding."),
tags: new[] { "live" })
.AddCheck<ApplicationHealthCheck>(
"application",
tags: new[] { "ready" })
.AddSqlServer(
connectionString!,
name: "sql-server",
tags: new[] { "ready" });
var app = builder.Build();
app.MapControllers();
app.MapHealthChecks("/health/live", new HealthCheckOptions
{
Predicate = check => check.Tags.Contains("live")
});
app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
Predicate = check => check.Tags.Contains("ready")
});
app.Run();
Required namespaces include:
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.Diagnostics.HealthChecks;
Make sure the SQL Server health check package is installed and the connection string is configured.
16. Return JSON Health Check Responses
By default, the health check middleware returns a simple text response.
For monitoring systems and troubleshooting, a structured JSON response may be more useful.
Example response
{
"status": "Healthy",
"results": {
"application": {
"status": "Healthy"
},
"sql-server": {
"status": "Healthy"
}
}
}
Configure JSON response writer
using System.Text.Json;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
static Task WriteHealthResponse(
HttpContext context,
HealthReport report)
{
context.Response.ContentType = "application/json";
var response = new
{
status = report.Status.ToString(),
results = report.Entries.ToDictionary(
entry => entry.Key,
entry => new
{
status = entry.Value.Status.ToString(),
description = entry.Value.Description
})
};
return context.Response.WriteAsync(
JsonSerializer.Serialize(response));
}
Use the response writer when mapping an endpoint:
app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
Predicate = check => check.Tags.Contains("ready"),
ResponseWriter = WriteHealthResponse
});
Security note: Do not expose connection strings, passwords, internal hostnames, exception messages, or other sensitive infrastructure information in publicly accessible health responses.
17. Health Check Status Codes
ASP.NET Core health check middleware supports different status codes based on the health report.
| Health Status | Default HTTP Status | Meaning |
|---|---|---|
| Healthy | 200 | Application checks passed. |
| Degraded | 200 by default | Application is functioning with a warning. |
| Unhealthy | 503 | One or more required checks failed. |
You can configure the status codes explicitly:
app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
Predicate = check => check.Tags.Contains("ready"),
ResultStatusCodes =
{
[HealthStatus.Healthy] = StatusCodes.Status200OK,
[HealthStatus.Degraded] = StatusCodes.Status200OK,
[HealthStatus.Unhealthy] = StatusCodes.Status503ServiceUnavailable
}
});
A degraded result can be treated differently depending on the requirements of your monitoring system.
18. Kubernetes Liveness, Readiness and Startup Probes
Kubernetes uses probes to monitor containers running inside pods.
It supports three main probes:
- livenessProbe: Determines whether a container should be restarted.
- readinessProbe: Determines whether a pod should receive service traffic.
- startupProbe: Determines whether the application has completed startup.
Kubernetes architecture
Kubernetes deployment YAML
apiVersion: apps/v1
kind: Deployment
metadata:
name: aspnet-api
spec:
replicas: 3
selector:
matchLabels:
app: aspnet-api
template:
metadata:
labels:
app: aspnet-api
spec:
containers:
- name: aspnet-api
image: myregistry/aspnet-api:latest
ports:
- containerPort: 8080
startupProbe:
httpGet:
path: /health/startup
port: 8080
periodSeconds: 10
failureThreshold: 30
livenessProbe:
httpGet:
path: /health/live
port: 8080
periodSeconds: 10
timeoutSeconds: 3
failureThreshold: 3
readinessProbe:
httpGet:
path: /health/ready
port: 8080
periodSeconds: 5
timeoutSeconds: 3
failureThreshold: 3
These settings are examples, not universal production values. Tune the periods, timeouts, thresholds, and startup allowance based on actual startup time and service behavior.
Important Kubernetes behavior
- If startup has not succeeded, Kubernetes does not run the liveness and readiness probes.
- If liveness repeatedly fails, Kubernetes restarts the container.
- If readiness fails, the pod is marked not ready and normally stops receiving traffic through its Service.
- A readiness failure does not itself restart the container.
19. Implementing Startup Health Check in ASP.NET Core
A startup check can be based on whether required application initialization has completed.
Example startup state service
public class StartupState
{
private volatile bool _completed;
public bool IsCompleted => _completed;
public void MarkCompleted()
{
_completed = true;
}
}
Register the state
builder.Services.AddSingleton<StartupState>();
builder.Services.AddHealthChecks()
.AddCheck(
"startup",
(StartupState state) =>
state.IsCompleted
? HealthCheckResult.Healthy("Startup complete.")
: HealthCheckResult.Unhealthy("Startup is in progress."),
tags: new[] { "startup" });
The dependency injection overload shown above is available in the health checks registration API. Alternatively, implement IHealthCheck and inject StartupState through its constructor.
Mark initialization as complete
var app = builder.Build();
var startupState =
app.Services.GetRequiredService<StartupState>();
// Perform required initialization here.
// For example, load required configuration or warm up services.
startupState.MarkCompleted();
app.MapHealthChecks("/health/startup", new HealthCheckOptions
{
Predicate = check => check.Tags.Contains("startup")
});
app.Run();
For asynchronous initialization, await the initialization task before marking the application ready. In real applications, avoid putting lengthy initialization directly into a request handler.
20. Health Checks in Docker
Docker can monitor the health of a container using a HEALTHCHECK instruction.
Dockerfile example
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS final
WORKDIR /app
COPY publish/ .
EXPOSE 8080
HEALTHCHECK --interval=30s \
--timeout=5s \
--start-period=30s \
--retries=3 \
CMD curl --fail http://localhost:8080/health/live || exit 1
ENTRYPOINT ["dotnet", "MyApi.dll"]
Important: This example assumes the container image includes curl. Minimal ASP.NET Core images may not include it. You must install a suitable health-check client or use an appropriate alternative for your image.
Docker health status is separate from Kubernetes probe behavior. A Docker HEALTHCHECK alone does not automatically restart a container or remove it from a Kubernetes Service.
21. Health Checks in Microservices Architecture
In microservices, each service should expose health endpoints appropriate to its responsibilities.
For example:
- Order Service checks its required database.
- Payment Service checks its required payment infrastructure.
- Inventory Service checks its required database or inventory dependency.
- Notification Service checks required messaging infrastructure.
Microservices health check architecture
Important microservices considerations
- Do not make one service's liveness depend on every other microservice.
- Include only critical dependencies in readiness.
- Avoid recursive health checks between services.
- Use timeouts to prevent slow dependency checks.
- Do not let a temporary optional-service failure remove every service from traffic.
22. Health Checks and Background Services
Some ASP.NET Core applications run background services using IHostedService or BackgroundService.
For example:
- Message queue consumers.
- Scheduled processing jobs.
- Data synchronization services.
- Background notification workers.
We may need to expose the status of these services through custom health checks.
Example
public class WorkerState
{
public volatile bool IsRunning;
}
public class OrderWorker : BackgroundService
{
private readonly WorkerState _state;
public OrderWorker(WorkerState state)
{
_state = state;
}
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
_state.IsRunning = true;
try
{
while (!stoppingToken.IsCancellationRequested)
{
// Process background work.
await Task.Delay(
TimeSpan.FromSeconds(5),
stoppingToken);
}
}
catch (OperationCanceledException)
when (stoppingToken.IsCancellationRequested)
{
// Normal shutdown.
}
finally
{
_state.IsRunning = false;
}
}
}
Register the worker and state:
builder.Services.AddSingleton<WorkerState>();
builder.Services.AddHostedService<OrderWorker>();
A custom health check can inspect the worker state. In production, define carefully what a worker's healthy state means: running, making progress, connected to its broker, or processing messages successfully are different conditions.
23. Securing Health Check Endpoints
Health endpoints can reveal information about application infrastructure.
Follow these security practices:
- Do not expose sensitive dependency details publicly.
- Return only the information required by the monitoring system.
- Restrict detailed diagnostic endpoints to trusted networks or authorized monitoring systems.
- Use authentication where appropriate for detailed endpoints.
- Do not return connection strings or secrets.
- Use separate public and internal health endpoints when necessary.
Basic liveness endpoints are often exposed to an internal orchestrator, while detailed health reports should have tighter access controls.
24. Common Health Check Mistakes
| Mistake | Why It Is a Problem | Better Approach |
|---|---|---|
| Checking database in liveness | Database outage may cause unnecessary restarts. | Use readiness for required database dependencies. |
| One endpoint for every purpose | Cannot distinguish process health from traffic readiness. | Separate liveness, readiness and startup endpoints. |
| Slow health checks | Probes may time out and create additional load. | Use lightweight checks and timeouts. |
| Checking every external service | Optional dependency failures may remove healthy instances. | Check only dependencies required for serving traffic. |
| Returning sensitive details | Can reveal infrastructure information. | Return safe summaries. |
| Creating new connections per probe | Can cause connection overhead and resource exhaustion. | Reuse managed clients and connections. |
| Ignoring startup duration | Healthy applications may be restarted prematurely. | Configure a startup probe. |
| No probe timeout | Slow checks can delay monitoring. | Configure suitable timeouts. |
25. Production Best Practices
- Use separate liveness and readiness endpoints.
- Use startup probes for applications with lengthy initialization.
- Keep liveness checks lightweight and independent of external dependencies.
- Check required dependencies through readiness.
- Use timeouts for all external health check operations.
- Avoid performing expensive database queries during every probe.
- Reuse HttpClient and other managed connections.
- Do not expose sensitive infrastructure details.
- Use appropriate Kubernetes failure thresholds and probe intervals.
- Monitor health check failures and trends.
- Test application startup, shutdown, and dependency failure scenarios.
- Ensure health checks do not overload databases or external systems.
26. Interview Questions and Answers
Q1. What are health checks in ASP.NET Core?
Health checks are endpoints that report whether an application and its required dependencies are functioning correctly.
Q2. What is a liveness probe?
A liveness probe checks whether an application is still functioning. Kubernetes can restart a container when liveness repeatedly fails.
Q3. What is a readiness probe?
A readiness probe checks whether an application instance is ready to receive traffic. A failed readiness probe removes the pod from normal service traffic.
Q4. What is a startup probe?
A startup probe determines whether an application has completed initialization. It protects slow-starting applications from premature liveness failures.
Q5. Should database connectivity be checked in liveness?
Normally no. Database connectivity is generally a readiness concern because a database outage should not automatically cause the application container to restart.
Q6. How do you register health checks?
Use builder.Services.AddHealthChecks() to register health check services and app.MapHealthChecks() to expose an endpoint.
Q7. What is IHealthCheck?
IHealthCheck is an interface used to implement custom health checks.
Q8. What happens when a Kubernetes readiness probe fails?
The pod is marked not ready and is normally excluded from traffic routed through its Kubernetes Service.
Q9. What happens when a Kubernetes liveness probe fails repeatedly?
Kubernetes restarts the container after the configured failure threshold is reached.
Q10. What is the purpose of health check tags?
Tags allow us to group health checks and selectively execute them for different endpoints, such as liveness and readiness.
Q11. How do you monitor SQL Server health?
Register the SQL Server health check integration or implement a custom IHealthCheck that performs a lightweight connectivity check.
Q12. What is the difference between Degraded and Unhealthy?
Degraded means a service is functioning with a warning or reduced capability. Unhealthy means a check has failed according to its defined criteria.
Q13. Can health checks cause performance problems?
Yes. Expensive or frequently executed checks can add load to databases, message brokers, and external services. Keep checks lightweight and use suitable intervals.
Q14. How do you implement health checks in microservices?
Each service exposes its own health endpoints and monitors only the dependencies relevant to its responsibilities.
Q15. Can health checks detect every application problem?
No. Health checks provide a limited view of application status. They should be combined with logs, metrics, tracing, alerts, and functional monitoring.
27. Quick Revision
| Concept | Purpose |
|---|---|
| Health Check | Reports application or dependency health. |
| Liveness | Determines whether the application should keep running. |
| Readiness | Determines whether the application can receive traffic. |
| Startup | Determines whether application initialization is complete. |
| IHealthCheck | Interface for custom health checks. |
| AddHealthChecks() | Registers health check services. |
| MapHealthChecks() | Maps a health check endpoint. |
| HealthCheckOptions | Configures endpoint behavior. |
| HealthStatus.Healthy | All applicable checks report healthy. |
| HealthStatus.Degraded | Application is functioning with a warning. |
| HealthStatus.Unhealthy | At least one applicable check reports unhealthy. |
28. Official Microsoft and Kubernetes Documentation
| Memory-Management-GC :👈 | 👉:Building-Cloud-Native-Core-Applications |