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

📚 Interview question

How do graceful shutdown and container readiness work for an ASP.NET Core service on Kubernetes or Azure Container Apps? Explain what happens from SIGTERM to process exit, the role of IHostApplicationLifetime and HostOptions.ShutdownTimeout, connection draining, and how startup and readiness probes stop traffic reaching a pod that is not ready.

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.

Mid-Level Theory Intermediate azure-container-apps cloud-native generic-host graceful-shutdown health-checks kubernetes

🎯 Key points

  • Kubernetes sends SIGTERM, waits terminationGracePeriodSeconds (30 s default), then SIGKILL
  • Endpoint removal and SIGTERM happen in parallel: a preStop delay (5-10 s) avoids 502s during propagation
  • Generic Host: ApplicationStopping, Kestrel stops accepting and drains, IHostedService.StopAsync in reverse order
  • HostOptions.ShutdownTimeout (30 s default) must be less than the platform's grace period
  • BackgroundService must honour the stopping token and checkpoint or release in-flight work
  • Startup probe protects slow starts; readiness controls traffic; liveness restarts only a stuck process
  • Readiness should fail during shutdown and before warm-up completes; liveness should not check dependencies
  • Run as PID 1 directly (exec-form ENTRYPOINT) so the process actually receives SIGTERM

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 preStop sleep of around 5 to 10 seconds. Then the .NET Generic Host takes over: SIGTERM fires ApplicationStopping, Kestrel stops accepting connections and lets in-flight requests finish, hosted services get StopAsync with a cancellation token, and the whole thing is capped by HostOptions.ShutdownTimeout, 30 seconds by default. That timeout plus the preStop delay must fit inside terminationGracePeriodSeconds, 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."


From SIGTERM to exit

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

Probes and what each should check

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

Azure Container Apps

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.

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate understands the container lifecycle end to end and can size the timeouts so deploys cause no errors.

Green flags

  • Knows endpoint removal and SIGTERM race, and uses a preStop delay
  • Names ApplicationStopping, ShutdownTimeout and the 30 s defaults, and how they must fit together
  • Gives each probe a distinct job and keeps dependencies out of liveness
  • Mentions PID 1 / exec-form entrypoints and background work honouring cancellation

Red flags

  • Thinks the app only needs to handle Ctrl+C
  • Puts database checks in liveness
  • Has never measured errors during a rollout

📚 Learn in depth

1. The two races in a pod's life

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.

2. How .NET receives SIGTERM

The Generic Host's ConsoleLifetime registers handlers using PosixSignalRegistration for SIGTERM, SIGINT and SIGQUIT. On SIGTERM it calls IHostApplicationLifetime.StopApplication(), which:

  1. Fires ApplicationStopping callbacks.
  2. Calls IHost.StopAsync with a token that cancels after HostOptions.ShutdownTimeout.
  3. Stops hosted services in reverse registration order. Kestrel's server is a hosted service, so it stops accepting connections and waits for in-flight requests; HTTP/1.1 keep-alive connections get Connection: close, HTTP/2 connections get GOAWAY.
  4. Fires 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.

3. PID 1 and signal delivery

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.

4. Background work

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.

5. Health check endpoints in ASP.NET Core

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.

6. Sizing the numbers

terminationGracePeriodSeconds >= preStop + ShutdownTimeout + margin
             40               >=   10   +       25        +   5

Set ShutdownTimeout from your p99 request duration and longest message handler, not by guessing.

Try it yourself

  1. Run an API in Docker, start a 20-second request, then docker stop (SIGTERM, 10 s default) and see the request cut off; retry with docker stop -t 40.
  2. Switch the Dockerfile to shell-form ENTRYPOINT and observe the app never logging ApplicationStopping.
  3. Deploy two replicas to a local kind cluster, run hey or k6 against the Service and do kubectl rollout restart; count non-2xx with and without a preStop sleep.
  4. Add a readiness check that fails after ApplicationStopping and watch kubectl get endpoints during a rollout.
  5. Log timestamps of SIGTERM, ApplicationStopping and ApplicationStopped to measure your real drain time.

💻 Code

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

⚠ Common mistakes

  • Mistake: Exiting as soon as SIGTERM arrives with no preStop delay. Why it is wrong: Load balancers still route to the pod for a few seconds, so those requests get 502 or connection resets. Instead: Add a 5-10 s preStop sleep and fail readiness on ApplicationStopping.
  • Mistake: Leaving 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.
  • Mistake: Using shell-form 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.
  • Mistake: Checking the database in the liveness probe. Why it is wrong: A database blip restarts every pod at once and turns a slowdown into an outage. Instead: Liveness checks only the process; dependencies belong in readiness, if anywhere.
  • Mistake: No startup probe for a slow-starting service. Why it is wrong: Liveness kills the container before it finishes starting, causing CrashLoopBackOff. Instead: Add a startup probe with enough failureThreshold × periodSeconds.
  • Mistake: A 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.
  • Mistake: Readiness that passes as soon as Kestrel listens. Why it is wrong: The first requests hit cold caches and a JIT-cold app, causing latency spikes on every deploy. Instead: Flip readiness only after warm-up completes.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions 502s during deployments Why: Checks they can diagnose deploy-time errors from symptoms to fix.
    How to 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.

  2. When: Candidate mentions readiness and liveness probes Why: Checks they can design truthful health checks across a fleet without cascading restarts.
    How to answer

    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.

  3. When: Candidate mentions background workers or queue consumers during shutdown Why: Checks graceful shutdown and idempotency for message processing on Kubernetes.
    How to answer

    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.

🛠 Real-world problems: how you handle them

502 burst on every rolling deploy
Situation
An ASP.NET Core orders API on AKS with [8] replicas behind an NGINX ingress, deployed [10] times a week. A partner integration had an SLO of 99.9% success.
Signals
Every deploy produced a burst of 502 and 503 responses at the ingress for about 20-30 seconds; Application Insights showed no matching exceptions in the app, and the partner's error-budget burn alert fired after each release.
Investigation
Correlated ingress logs with `kubectl get events` and pod termination times: errors started at the moment pods received SIGTERM. App logs showed `ApplicationStopping` and exit within one second, while the ingress kept routing to the terminated pod's IP for several more seconds. The Dockerfile used exec form, so signals arrived correctly; the issue was the propagation race.
Resolution
Added a 10-second preStop sleep, a readiness check that fails on `ApplicationStopping`, set `ShutdownTimeout` to 25 s and `terminationGracePeriodSeconds` to 40, and added a startup probe so new pods only received traffic after warm-up.
Prevention
A pipeline stage that runs a k6 load test through `kubectl rollout restart` in staging and fails on any non-2xx; a dashboard of ingress 5xx annotated with deploy markers; the timeout numbers recorded in the service template.

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.

↩ Usually asked after

More in Cloud-Native Patterns

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me