Stopping a pod or server during a deployment is easy. The difficult part is preventing active HTTP requests from being interrupted, stopping background workers without losing work, and ensuring that load balancers no longer send new traffic to an instance that is shutting down. Without a deliberate design, users may see intermittent 502, 503, or connection-reset errors, while queued jobs may run twice or disappear.
Graceful shutdown means that a service stops accepting new work, allows work already in progress to finish within a defined budget, and then closes its resources. This article examines a practical shutdown flow for an ASP.NET Core API and background worker running on Kubernetes.
The problem: why rolling updates create errors
Consider an order API running with two replicas. During a deployment, Kubernetes terminates one of the old pods. If the application simply exits after receiving SIGTERM, several race conditions can occur:
- An active request is interrupted and the client receives a 5xx response or a connection error.
- Service discovery or an intermediate proxy continues sending traffic to the terminating pod for a short period.
- A background worker is killed between writing to the database and acknowledging a message. The message may later be processed again or, with a poor queue design, lost.
The common mistake is assuming that “handle SIGTERM and exit” is a complete shutdown strategy. Traffic removal, application-level shutdown, and completion of in-flight work must be designed together.
Understanding the Kubernetes termination flow
When a pod is deleted, Kubernetes normally gives it a controlled termination window defined by terminationGracePeriodSeconds. The default value is 30 seconds. If a preStop hook exists, the kubelet runs it before terminating the container. The hook and application shutdown must fit within the same grace-period budget; otherwise, the process can be forcibly terminated.
For terminating endpoints, Kubernetes EndpointSlice data marks the endpoint as not ready. This helps route new traffic elsewhere, but every proxy and network component may not observe the change at exactly the same time. The application should therefore stop accepting new work as well instead of relying only on endpoint removal.
A preStop hook is not an unlimited waiting room. If the grace period is 30 seconds and the hook sleeps for 10 seconds, the application may have only about 20 seconds left to finish requests and background work. The full sequence needs an explicit time budget.
A three-stage shutdown model
A reliable service can divide shutdown into three stages:
- Stop new work: Make readiness fail, stop accepting new HTTP requests, and prevent the queue consumer from receiving additional messages.
- Finish existing work: Allow active requests and bounded background operations to finish within a cancellation-aware deadline.
- Close resources: Dispose database connections, HTTP clients, message consumers, telemetry exporters, and other resources.
The ASP.NET Core Generic Host triggers ApplicationStopping during shutdown and calls StopAsync on hosted services. Current .NET Generic Host documentation specifies a default shutdown timeout of 30 seconds. Once that timeout expires, remaining operations are no longer guaranteed to complete gracefully.
A simple ASP.NET Core shutdown coordinator
public sealed class ShutdownState
{
private int _stopping;
public bool IsStopping => Volatile.Read(ref _stopping) == 1;
public void Begin() => Interlocked.Exchange(ref _stopping, 1);
}
public sealed class ShutdownListener : IHostedService
{
private readonly IHostApplicationLifetime _lifetime;
private readonly ShutdownState _state;
public ShutdownListener(
IHostApplicationLifetime lifetime,
ShutdownState state)
{
_lifetime = lifetime;
_state = state;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_lifetime.ApplicationStopping.Register(_state.Begin);
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
=> Task.CompletedTask;
}The readiness endpoint can inspect ShutdownState.IsStopping. Once shutdown begins, the endpoint may remain reachable while returning an unsuccessful readiness result. This allows service discovery to stop selecting the instance. Readiness and liveness must not be confused: a terminating pod is not necessarily broken; it simply should not receive new traffic.
Preventing data loss in background workers
Stopping a worker loop is not enough. The system must define when a message is considered successfully handled. A safer sequence is:
- Stop receiving new messages.
- Give messages already being processed a bounded cancellation-aware period to finish.
- Acknowledge only successfully completed messages.
- Allow unfinished messages to become visible again through the broker’s visibility timeout or consumer connection handling.
Imagine an order worker that writes to a database and then acknowledges the message. The process can still be killed between those two operations. The handler must therefore be idempotent, using a unique constraint, an operation key, or an order-state check. Graceful shutdown reduces the chance of interruption, but it does not replace idempotent processing or durable delivery semantics.
Defining a Kubernetes time budget
apiVersion: apps/v1
kind: Deployment
metadata:
name: orders-api
spec:
replicas: 3
template:
spec:
terminationGracePeriodSeconds: 45
containers:
- name: orders-api
image: example/orders-api:2026.11.17
lifecycle:
preStop:
exec:
command: ["/bin/sh", "-c", "sleep 8"]The eight-second delay can provide time for endpoint changes to propagate through load balancers and intermediate layers. It should not be copied blindly. Measure how long traffic draining actually takes and combine that result with the application’s shutdown time.
For example, suppose measurements show:
| Stage | Measured time | Target budget |
|---|---|---|
| Readiness propagation | 2 seconds | 5 seconds |
| Active HTTP requests | 9 seconds | 20 seconds |
| Worker shutdown | 6 seconds | 10 seconds |
| Safety margin | — | 10 seconds |
A 45-second grace period may be a reasonable starting point. By contrast, an API with a 25-second p95 request duration cannot safely be assumed to shut down within Kubernetes’ 30-second default.
Shutdown timeout and grace period are different
ASP.NET Core’s ShutdownTimeout controls how long the host waits for its shutdown operations. Kubernetes’ terminationGracePeriodSeconds controls the total time before the container can be forcibly terminated. If the application timeout is 60 seconds but Kubernetes allows only 30 seconds, the application cannot actually use the full 60-second budget.
For example:
builder.Services.Configure<HostOptions>(options =>
{
options.ShutdownTimeout = TimeSpan.FromSeconds(35);
});The Kubernetes grace period should be longer than the application timeout plus any preStop delay and a small safety margin. Otherwise, the kubelet may kill the process while the application is still waiting for active work to finish.
Scenarios that must be tested
Graceful shutdown cannot be validated by reviewing YAML alone. Test these scenarios in a controlled environment:
- Delete a pod under load and measure the error rate for active requests.
- Start a long-running HTTP request, delete the pod, and verify that the response completes.
- Terminate a worker while it is processing a message and verify that the message is redelivered and handled idempotently.
- Deliberately shorten the grace period and confirm that forced termination appears in logs and metrics.
- Monitor unavailable replicas during a rolling update.
Useful metrics include shutdown starts, shutdown duration, grace-period overruns, 5xx responses during termination, redelivered messages, and active requests at shutdown. Logs should include the deployment version, pod name, and shutdown reason.
Practical checklist
- Design startup, readiness, and liveness checks for different purposes.
- Stop new HTTP traffic and new queue consumption as soon as shutdown begins.
- Define an explicit time budget for in-flight work.
- Use
preStopbased on measured traffic-draining behavior. - Ensure the Kubernetes grace period exceeds the application shutdown timeout.
- Make worker operations idempotent; do not treat graceful shutdown as the only data-safety mechanism.
- Test pod deletion, rolling updates, and node draining under realistic load.
Graceful shutdown is not a single signal handler. Traffic routing, application lifecycle, background-job delivery, and Kubernetes timing are parts of the same reliability design. When these parts are measured and tested together, deployment-related 5xx errors and incomplete work can be reduced substantially.
Sources
- https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/
- https://kubernetes.io/docs/tutorials/services/pods-and-endpoint-termination-flow/
- https://kubernetes.io/docs/tasks/configure-pod-container/attach-handler-lifecycle-event/
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-10.0
- https://learn.microsoft.com/en-gb/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-10.0
0 Comments