📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Every time you deploy your ASP.NET Core API to Kubernetes (or Azure Container Apps), clients see a burst of 502 and 503 errors for about 30 seconds, then everything recovers. How do you diagnose it, and how do you fix it with graceful shutdown, HostOptions.ShutdownTimeout, readiness probes and connection draining?

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.

Senior Debugging Advanced aspnet-core deployment graceful-shutdown health-checks kestrel kubernetes

🎯 Key points

  • Kubernetes sends SIGTERM and removes the pod from Service endpoints in parallel, so traffic can arrive after the app started shutting down
  • Fix the race with a preStop delay (sleep 5-15 s) so ingress and kube-proxy stop routing before SIGTERM reaches the app
  • On SIGTERM the host stops accepting connections, lets existing connections finish in-flight requests (Connection: close / HTTP/2 GOAWAY) and stops hosted services within HostOptions.ShutdownTimeout (30 s default)
  • Rule: preStop + ShutdownTimeout + margin < terminationGracePeriodSeconds (30 s default), e.g. 10 + 15 < 35, or the pod is SIGKILLed
  • Size ShutdownTimeout from measured request durations (p99.9 from Application Insights), not a guess
  • Separate readiness (can I take traffic: dependencies warm, not stopping) from liveness (am I alive: no dependency checks)
  • New pods must not be ready until warm; old pods are removed only when new ones are ready (maxUnavailable 0, maxSurge)
  • 502s can also come from keep-alive mismatches: the app's keep-alive timeout must exceed the proxy's idle timeout

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 preStop hook 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 connection and connect() failed to the old pod IPs, with kubectl get events and the Application Insights failures, and they matched the termination timestamps exactly. The fixes were: a preStop sleep of 10 seconds so routing caught up before SIGTERM; HostOptions.ShutdownTimeout of 15 seconds so in-flight requests could finish, keeping 10 plus 15 inside a 35-second terminationGracePeriodSeconds; a readiness endpoint that only checks what's needed to serve and starts failing as soon as ApplicationStopping fires; liveness with no dependency checks; and maxUnavailable: 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."


The race, drawn out

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

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

Timeouts that must agree

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

Production example

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.

🔍 What the interviewer is checking

Checks production experience with zero-downtime deployments and the ability to reason across app, host and platform.

Green flags

  • Explains the SIGTERM/endpoint-removal race and the preStop delay.
  • Aligns ShutdownTimeout, preStop and terminationGracePeriodSeconds with numbers.
  • Separates readiness from liveness correctly.
  • Mentions keep-alive mismatch and exec-form entry points.
  • Verifies with a load test during a rollout.

Red flags

  • 'Add retries' as the fix.
  • Puts the database in liveness.
  • Doesn't know what happens on SIGTERM in ASP.NET Core.

📚 Learn in depth

1. Two parallel paths on termination

When a pod is deleted (rolling update, scale-in, node drain):

  1. The API server sets deletionTimestamp; the pod becomes Terminating.
  2. Path A (kubelet): runs the container's preStop hook, then sends SIGTERM to PID 1, waits up to terminationGracePeriodSeconds (counted from the start of preStop), then SIGKILL.
  3. Path B (networking): the EndpointSlice controller removes the pod's IP; kube-proxy on every node rewrites iptables/IPVS rules; ingress controllers (nginx, Application Gateway for Containers, Traefik) reload their upstream lists. This takes from under a second to many seconds.

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.

2. What ASP.NET Core does on SIGTERM

ConsoleLifetime registers a PosixSignalRegistration for SIGTERM and calls StopApplication():

  1. ApplicationStopping fires.
  2. Kestrel stops its listeners (new TCP connections are refused), sends Connection: close on HTTP/1.1 responses and GOAWAY on HTTP/2/HTTP/3, and waits for in-flight requests.
  3. Hosted services StopAsync in reverse order.
  4. If 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"].

3. Readiness, liveness and startup probes

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.

4. Keep-alive mismatch

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.

