Diagnosing 502/503 errors during rolling deployments of ASP.NET Core on Kubernetes or Container Apps: the SIGTERM and endpoint-removal race, preStop delays, readiness versus liveness probes, HostOptions.ShutdownTimeout versus terminationGracePeriodSeconds, Kestrel connection draining, keep-alive timeouts versus load balancer idle timeouts, and start-up readiness.
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.
"When errors line up exactly with deployments and then disappear, I look at the pod lifecycle before the code. In Kubernetes, terminating a pod triggers two independent things: the kubelet runs the
preStophook and sends SIGTERM, and the endpoints controller removes the pod from the Service, which then has to propagate to kube-proxy and the ingress controller. Those happen in parallel, so for a few seconds the ingress still routes to a pod whose ASP.NET Core host has stopped accepting connections. That's the 502 or 503. The mirror image happens on start-up if readiness passes before the app is actually ready.For example, [at company] we saw [about 1-2%] of requests fail for [30 seconds] on every rollout of [an order API on AKS]. I lined up the ingress-nginx logs, which showed
upstream prematurely closed connectionandconnect() failedto the old pod IPs, withkubectl get eventsand the Application Insights failures, and they matched the termination timestamps exactly. The fixes were: apreStopsleep of 10 seconds so routing caught up before SIGTERM;HostOptions.ShutdownTimeoutof 15 seconds so in-flight requests could finish, keeping 10 plus 15 inside a 35-secondterminationGracePeriodSeconds; a readiness endpoint that only checks what's needed to serve and starts failing as soon asApplicationStoppingfires; liveness with no dependency checks; andmaxUnavailable: 0. There was one more cause: Kestrel's keep-alive was shorter than the ingress's upstream keep-alive, so nginx occasionally reused a connection Kestrel had just closed. After that, rollouts dropped [zero] requests.The mistake I see is fixing this with retries in the client. Retries hide it for GETs but double-submit POSTs. The senior fix is making the platform and the host agree on who stops sending traffic, and when."
t=0 kubectl rollout ─► pod marked Terminating
├─► kubelet: run preStop (sleep 10) ───────────► t=10 SIGTERM ─► host drains (≤ 15 s) ─► exit
└─► endpoints controller removes pod IP ─► kube-proxy / ingress update (1–10 s)
Without preStop: SIGTERM at t=0, Kestrel stops accepting ─► ingress still routes here ─► 502/503
Grace period (terminationGracePeriodSeconds) covers preStop + drain; after it: SIGKILL
| Symptom | Cause | Fix |
|---|---|---|
| 502/503 right after old pods terminate | SIGTERM before routing update | preStop sleep 5–15 s |
| Long requests cut off at ~30 s | Grace period or ShutdownTimeout too short |
Align: preStop + drain < grace period |
| Errors when new pods start | Readiness passes before warm-up | Readiness after warm-up; startupProbe for slow starts |
| Pods restarted during a DB blip | Liveness checks the database | Liveness = process only; dependencies in readiness |
| Occasional 502s at any time | Kestrel keep-alive < proxy idle timeout | App keep-alive > proxy upstream keep-alive |
| Lost queue messages on deploy | Worker ignores stoppingToken |
Stop pulling, finish current message, honour token |
| Setting | Default | Rule |
|---|---|---|
preStop sleep |
none | ~ time for endpoint propagation (5–15 s) |
HostOptions.ShutdownTimeout |
30 s (.NET 8+) | longest expected request + margin |
terminationGracePeriodSeconds |
30 s | > preStop + ShutdownTimeout |
Kestrel KeepAliveTimeout |
130 s | > proxy upstream idle timeout |
With a 10 s preStop, a 15 s ShutdownTimeout, a 35 s grace period and a readiness endpoint tied to ApplicationStopping, an API taking about 1,200 requests per second went from roughly 1,500 failed requests per rollout to zero across the next [50] deployments, at the cost of each rollout taking about 40 seconds longer.
Checks production experience with zero-downtime deployments and the ability to reason across app, host and platform.
Green flags
preStop delay.ShutdownTimeout, preStop and terminationGracePeriodSeconds with numbers.Red flags
When a pod is deleted (rolling update, scale-in, node drain):
deletionTimestamp; the pod becomes Terminating.preStop hook, then sends SIGTERM to PID 1, waits up to terminationGracePeriodSeconds (counted from the start of preStop), then SIGKILL.There is no ordering guarantee between A and B. The preStop sleep is the conventional way to give B a head start. Kubernetes 1.30+ supports a native sleep action in preStop, so chiseled images without a shell still work; on older clusters you need a shell sleep or an app endpoint.
Azure Container Apps uses the same model underneath (Envoy ingress, SIGTERM, a configurable termination grace period), so the same principles apply.
ConsoleLifetime registers a PosixSignalRegistration for SIGTERM and calls StopApplication():
ApplicationStopping fires.Connection: close on HTTP/1.1 responses and GOAWAY on HTTP/2/HTTP/3, and waits for in-flight requests.StopAsync in reverse order.ShutdownTimeout elapses, remaining requests are aborted.Note PID 1: if your container runs sh -c "dotnet app.dll", the shell may not forward SIGTERM. Use exec-form ENTRYPOINT ["dotnet", "app.dll"].
| Probe | Question | On failure | Should check |
|---|---|---|---|
startupProbe |
Has it finished starting? | Keep waiting, then restart | Warm-up complete |
readinessProbe |
Should it get traffic now? | Removed from endpoints (no restart) | Critical dependencies, not shutting down |
livenessProbe |
Is it stuck? | Container restarted | Process responds; no dependencies |
Putting the database in liveness turns a database outage into a restart storm across every pod.
A reverse proxy keeps a pool of idle upstream connections. If the upstream (Kestrel, default KeepAliveTimeout 130 s) closes an idle connection at the same moment the proxy sends a request on it, the proxy gets a reset and returns 502. The rule: the server's idle timeout must be longer than the proxy's. Azure Load Balancer's idle timeout defaults to 4 minutes, which is longer than Kestrel's 130 s, so services behind it can see this unless one side is changed.
maxUnavailable: 0 and maxSurge: 1 (or 25%) mean old pods are only terminated after new ones pass readiness. A PodDisruptionBudget protects against node drains taking too many replicas at once.
hey -z 60s or k6 against it, and trigger kubectl rollout restart; count non-2xx responses.preStop sleep 10 and repeat.kubectl get events -w and ingress logs side by side during a rollout.KeepAliveTimeout to 5 s behind nginx with a 60 s upstream keep-alive and watch for sporadic 502s under light load.Host shutdown settings, readiness that fails on shutdown, liveness without dependencies, and the matching Kubernetes manifest.
// Program.cs
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.Diagnostics.HealthChecks;
var builder = WebApplication.CreateBuilder(args);
// Drain budget: longest expected request plus margin; keep below the pod's grace period minus preStop
builder.Services.Configure<HostOptions>(o => o.ShutdownTimeout = TimeSpan.FromSeconds(15));
// Server idle timeout must outlive the proxy's upstream keep-alive to avoid stale-connection 502s
builder.WebHost.ConfigureKestrel(k => k.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(5));
builder.Services.AddSingleton<ShutdownState>();
builder.Services.AddHealthChecks()
.AddCheck<NotStoppingCheck>("not-stopping", tags: ["ready"])
.AddSqlServer(builder.Configuration.GetConnectionString("Orders")!, tags: ["ready"]); // AspNetCore.HealthChecks.SqlServer
var app = builder.Build();
var state = app.Services.GetRequiredService<ShutdownState>();
app.Lifetime.ApplicationStopping.Register(() => state.Stopping = true);
// Liveness: is the process responsive? No dependency checks, or a DB blip restarts every pod
app.MapHealthChecks("/health/live", new HealthCheckOptions { Predicate = _ => false });
// Readiness: should this instance receive traffic right now?
app.MapHealthChecks("/health/ready", new HealthCheckOptions { Predicate = r => r.Tags.Contains("ready") });
app.MapGet("/orders/{id:int}", (int id) => TypedResults.Ok(new { id }));
app.Run();
public sealed class ShutdownState { public volatile bool Stopping; }
public sealed class NotStoppingCheck(ShutdownState state) : IHealthCheck
{
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken ct = default)
=> Task.FromResult(state.Stopping ? HealthCheckResult.Unhealthy("shutting down") : HealthCheckResult.Healthy());
}
# deployment.yaml (excerpt)
spec:
strategy:
rollingUpdate: { maxUnavailable: 0, maxSurge: 1 } # never drop below desired ready replicas
template:
spec:
terminationGracePeriodSeconds: 35 # > preStop (10) + ShutdownTimeout (15) + margin
containers:
- name: orders-api
image: myregistry.azurecr.io/orders-api:1.4.2
lifecycle:
preStop:
sleep: { seconds: 10 } # K8s 1.30+; lets endpoints/ingress update before SIGTERM
startupProbe: { httpGet: { path: /health/live, port: 8080 }, periodSeconds: 2, failureThreshold: 30 }
readinessProbe: { httpGet: { path: /health/ready, port: 8080 }, periodSeconds: 5, failureThreshold: 2 }
livenessProbe: { httpGet: { path: /health/live, port: 8080 }, periodSeconds: 10, failureThreshold: 3 }
preStop delay. Why it is wrong: SIGTERM and endpoint removal race, so traffic arrives at a closing pod. Instead: preStop sleep of 5–15 s (native sleep action on K8s 1.30+).ShutdownTimeout plus preStop longer than terminationGracePeriodSeconds. Why it is wrong: The kubelet SIGKILLs the process mid-drain. Instead: Keep the sum a few seconds below the grace period.ShutdownTimeout without knowing request durations. Why it is wrong: Exports, uploads or report endpoints that take 40 s are cut off by a 15 s drain, and nobody notices until a customer complains. Instead: Query request duration percentiles per endpoint in Application Insights, size the drain for the long tail, and move genuinely long work to background jobs.startupProbe for slow starts.ENTRYPOINT (sh -c dotnet app.dll). Why it is wrong: The shell is PID 1 and may not forward SIGTERM, so the app never shuts down gracefully and is killed. Instead: Exec-form ENTRYPOINT ["dotnet", "app.dll"].maxUnavailable greater than zero with few replicas. Why it is wrong: Capacity drops during the rollout and remaining pods overload. Instead: maxUnavailable: 0 with a surge.This problem lives on the boundary between the platform and the app, which is why it survives so long: developers see a Kubernetes issue, platform engineers see an app issue. A senior owns the whole timeline and writes it down as numbers that must agree. The framework already does the hard part (draining Kestrel, cancelling stoppingToken, GOAWAY on HTTP/2); what it can't know is your routing propagation delay and request duration. Measure it: run a load test during kubectl rollout restart in CI or staging and fail the pipeline if any request errors.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
preStop sleep |
Every Kubernetes/Container Apps deployment | Slower rollouts and scale-in | Never really wrong |
Readiness flips on ApplicationStopping |
Proxies that probe frequently | A little code | When preStop alone covers propagation |
Long ShutdownTimeout (60 s+) |
Long-running requests or uploads | Very slow rollouts | Typical sub-second APIs |
| Client retries | Transient network faults | Duplicate side effects without idempotency | As the fix for deployment errors |
The Generic Host (IHost) is the common runtime shell for every modern .NET app, web or worker: it owns configuration, logging, dependency injection and the application lifetime. WebApplication.CreateBuilder(args) creates one with sensible defaults: appsettings.json, appsettings.{Environment}.json, user secrets in Development, environment variables and command-line args; console, debug and EventSource logging; and Kestrel. Build() freezes the service collection and builds the IServiceProvider. Run() starts hosted services, then the web server, and blocks until shutdown. On SIGTERM or Ctrl+C the host fires ApplicationStopping, stops accepting requests, lets in-flight ones finish, stops hosted services and exits within HostOptions.ShutdownTimeout (30 seconds by default). The trade-off: the defaults are great, but you must understand them to override them deliberately.
A load balancer spreads traffic across healthy instances.
Health checks remove unhealthy instances (in Kubernetes: readiness for traffic, liveness for restarts). Algorithms: round robin, least connections/requests, hashing. Sticky sessions pin a user to one instance, which hurts scaling and failover. Connection draining stops new traffic to an instance before shutdown so in-flight requests finish.
gRPC uses long-lived HTTP/2 connections, so an L4 balancer balances connections, not calls: one client connection carries all its calls to one pod. Use L7 balancing (mesh/Envoy) or client-side load balancing.
How to tell it (STAR)
**S:** Every deployment of our [order API on AKS] caused about 30 seconds of 502s that partners saw as outages. **T:** I took ownership of making deployments zero-downtime. **A:** I put ingress logs, pod events and Application Insights on one timeline, showed the errors started at pod termination, and reproduced it with k6 during a rollout. I added a preStop delay, aligned the shutdown timeout with the grace period, split readiness from liveness, and fixed a keep-alive mismatch with the ingress. **R:** Failed requests per rollout went from [about 1,500] to [zero] across the next [50] deployments, and a CI stage now fails any build that regresses it.
Last updated 23 Nov 2026.