In production deployments—whether running on bare-metal/dedicated Linux servers, Docker containers, or Kubernetes—an ASP.NET Core MVC application frequently experiences transient dependency outages, rolling restarts, and pod/service drain windows. Without structured health probes and shutdown coordination:
Liveness vs. Readiness Confusion: Routing traffic to an instance whose downstream dependencies (database, message broker, or cache) are unreachable causes cascading
500errors, while marking a process "unhealthy" for a temporary dependency blip can trigger unnecessary container restarts and thrashing.Abrupt Shutdowns & Dropped In-Flight Work: When a process or container receives
SIGTERM, stopping background workers or closing connections abruptly without draining active MVC requests or background tasks leads to dropped connections, partial writes, or failed background flushes.
ASP.NET Core's IHealthCheck + HealthCheckOptions, readiness vs. liveness endpoint separation, and IHostApplicationLifetime + HostOptions.ShutdownTimeout provide a clean, deterministic lifecycle model for probes, readiness gating, and graceful shutdown.
1. Architectural Blueprint & Lifecycle Probes
Plaintext
[Load Balancer / Orchestrator]
├─ Liveness Probe ──> GET /health/live (predicate: r => r.Tags.Contains("live"))
│ Checks process responsiveness; stays Healthy unless deadlocked/corrupted
├─ Readiness Probe ──> GET /health/ready (predicate: r => r.Tags.Contains("ready"))
│ Checks critical dependencies + shutdown gate; returns 503 when draining/down
└─ Startup / Full ──> GET /health (all registered IHealthCheck checks)
│
▼
[SIGTERM / Shutdown Triggered]
├─ IHostApplicationLifetime.ApplicationStopping fires
├─ ReadinessGate sets IsShuttingDown = true ──> /health/ready immediately returns 503
├─ Active MVC requests & BackgroundService loops observe CancellationToken
└─ Host waits up to HostOptions.ShutdownTimeout before forcing exit
Probe / Mechanism |
Purpose |
Failure Behavior |
Liveness ( |
Confirms the ASP.NET Core process and MVC host are alive and responsive. |
Kept focused on process liveness; avoid failing on transient external dependency blips to prevent restart loops. |
Readiness ( |
Indicates whether the instance can safely accept new traffic and is not shutting down. |
Returns |
Graceful Shutdown ( |
Stops new traffic via readiness gating while letting in-flight requests and background workers drain cleanly. |
Flips readiness to |
2. Readiness Gate, Custom IHealthCheck Implementations, and JSON Health Writer
Let's create:
A
ReadinessGateservice hooked intoIHostApplicationLifetime.ApplicationStoppingso readiness immediately flips tofalsewhen shutdown begins (and can also be toggled in tests/operations).A
DependencyStatusTrackerand twoIHealthCheckimplementations:ProcessLivenessHealthCheck(tagged"live")DownstreamDependencyHealthCheck(tagged"ready", checking bothReadinessGateand downstream readiness)
A
HealthCheckJsonWriterthat writes a clean JSON status report (Healthy,Degraded,Unhealthy) with individual check entries and duration metadata.
C#
using System.Text.Json;
using Microsoft.Extensions.Diagnostics.HealthChecks;
public sealed class ReadinessGate
{
private int _isAcceptingTraffic = 1;
public bool IsAcceptingTraffic => Volatile.Read(ref _isAcceptingTraffic) == 1;
public void MarkReady() => Interlocked.Exchange(ref _isAcceptingTraffic, 1);
public void MarkDraining() => Interlocked.Exchange(ref _isAcceptingTraffic, 0);
}
public sealed class DependencyStatusTracker
{
private volatile bool _isDatabaseReachable = true;
private volatile bool _isQueueReachable = true;
private string _lastError = string.Empty;
public bool IsDatabaseReachable => _isDatabaseReachable;
public bool IsQueueReachable => _isQueueReachable;
public string LastError => _lastError;
public void SetDependencyState(bool databaseReachable, bool queueReachable, string? error = null)
{
_isDatabaseReachable = databaseReachable;
_isQueueReachable = queueReachable;
_lastError = error ?? string.Empty;
}
}
public sealed class ProcessLivenessHealthCheck : IHealthCheck
{
private readonly DateTimeOffset _startedAtUtc = DateTimeOffset.UtcNow;
public Task<HealthCheckResult> CheckHealthAsync(
HealthCheckContext context,
CancellationToken cancellationToken = default)
{
var data = new Dictionary<string, object>
{
["startedAtUtc"] = _startedAtUtc,
["uptimeSeconds"] = (long)(DateTimeOffset.UtcNow - _startedAtUtc).TotalSeconds
};
return Task.FromResult(HealthCheckResult.Healthy("Process is responsive.", data));
}
}
public sealed class DownstreamDependencyHealthCheck : IHealthCheck
{
private readonly ReadinessGate _readinessGate;
private readonly DependencyStatusTracker _statusTracker;
public DownstreamDependencyHealthCheck(
ReadinessGate readinessGate,
DependencyStatusTracker statusTracker)
{
_readinessGate = readinessGate;
_statusTracker = statusTracker;
}
public Task<HealthCheckResult> CheckHealthAsync(
HealthCheckContext context,
CancellationToken cancellationToken = default)
{
if (!_readinessGate.IsAcceptingTraffic)
{
return Task.FromResult(HealthCheckResult.Unhealthy(
"Instance is draining traffic for shutdown or maintenance."));
}
if (!_statusTracker.IsDatabaseReachable)
{
return Task.FromResult(HealthCheckResult.Unhealthy(
string.IsNullOrWhiteSpace(_statusTracker.LastError)
? "Primary data store check failed."
: _statusTracker.LastError));
}
if (!_statusTracker.IsQueueReachable)
{
return Task.FromResult(HealthCheckResult.Degraded(
"Background queue is degraded; read traffic remains available."));
}
var data = new Dictionary<string, object>
{
["database"] = "reachable",
["queue"] = "reachable",
["acceptingTraffic"] = true
};
return Task.FromResult(HealthCheckResult.Healthy("All critical dependencies ready.", data));
}
}
internal static class HealthCheckJsonWriter
{
private static readonly JsonSerializerOptions SerializerOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = false
};
public static async Task WriteResponseAsync(HttpContext httpContext, HealthReport report)
{
httpContext.Response.ContentType = "application/json; charset=utf-8";
var payload = new
{
status = report.Status.ToString(),
totalDurationMs = Math.Round(report.TotalDuration.TotalMilliseconds, 2),
checks = report.Entries.ToDictionary(
kvp => kvp.Key,
kvp => new
{
status = kvp.Value.Status.ToString(),
description = kvp.Value.Description,
durationMs = Math.Round(kvp.Value.Duration.TotalMilliseconds, 2),
data = kvp.Value.Data
})
};
await JsonSerializer.SerializeAsync(
httpContext.Response.Body,
payload,
SerializerOptions,
httpContext.RequestAborted);
}
}
Join the conversation! Your thoughts help the community grow.