5. Rollout strategy

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.

Try it yourself

  1. Deploy a two-replica app to kind or minikube, run hey -z 60s or k6 against it, and trigger kubectl rollout restart; count non-2xx responses.
  2. Add preStop sleep 10 and repeat.
  3. Add a 20 s endpoint, start a request and delete the pod; check whether it completes with default and reduced grace periods.
  4. Use kubectl get events -w and ingress logs side by side during a rollout.
  5. Set Kestrel KeepAliveTimeout to 5 s behind nginx with a 60 s upstream keep-alive and watch for sporadic 502s under light load.

💻 Code

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 }

⚠ Common mistakes

  • Mistake: Adding client retries to hide deployment errors. Why it is wrong: It masks the cause and can double-submit non-idempotent POSTs. Instead: Fix the shutdown race; keep retries for genuinely transient faults with idempotency keys.
  • Mistake: No 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+).
  • Mistake: 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.
  • Mistake: Picking 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.
  • Mistake: Checking the database in the liveness probe. Why it is wrong: A database blip makes every pod fail liveness and restart at once. Instead: Liveness checks the process only; dependencies go in readiness.
  • Mistake: Readiness that passes as soon as the port opens. Why it is wrong: New pods get traffic before caches, connections or JIT warm-up, causing slow or failed requests. Instead: Report ready after warm-up; use a startupProbe for slow starts.
  • Mistake: Shell-form 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"].
  • Mistake: Lowering Kestrel's keep-alive below the proxy's idle timeout. Why it is wrong: The proxy reuses connections the server just closed and returns 502. Instead: Server idle timeout longer than the proxy's.
  • Mistake: 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.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions ApplicationStopping or HostOptions.ShutdownTimeout. Why: Checks the host-level shutdown sequence that this fix depends on.
    How to answer

    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.

  2. When: Candidate mentions the ingress or load balancer still routing to old pods. Why: Checks understanding of load balancer behaviour, health checks and connection reuse.
    How to answer

    A load balancer spreads traffic across healthy instances.

    • Layer 4 (TCP/UDP: Azure Load Balancer, AWS NLB, Kubernetes Services via kube-proxy) picks a backend per connection using IPs and ports. Fast, protocol-agnostic, no HTTP awareness.
    • Layer 7 (HTTP: App Gateway, ALB, Front Door, ingress controllers, Envoy, YARP) picks per request, can route by path/host/header, terminate TLS, retry and add headers.

    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.

🛠 Real-world problems: how you handle them

502 burst on every rolling deployment of an order API on AKS
Situation
An order API on [AKS in Australia East] handling [about 1,200 requests per second] behind ingress-nginx, deployed [several times a day]. Each rollout caused a short error burst that partner integrations reported as outages.
Signals
Application Insights showed failed request spikes of [1-2%] lasting [~30 s] aligned with deployments; ingress logs had `upstream prematurely closed connection` and `connect() failed (111: Connection refused)` to old pod IPs; synthetic availability tests failed during rollouts.
Investigation
Lined up `kubectl get events -w`, ingress-nginx logs and Application Insights failures on one timeline; confirmed errors started at pod termination. Found no `preStop` hook, a 30 s grace period equal to the host's 30 s timeout, readiness passing on port open, and a database check in liveness. A load test with `k6` during `kubectl rollout restart` in staging reproduced it reliably.
Resolution
Added a 10 s `preStop` sleep, set `ShutdownTimeout` to 15 s and the grace period to 35 s, made readiness fail on `ApplicationStopping` and pass only after warm-up, moved the database check out of liveness, set `maxUnavailable: 0`, and raised Kestrel's keep-alive above the ingress upstream keep-alive.
Prevention
A CI stage that runs k6 during a rollout in staging and fails on any non-2xx; a deployment checklist with the timeout arithmetic; an availability alert scoped to deployment windows; an ADR documenting probe semantics.

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.

↩ Usually asked after

More in ASP.NET Core Fundamentals

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me