Health checks and graceful shutdown in ASP.NET Core: zero-downtime deployments in containers
A new version is being deployed. The orchestrator starts new containers and stops the old ones. A wave of 502s shows up on the dashboards for a few seconds, then everything goes back to normal. Nobody gets paged because the error spike is short; but with every deployment, half-finished requests, interrupted background jobs and meaningless errors returned to users keep piling up.
The cause is rarely the application code itself. It is how the application describes its lifecycle to the outside world. The orchestrator wants to know when the application is ready for traffic, when it needs to be restarted and how long to wait while it shuts down. In this post I explain how to give clear answers to these three questions with ASP.NET Core: separating health checks by purpose and shutting down in a controlled way.
Why a single /health endpoint is not enough
Many projects have a single /health endpoint that checks the database, the cache, the message queue and external APIs together. That endpoint is used both for "is the application alive" and for "can I send it traffic". The problem is that these two questions lead to different consequences.
If a liveness check fails, the orchestrator restarts the container. If a readiness check fails, the container is not restarted; it is only removed from the load balancer temporarily. When the database is unreachable for a few seconds, the second behaviour is the right one: restarting the application does not fix it. Putting the database into the liveness check can turn a short database outage into a cascading failure where every service restarts at the same time.
So the rule is simple: liveness checks only the process itself; dependencies belong to readiness.
Separating checks with tags in ASP.NET Core
The built-in health check infrastructure in ASP.NET Core makes this separation easy through tags. You give each check a tag when registering it and filter the endpoints by those tags:
builder.Services.AddHealthChecks()
.AddCheck<DatabaseHealthCheck>("database", tags: ["ready"])
.AddCheck<MessageBrokerHealthCheck>("broker", tags: ["ready"]);
var app = builder.Build();
app.MapHealthChecks("/health/live", new HealthCheckOptions
{
Predicate = _ => false
});
app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
Predicate = check => check.Tags.Contains("ready")
});
/health/live runs no checks at all; if the process is up and can handle a request, it returns Healthy. That is a deliberate choice: liveness is nothing more than "can the HTTP pipeline respond". /health/ready runs only the checks tagged ready.
To write your own check, you implement the IHealthCheck interface:
public sealed class DatabaseHealthCheck(AppDbContext db) : IHealthCheck
{
public async Task<HealthCheckResult> CheckHealthAsync(
HealthCheckContext context, CancellationToken cancellationToken = default)
{
return await db.Database.CanConnectAsync(cancellationToken)
? HealthCheckResult.Healthy()
: HealthCheckResult.Unhealthy("Cannot connect to the database");
}
}
Keeping the readiness check cheap and honest
The readiness endpoint is called every few seconds for every instance. Running a heavy query or calling an external API each time creates unnecessary load and slows down the check itself. A simple connection test or a SELECT 1 is usually enough.
Adding every dependency to readiness is not right either. Removing all instances from traffic because an external service used by one small feature is down turns a partial problem into a full outage. Ask yourself: without this dependency, can this instance not serve most meaningful requests? If the answer is yes, it belongs in readiness; if not, that feature needs its own error handling and monitoring. The Degraded status is also a good fit for reporting this in-between state.
Another point is the content of health check responses. Detailed JSON output is useful for debugging, but connection strings, internal host names or exception messages should not be exposed. Either restrict these endpoints to the internal network or return only the status code externally.
Startup: not taking traffic before being ready
When the application process starts, it may not be ready yet. A cache may be warming up, configuration may be loading or the first connections may still be opening. The readiness check should cover this period too. If there is work to be done at startup, you can write a small service that tracks whether it has finished and a health check that reads it:
public sealed class StartupState
{
private volatile bool _ready;
public bool IsReady => _ready;
public void MarkReady() => _ready = true;
}
public sealed class StartupHealthCheck(StartupState state) : IHealthCheck
{
public Task<HealthCheckResult> CheckHealthAsync(
HealthCheckContext context, CancellationToken cancellationToken = default) =>
Task.FromResult(state.IsReady
? HealthCheckResult.Healthy()
: HealthCheckResult.Unhealthy("Startup work in progress"));
}
If you use Kubernetes, defining a separate startup probe for slow-starting applications prevents the liveness check from killing the container too early during startup.
What happens when SIGTERM arrives
Shutdown matters at least as much as startup. When an orchestrator stops a container, it first sends SIGTERM, waits for a certain period and, if that period expires, forcibly terminates the process with SIGKILL. The .NET Generic Host catches SIGTERM and starts a controlled shutdown: IHostApplicationLifetime.ApplicationStopping fires, Kestrel stops accepting new connections and waits for in-flight requests to complete, and the StopAsync methods of hosted services are called.
For this chain to work, the signal has to reach the application. If ENTRYPOINT in the Dockerfile is written in shell form, the process starts under a shell and the signal may not be forwarded to the application. Use the exec form:
ENTRYPOINT ["dotnet", "MyApi.dll"]
The time allowed for shutdown is also a contract. There is HostOptions.ShutdownTimeout on the host side and the container termination period on the orchestrator side. The application's shutdown time must be shorter than what the orchestrator allows; otherwise cleanup is cut off halfway:
builder.Services.Configure<HostOptions>(options =>
{
options.ShutdownTimeout = TimeSpan.FromSeconds(20);
});
Winning the race with the load balancer
There is a detail that is often overlooked: sending SIGTERM and the load balancer stopping traffic to that instance do not happen at the same moment. These two events take place in different parts of a distributed system, and there is a short delay between them. If the application stops accepting connections as soon as it receives SIGTERM, requests routed to it in the meantime hit connection errors. This is the most common cause of the 502 wave during deployments.
The solution is to wait briefly before starting to shut down. In Kubernetes this is usually done with a preStop hook; the hook waits a few seconds, during which the instance is removed from the endpoint list, and then SIGTERM is sent. If you want to do it inside the application, you can switch the readiness check to failing at ApplicationStopping and add a short delay. Whichever way you choose, add up the waiting time and the shutdown timeout and make sure the total stays below the orchestrator's termination period.
Not abandoning background work halfway
HTTP requests are awaited by Kestrel, but loops running inside a BackgroundService are your responsibility. The stoppingToken passed to ExecuteAsync signals that shutdown has begun. Use this token not only in the loop condition but in every awaited asynchronous call where cancelling is safe:
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
var message = await queue.ReceiveAsync(stoppingToken);
if (message is null) continue;
await ProcessAsync(message, CancellationToken.None);
await queue.CompleteAsync(message, CancellationToken.None);
}
}
There is a deliberate distinction here: receiving new messages is cancellable, but a message that has already started processing is not interrupted. If processing a single message can take longer than the shutdown period, this assumption breaks; in that case the work must be idempotent and an unfinished message must return to the queue. Shutdown should always be designed as a moment that can be interrupted.
Verifying: making deployment a test scenario
Measure instead of assuming these settings work. Start a deployment while a simple load testing tool sends continuous requests to the service, and watch the error count. It should be zero. Repeat the same test by stopping a container directly, and check the order and duration of the shutdown steps in the logs. Try the health check endpoints too by shutting down dependencies one by one: when the database goes away, is the instance removed from traffic without being restarted?
Zero-downtime deployment is not achieved with a single setting but with an explicit contract between the application and the orchestrator. Liveness says the process is alive, readiness says it can take traffic, and shutdown happens within a known time, in order and without losing work. Once this contract is in place, deploying becomes an ordinary, boring task. That is exactly the goal.