Covers the container lifecycle for a .NET service: startup, readiness and liveness probes, the SIGTERM to SIGKILL sequence and terminationGracePeriodSeconds, the Generic Host's shutdown path, IHostApplicationLifetime events, HostOptions.ShutdownTimeout, preStop delays for endpoint propagation and draining background work.
When a pod is stopped, Kubernetes removes it from Service endpoints and sends SIGTERM at the same time, then waits terminationGracePeriodSeconds (30 s by default) before SIGKILL. In .NET the Generic Host turns SIGTERM into IHostApplicationLifetime.ApplicationStopping; Kestrel stops accepting new connections and drains in-flight requests, and every IHostedService.StopAsync runs, all bounded by HostOptions.ShutdownTimeout (30 s by default since .NET 6, including .NET 10; it was 5 s before). Because endpoint removal propagates slowly, add a short preStop delay so the pod keeps serving until load balancers stop sending to it.
On the way up, a startup probe covers slow initialisation, a readiness probe decides whether the pod gets traffic, and liveness restarts only a truly stuck process. The trade-off: longer grace periods mean safer drains but slower deploys and scale-in.
"A container is disposable: the platform starts it, sends it traffic only when it says it is ready, and stops it whenever it wants, during a deploy, a scale-in or a node drain. Graceful shutdown is about finishing what you started in that window, and readiness is about not taking work you cannot do yet.
On stop, Kubernetes does two things at once: it marks the pod as terminating so it is removed from the Service endpoints, and it sends SIGTERM to PID 1. Those race. kube-proxy, ingress controllers and cloud load balancers can take a few seconds to stop routing to the pod, so if the app exits immediately, those last requests get 502s. That is why I add a
preStopsleep of around 5 to 10 seconds. Then the .NET Generic Host takes over: SIGTERM firesApplicationStopping, Kestrel stops accepting connections and lets in-flight requests finish, hosted services getStopAsyncwith a cancellation token, and the whole thing is capped byHostOptions.ShutdownTimeout, 30 seconds by default. That timeout plus the preStop delay must fit insideterminationGracePeriodSeconds, otherwise the kubelet sends SIGKILL mid-drain.On start, I use three probes with different jobs: a startup probe so a slow first start isn't killed by liveness, a readiness probe that passes only after warm-up and fails as soon as shutdown begins, and a liveness probe that checks only that the process can respond, never the database. The mistake I see is liveness checking SQL: the database blips and Kubernetes restarts every pod at once. Shutdown is a feature; you have to design it and test it."
| Step | Who | Default | What you control |
|---|---|---|---|
| Pod marked Terminating, endpoints removed | Control plane | Asynchronous, seconds to propagate | Nothing directly: hence preStop |
preStop hook runs |
Kubelet | None | sleep 5-10 s |
| SIGTERM to PID 1 | Kubelet / container runtime | After preStop | Exec-form ENTRYPOINT so .NET is PID 1 |
ApplicationStopping fires |
Generic Host | Immediately | Flip readiness to unhealthy, stop pulling messages |
Kestrel drains, StopAsync runs |
Host | ShutdownTimeout = 30 s |
Set to grace period minus preStop minus margin |
ApplicationStopped, process exits |
Host | Flush telemetry | |
| SIGKILL | Kubelet | terminationGracePeriodSeconds = 30 s |
Raise for long-running work |
| Probe | Question it answers | What to check | On failure |
|---|---|---|---|
| Startup | Has it finished starting? | Warm-up complete (migrations checked, caches primed) | Keeps liveness off until it passes |
| Readiness | Should it get traffic now? | Warm-up done, not shutting down, critical local dependencies | Removed from endpoints, not restarted |
| Liveness | Is the process stuck? | The process responds (no dependencies) | Container restarted |
Container Apps runs on Kubernetes and Envoy underneath. It supports the same three probe types and sends SIGTERM with a configurable termination grace period; new revisions receive traffic only after their probes pass. The same .NET settings apply.
An API on AKS showed about 0.4% 502s during every rolling deploy. Adding a 10-second preStop sleep, failing readiness on ApplicationStopping, setting ShutdownTimeout to 20 seconds and terminationGracePeriodSeconds to 40 took deploy-time errors to zero across the next 50 releases.
Checks whether the candidate understands the container lifecycle end to end and can size the timeouts so deploys cause no errors.
Green flags
ApplicationStopping, ShutdownTimeout and the 30 s defaults, and how they must fit togetherRed flags
Start-up race Shutdown race
------------- -------------
container starts pod deleted
| |----------------------------+
process listening on 8080 | endpoints updated | preStop sleep 10s
| (but caches cold, | (kube-proxy, ingress, |
| EF model not built) | Azure LB catch up: 1-10s)| SIGTERM -> .NET
startupProbe passes | | ApplicationStopping
readinessProbe passes -> traffic | | Kestrel drains
+----------------------------+ StopAsync (<= ShutdownTimeout)
exit 0 (or SIGKILL at grace period)
Without a readiness gate, traffic arrives before the app can serve it. Without a preStop delay, the app exits while routers still send it traffic.
The Generic Host's ConsoleLifetime registers handlers using PosixSignalRegistration for SIGTERM, SIGINT and SIGQUIT. On SIGTERM it calls IHostApplicationLifetime.StopApplication(), which:
ApplicationStopping callbacks.IHost.StopAsync with a token that cancels after HostOptions.ShutdownTimeout.Connection: close, HTTP/2 connections get GOAWAY.ApplicationStopped, then Main returns.Since .NET 8 you can set HostOptions.ServicesStartConcurrently and ServicesStopConcurrently; stopping concurrently helps when several services each need time to drain.
The default ShutdownTimeout was 5 seconds before .NET 6 and is 30 seconds now, the same as the Kubernetes grace period, which is exactly why you must lower one or raise the other: preStop time comes out of the same 30 seconds.
A shell-form ENTRYPOINT dotnet app.dll runs /bin/sh -c, which becomes PID 1 and may not forward SIGTERM; your app is then SIGKILLed after 30 s. Use exec form ENTRYPOINT ["dotnet", "Orders.Api.dll"] (the default in dotnet publish container images). Chiseled images have no shell, so a preStop exec: sleep command fails there; use the Kubernetes native sleep lifecycle action, available in recent Kubernetes versions, or a /prestop HTTP endpoint that delays.
A BackgroundService must pass stoppingToken to every await. For queue consumers, stop pulling new messages on ApplicationStopping, finish or abandon the current one, and rely on redelivery plus idempotency for anything cut off. If a job takes longer than any reasonable grace period, it should be checkpointed or moved to a Job / Container Apps job.
Use tags to build separate endpoints:
/health/live: Predicate = _ => false (no checks; responds if the process is alive)./health/ready: checks tagged ready, including a custom check that returns Unhealthy once ApplicationStopping has fired or before warm-up completes.Keep readiness checks cheap and cache the results of expensive ones (HealthCheckPublisherOptions or your own caching), because probes run every few seconds on every pod.
terminationGracePeriodSeconds >= preStop + ShutdownTimeout + margin
40 >= 10 + 25 + 5
Set ShutdownTimeout from your p99 request duration and longest message handler, not by guessing.
docker stop (SIGTERM, 10 s default) and see the request cut off; retry with docker stop -t 40.ENTRYPOINT and observe the app never logging ApplicationStopping.hey or k6 against the Service and do kubectl rollout restart; count non-2xx with and without a preStop sleep.ApplicationStopping and watch kubectl get endpoints during a rollout.ApplicationStopping and ApplicationStopped to measure your real drain time.Readiness that follows warm-up and shutdown, sized timeouts and a background worker that honours cancellation.
// Program.cs (.NET 10)
using Microsoft.Extensions.Diagnostics.HealthChecks;
var builder = WebApplication.CreateBuilder(args);
// preStop (10s) + ShutdownTimeout (25s) + margin fits a 40s terminationGracePeriodSeconds.
builder.Services.Configure<HostOptions>(o =>
{
o.ShutdownTimeout = TimeSpan.FromSeconds(25);
o.ServicesStopConcurrently = true;
});
builder.Services.AddSingleton<ReadinessState>();
builder.Services.AddHostedService<WarmUpService>();
builder.Services.AddHostedService<OrderQueueWorker>();
builder.Services.AddHealthChecks()
.AddCheck<ReadinessCheck>("readiness", tags: ["ready"]);
var app = builder.Build();
// Stop advertising readiness the moment shutdown starts.
app.Lifetime.ApplicationStopping.Register(() =>
app.Services.GetRequiredService<ReadinessState>().ShuttingDown = true);
app.MapHealthChecks("/health/live", new() { Predicate = _ => false }); // process only
app.MapHealthChecks("/health/ready", new() { Predicate = c => c.Tags.Contains("ready") });
app.MapGet("/orders/{id:int}", (int id) => Results.Ok(new { id }));
app.Run();
public sealed class ReadinessState
{
public volatile bool WarmedUp;
public volatile bool ShuttingDown;
}
public sealed class ReadinessCheck(ReadinessState state) : IHealthCheck
{
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default) =>
Task.FromResult(state switch
{
{ ShuttingDown: true } => HealthCheckResult.Unhealthy("Shutting down"),
{ WarmedUp: false } => HealthCheckResult.Unhealthy("Warming up"),
_ => HealthCheckResult.Healthy()
});
}
public sealed class WarmUpService(ReadinessState state, ILogger<WarmUpService> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await Task.Delay(TimeSpan.FromSeconds(3), stoppingToken); // e.g. prime caches, build EF model
state.WarmedUp = true;
logger.LogInformation("Warm-up complete; readiness will pass");
}
}
public sealed class OrderQueueWorker(ILogger<OrderQueueWorker> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
// Receive and handle one message; pass the token to every await.
await Task.Delay(TimeSpan.FromSeconds(1), stoppingToken);
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
logger.LogInformation("Stopping: unfinished message will be redelivered");
}
}
}
}
# Deployment excerpt
spec:
terminationGracePeriodSeconds: 40
containers:
- name: orders-api
lifecycle:
preStop:
sleep:
seconds: 10 # native sleep action: works in chiseled images with no shell
startupProbe:
httpGet: { path: /health/ready, port: 8080 }
periodSeconds: 2
failureThreshold: 30 # up to 60 s to start
readinessProbe:
httpGet: { path: /health/ready, port: 8080 }
periodSeconds: 5
livenessProbe:
httpGet: { path: /health/live, port: 8080 }
periodSeconds: 10
failureThreshold: 3
ApplicationStopping.ShutdownTimeout at 30 s with the default 30 s grace period and a preStop hook. Why it is wrong: The preStop time is taken from the same grace period, so the kubelet SIGKILLs mid-drain. Instead: Size terminationGracePeriodSeconds to preStop + ShutdownTimeout + margin.ENTRYPOINT. Why it is wrong: The shell is PID 1 and may not forward SIGTERM, so the app is killed without draining. Instead: Use exec form so the .NET process is PID 1.failureThreshold × periodSeconds.BackgroundService that ignores stoppingToken. Why it is wrong: Shutdown waits for the full timeout and then the work is cut off anyway. Instead: Pass the token to every await and design work to be redelivered safely.Graceful shutdown is a contract between three parties: the platform (grace period, endpoint propagation), the host (ShutdownTimeout, Kestrel draining) and your code (honouring cancellation, idempotent work). Most deploy-time errors come from those numbers not adding up, not from bugs in business code. Measure it: run a load test through a rolling restart and count non-2xx responses; the target is zero.
| Choice | When it fits | Cost | When not to |
|---|---|---|---|
| Short grace (30 s) | Fast HTTP APIs, p99 < 1 s | Long requests cut off | Message handlers taking minutes |
| Long grace (2-5 min) | Batch handlers, large uploads | Slower deploys, node drains, scale-in | User-facing APIs; make the work resumable instead |
| Readiness checking dependencies | A dependency that only this pod can lose (local sidecar) | Cascading removal if shared dependency fails | Shared databases: all pods fail together |
A burst of 502s on every rollout is almost always a shutdown or start-up race, not a code bug. On termination, Kubernetes sends SIGTERM to the container and removes the pod from the Service endpoints at the same time, so the ingress keeps sending requests for a few seconds to a process that is closing. I fix it in layers, with numbers that must add up: a preStop sleep (about 10 s) so routing updates first; HostOptions.ShutdownTimeout sized from the measured p99.9 request duration (say 15 s) so in-flight requests drain; and terminationGracePeriodSeconds larger than both together (35 s). Then readiness probes that only pass when the app is warm and fail once ApplicationStopping fires, separate from liveness, plus maxUnavailable: 0. I also check keep-alive timeouts: if Kestrel closes idle connections before the proxy does, the proxy reuses a dead connection and returns 502. The trade-off is slightly slower deployments for zero dropped requests.
A health check is an automated decision: the orchestrator or load balancer acts on it, so it must answer exactly the question the actor asks. Liveness asks "is this process stuck?", so the answer is a restart. It never checks shared dependencies. Readiness asks "should this instance get traffic now?" It checks warm-up and local essentials, not something every instance shares. Startup probes give slow starts time before liveness applies.
The classic failure is a database check in liveness or readiness: one database blip makes every instance fail together. You get a fleet restart or zero healthy backends, which turns a partial outage into a total one. In ASP.NET Core I use tagged checks mapped to separate endpoints, keep them cheap and time-boxed, and keep detailed output internal. Dependency health goes to monitoring and alerts, where a human decides.
Three things make a queue worker safe on Kubernetes or Container Apps. Graceful shutdown: on SIGTERM the host cancels stoppingToken. The worker stops receiving and finishes or abandons in-flight messages within HostOptions.ShutdownTimeout, which must be shorter than terminationGracePeriodSeconds. Idempotency: Service Bus peek-lock is at-least-once. A crash, a lock expiry or a shutdown redelivers the message, so the handler records the message id in a processed-messages table in the same transaction as the business change, and passes idempotency keys to the payment provider. Poison messages go to the dead-letter queue after MaxDeliveryCount. Scaling: a KEDA ScaledObject (or a Container Apps scale rule) on queue length adds pods as the backlog grows and scales to zero or a minimum when idle.
The trade-off: more replicas clear backlogs faster but multiply concurrency against downstream systems and break ordering unless you use sessions.
How to tell it (STAR)
**S:** Our orders API ran on AKS with [8] replicas, and every deploy caused a 20-second burst of 502s that burned our partner's error budget. **T:** I was asked to make deploys invisible to callers. **A:** I lined up ingress logs with pod termination events and saw the app exited in under a second while the ingress kept routing to it: endpoint removal and SIGTERM race. I added a 10-second preStop sleep, failed readiness on `ApplicationStopping`, sized `ShutdownTimeout` and the grace period so they fit together, and added a startup probe. Then I added a staging load test through a rolling restart to the pipeline. **R:** Deploy-time errors went from about [0.4%] of requests to zero over the next [50] releases, and we could deploy during business hours again.
Last updated 23 Nov 2026.