Shutting down gracefully: don't drop requests when your pod stops
Every deployment stops your old pods. If your .NET API doesn't shut down cleanly, every deployment also drops requests and abandons background work. Here's how the shutdown sequence works, and the few settings that make it clean.
A couple of weeks ago one of the clues was a restart that came with no "Application is shutting down..." line before it. That's what it looks like when a container is killed outright. This week is about the other kind of stop, the polite one. It happens every time you deploy, scale down or a node is drained, so it happens far more often than any crash.
A polite stop should be harmless: requests in progress finish, background work stops at a safe point, and nothing new arrives at a pod that's on its way out. In practice, a lot of .NET APIs return a handful of 502s on every deployment, or leave a batch job half done, and the team accepts it as normal. It usually comes down to three or four settings.
What actually happens when a pod stops
When Kubernetes decides a pod should go, several things start at once:
- The pod is marked as terminating, and Kubernetes starts removing it from the Service's endpoints, so load balancers and ingress controllers stop sending it traffic.
- At the same time, the kubelet runs the container's preStop hook, if there is one.
- When the preStop hook finishes, the container's main process gets a SIGTERM.
- If the process is still running when the grace period runs out (30 seconds by default, counted from step 1), it gets a SIGKILL and dies on the spot.
The trap is in the first two steps happening at the same time. Removing a pod from the endpoints has to reach every node, every kube-proxy and every ingress controller, and that takes a moment. If your app gets SIGTERM straight away and stops accepting connections, traffic is still being routed to it for that moment. Those requests fail with connection errors or 502s, and nobody's code logged anything wrong.
What .NET does with SIGTERM
The generic host listens for SIGTERM. When it arrives, the host:
- signals
IHostApplicationLifetime.ApplicationStoppingand logs "Application is shutting down...", - tells Kestrel to stop accepting new connections and lets requests in progress finish,
- calls
StopAsyncon every hosted service, which cancels thestoppingTokenyourBackgroundServicewas given, - waits for all of that, up to
HostOptions.ShutdownTimeout, which is 30 seconds by default.
That's a good sequence. It just needs three things from you: a little time before it starts, a budget that fits inside Kubernetes' grace period, and code that actually stops when it's asked to.
Fix 1: give the routing time to catch up
Add a short pause before your app sees SIGTERM, so the pod is out of rotation before it stops listening. On Kubernetes 1.30 and later there's a built-in sleep action for this:
spec:
terminationGracePeriodSeconds: 45
containers:
- name: api
image: your-api:latest
lifecycle:
preStop:
sleep:
seconds: 10
On older clusters people use an exec hook that runs sleep 10. Be careful with that one: the chiseled and distroless .NET images don't have a shell or a sleep command, so the hook fails and you're back to no pause at all. The built-in action doesn't need anything inside the image.
How long to sleep depends on your ingress and load balancer. Five to ten seconds covers most setups. You don't need to fail your readiness probe during shutdown to get the same effect; a terminating pod is taken out of the endpoints anyway. (Readiness still matters for startup and for dependency problems. See Health checks that tell the truth.)
Fix 2: make the budgets add up
The grace period is counted from the moment the pod starts terminating, and the preStop sleep comes out of it. So the defaults don't fit together: a 10-second sleep plus .NET's 30-second shutdown timeout is 40 seconds, and the default grace period is 30. Anything still running at second 30 is killed without a log line.
Set both sides on purpose:
builder.Services.Configure<HostOptions>(options =>
{
options.ShutdownTimeout = TimeSpan.FromSeconds(25);
});
With the YAML above, that's a 10-second sleep plus up to 25 seconds of shutdown, inside a 45-second grace period, with room to spare for flushing logs. The rule is simply:
| Setting | Where | Must be |
|---|---|---|
| preStop sleep | Deployment YAML | Long enough for routing to update (5–10 s) |
HostOptions.ShutdownTimeout | Program.cs | Longer than your slowest normal request or unit of background work |
terminationGracePeriodSeconds | Deployment YAML | Greater than the other two added together, plus a few seconds |
If a request or a job can legitimately take longer than you're willing to wait during a deployment, that's a sign it should be split into smaller steps or moved onto a queue, not a reason to set a five-minute grace period.
Fix 3: make sure SIGTERM reaches your app
All of this assumes your process gets the signal. Kubernetes sends SIGTERM to the container's first process, PID 1. If your Dockerfile uses the shell form:
ENTRYPOINT dotnet MyApi.dll
then PID 1 is a shell, not your app, and the shell doesn't pass the signal on. Your app never hears about the shutdown, carries on serving requests and is killed when the grace period runs out. Every deployment takes the full 30 seconds per pod and ends with a SIGKILL. Use the exec form instead:
ENTRYPOINT ["dotnet", "MyApi.dll"]
The images built by dotnet publish with container support already do this. It's hand-written Dockerfiles, and entrypoint scripts that end in dotnet MyApi.dll instead of exec dotnet MyApi.dll, that get it wrong.
Fix 4: write background services that stop
Kestrel handles requests in progress for you. Hosted services are your responsibility. When shutdown starts, the stoppingToken passed to ExecuteAsync is cancelled, and the host waits for ExecuteAsync to finish. A worker that ignores the token will be waited on until the timeout and then abandoned mid-step.
public sealed class OrderSyncWorker(IOrderSync sync, ILogger<OrderSyncWorker> logger)
: BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(TimeSpan.FromMinutes(1));
try
{
while (await timer.WaitForNextTickAsync(stoppingToken))
{
await sync.RunNextBatchAsync(stoppingToken);
}
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
logger.LogInformation("Order sync stopped cleanly");
}
}
}
Two things make this work. The token is passed into the work itself, not just the loop, so a batch in progress can stop too (see Pass your CancellationToken all the way down). And the work comes in small batches, each one safe to stop after, so stopping never leaves things half written.
If a worker owns a Service Bus processor, stop it explicitly so it finishes the messages it's handling and stops taking new ones:
public override async Task StopAsync(CancellationToken cancellationToken)
{
await _processor.StopProcessingAsync(cancellationToken);
await base.StopAsync(cancellationToken);
}
Anything that doesn't finish in time will have its lock expire and be delivered again to another pod. That's fine, as long as your handlers are idempotent.
Last, flush anything buffered. If you send logs or telemetry in batches, as with agentless logging to Datadog, make sure the final batch is sent on shutdown. Otherwise the lines that would explain a bad shutdown are exactly the ones you lose.
Try it before you trust it
You can rehearse a shutdown locally. docker stop sends SIGTERM, waits 10 seconds by default, then sends SIGKILL, which is the same sequence Kubernetes uses:
docker run -d --name api -p 8080:8080 your-api:latest
# start a slow request or let a background job begin, then:
docker stop -t 30 api
docker logs api | tail -20
You should see "Application is shutting down...", then your workers' "stopped cleanly" lines, then nothing else. If docker stop takes the full 30 seconds and the shutdown line never appears, the signal isn't reaching your app (fix 3). If the shutdown line appears but your workers' lines don't, something isn't honoring its token (fix 4).
In the cluster, run a load test against the service and do a rollout while it runs. Before these changes, a few failed requests per pod replaced is common. After them, it should be zero.
Takeaway
Your pods stop every time you deploy, so a clean shutdown matters more than almost any crash handling. Pause briefly with a preStop sleep so traffic stops arriving before your app stops listening. Make sure the sleep plus ShutdownTimeout fits inside terminationGracePeriodSeconds. Use the exec form of ENTRYPOINT so SIGTERM actually reaches .NET. And write background services that take their stoppingToken seriously and work in steps that are safe to stop after.