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

πŸ“š Interview question

Explain liveness, readiness and startup probes in Kubernetes. What does the kubelet do when each one fails, how do initialDelaySeconds, periodSeconds, timeoutSeconds and failureThreshold interact, and how can badly configured probes cause or worsen an outage?

Covers the three Kubernetes probe types and their failure actions, the timing fields and how to calculate time-to-detect, and the common ways probe misconfiguration causes restart storms, slow rollouts and cascading outages for .NET services.

Intermediate Theory Intermediate aks health-checks kubernetes liveness-probe observability readiness-probe

🎯 Key points

  • Liveness failure → kubelet kills and restarts the container (subject to restartPolicy and CrashLoopBackOff)
  • Readiness failure → kubelet sets Ready=False; EndpointSlice controller removes the pod from the Service; no restart
  • Startup probe gates the other two until it succeeds; protects slow-starting apps
  • Time to act ≈ periodSeconds × failureThreshold (timeouts count as failures); defaults 10 s × 3, timeout 1 s; successThreshold must be 1 for liveness and startup
  • Trade-off: faster detection = more false restarts under load; tune liveness forgiving, readiness quicker
  • Shared dependency in liveness → restart storm across all pods
  • Readiness on a shared dependency → all pods NotReady → Service has no endpoints → total outage; prefer fail-fast fallbacks plus a human alert
  • Readiness must fail first on shutdown (preStop delay) so traffic drains before the app stops

⏱ 30-second answer

Kubernetes runs three probes per container. A liveness failure makes the kubelet restart the container. A readiness failure removes the pod from the Service's endpoints so it gets no traffic, with no restart. A startup probe disables the other two until it passes, so slow starts aren't killed.

The timing fields decide speed: the kubelet acts after failureThreshold consecutive failures, roughly periodSeconds Γ— failureThreshold (defaults 10 s Γ— 3), and each attempt fails if it exceeds timeoutSeconds (default 1 s).

Bad probes cause outages: a database check in liveness restarts every pod during a database blip; a 1-second timeout kills pods that are just busy under load, which pushes more load onto the rest; readiness tied to a shared dependency leaves the Service with zero endpoints. The trade-off is detection speed versus false positives.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"Kubernetes gives each container up to three probes, and the key is that they trigger different actions. If liveness fails failureThreshold times in a row, the kubelet kills the container and restarts it. If readiness fails, the kubelet marks the pod's Ready condition false, and the EndpointSlice controller then removes the pod from the Service, so kube-proxy and most ingress controllers stop sending it traffic, but nothing restarts. The startup probe runs first: until it succeeds, liveness and readiness are not run at all, so an app that needs 60 seconds to warm up isn't killed by a liveness probe tuned for steady state.

The timing fields combine. initialDelaySeconds waits before the first probe, periodSeconds is how often it runs, timeoutSeconds is how long one attempt may take before it counts as a failure, and failureThreshold is how many consecutive failures trigger the action. So with the defaults, once the container is past start-up (and past the startup probe, if there is one), a hung process is restarted roughly 30 seconds after it stops answering. For a startup probe I'd use something like period 5 and failureThreshold 30, giving the app up to 150 seconds to start once, and then a liveness probe that's fairly forgiving. It's a trade-off: tighter settings detect a hang sooner but restart healthy pods that are just busy.

The mistake I see is treating probes as monitoring. They are automation that kills and drains pods, so a wrong probe actively causes outages. The classic ones are a database check in liveness, which restarts every pod when the database fails over; a 1-second timeout on an endpoint that slows down under load, so the busiest pods get killed and the survivors get even more load; and readiness that depends on a shared service, so every pod goes NotReady together and the Service has no endpoints at all. My rule is: liveness only fails when a restart would fix it, and readiness only reflects this pod's ability to serve; anything that would fail on every pod at once is an alert for a human."


What each probe does on failure

Probe Runs On failure Typical .NET endpoint
startupProbe From container start until first success After threshold: container killed and restarted /health/startup (warm-up done) or the liveness endpoint
livenessProbe After startup succeeds, for the life of the container Container killed and restarted; repeated restarts β†’ CrashLoopBackOff /health/live (no dependency checks)
readinessProbe After startup succeeds, for the life of the container Pod Ready=False β†’ removed from Service endpoints; no restart /health/ready (critical dependencies, warm-up)

Who does what

Component Role
kubelet (on the node) Runs the probes, restarts containers on liveness/startup failure, sets the pod's Ready condition
EndpointSlice controller (control plane) Watches Ready and adds or removes the pod IP from the Service's EndpointSlices
kube-proxy, ingress, service mesh Watch EndpointSlices and update routing; this propagation takes seconds

The timing fields

Field Default Meaning
initialDelaySeconds 0 Wait before the first probe (prefer a startup probe over a big delay)
periodSeconds 10 Interval between probes
timeoutSeconds 1 Max time for one attempt; a timeout counts as a failure
failureThreshold 3 Consecutive failures before acting
successThreshold 1 Consecutive successes to count as recovered. Only meaningful for readiness; the API rejects any value other than 1 for liveness and startup probes

Approximate time to act after the process stops answering: periodSeconds Γ— failureThreshold (plus up to timeoutSeconds per attempt). Liveness and readiness clocks only start once the startup probe has succeeded. Maximum start-up allowance with a startup probe: periodSeconds Γ— failureThreshold.

How probes cause outages

Misconfiguration What happens
Dependency in liveness Database failover β†’ all pods restart at once β†’ cold starts, connection storms on recovery
Timeout too tight (1 s) Under load or during a Gen2 GC pause the probe times out; kubelet kills busy pods; remaining pods get more load; spiral
No startup probe, large app Liveness kills the app during EF Core model build / cache warm-up β†’ CrashLoopBackOff on every deploy
Readiness on a shared dependency Every pod NotReady together β†’ Service has zero endpoints β†’ 503 from ingress for all requests, even ones that didn't need the dependency
Readiness same as liveness Can't drain without restarting; restarts where draining was enough
No readiness at all Pods get traffic before they can serve; errors on every rollout

To avoid the zero-endpoints case, keep shared dependencies out of readiness (or mark them Degraded), let the app fail fast with a circuit breaker and fallback, and page a human based on the error SLO.

Production example

On an AKS cluster running [20] API pods, liveness pointed at a health endpoint that also ran a SQL check, with timeoutSeconds: 1. During a [Monday 9 am] peak, SQL latency rose to [1.5 s], probes timed out and the kubelet restarted [14 of 20] pods within two minutes; the outage lasted [11 minutes]. After moving SQL to readiness, giving liveness a no-op endpoint with timeoutSeconds: 3 and adding a startup probe, the next SQL slowdown caused zero restarts.

πŸ” What the interviewer is checking

Checks the candidate understands that probes trigger automated actions and can tune them to avoid self-inflicted outages.

Green flags

  • States the different action for each probe (restart vs remove from endpoints vs gate)
  • Calculates time-to-act from period, timeout and threshold
  • Describes at least two concrete probe-caused outages (restart storm, zero endpoints, busy pods killed)
  • Links readiness to rollouts and graceful shutdown

Red flags

  • Thinks readiness failure restarts the pod
  • Puts the database check in liveness
  • Uses initialDelaySeconds: 120 as the fix for slow starts

πŸ“š Learn in depth

1. Who runs the probes

Probes are run by the kubelet on the node, not by the control plane. The kubelet calls the container's IP directly (HTTP GET, TCP socket, gRPC or exec) and updates the pod status.

kubelet ──HTTP GET /health/live──► container
   β”‚
   β”œβ”€ liveness fails Γ— threshold ──► kill container (SIGTERM, grace period, SIGKILL) ──► restart
   β”‚                                       restarts back off: 10s, 20s, 40s ... max 5 min = CrashLoopBackOff
   β”‚
   └─ readiness fails ──► pod condition Ready=False
                             β”‚
                             β–Ό
                 EndpointSlice controller removes pod IP
                             β”‚
                             β–Ό
          kube-proxy / ingress / service mesh stop routing to it

Removal from endpoints is eventually consistent: it takes time for every node's kube-proxy and the ingress controller to see the change. That is why graceful shutdown needs a short delay (a preStop sleep) before the app stops accepting connections.

2. Startup probes and slow .NET starts

A .NET app can take a while to be ready: JIT of hot paths, EF Core model building, loading configuration from Azure App Configuration and Key Vault, warming caches. Before startup probes, people set initialDelaySeconds: 90 on liveness, which also slowed detection of real crashes on every start. A startup probe allows a long window only once:

startupProbe:   period 5s Γ— failureThreshold 30 = up to 150 s to start
livenessProbe:  period 10s Γ— failureThreshold 3 = ~30 s to detect a hang (only after startup succeeds)

ReadyToRun or Native AOT shortens start time and reduces the window you need.

3. Why timeouts kill busy pods

The probe goes through the same Kestrel and thread pool as user requests. If the thread pool is starved (sync-over-async) or a long blocking GC pause happens, the probe can take longer than timeoutSeconds even though the process is fine. Under load this means the busiest pods fail liveness first. When they restart, their traffic moves to the others, which then also fail: a positive feedback loop. Mitigations: liveness endpoint does no I/O, a 2-5 s timeout, a higher failureThreshold, and fix the starvation.

4. Readiness and the zero-endpoints outage

If every pod's readiness depends on the same thing (the database, a downstream API), a failure of that thing makes every pod NotReady at once. The Service then has no endpoints and the ingress returns 503 for everything, including health pages, static content and endpoints that didn't need the dependency. Often it is better for the pods to stay ready and return fast errors or fallbacks (with a circuit breaker) so the app can degrade gracefully, and to alert a human.

5. Probes and rollouts

The Deployment's rolling update waits for new pods to be Ready (and minReadySeconds) before removing old ones. A readiness probe that passes before the app can serve means bad versions roll out fully; one that never passes means the rollout stalls at maxSurge, which is the safe failure. progressDeadlineSeconds marks the rollout as failed so CI/CD can roll back.

6. Probe types

Type Use
httpGet Most ASP.NET Core apps; 200-399 = success
grpc gRPC services implementing the gRPC health protocol (Grpc.AspNetCore.HealthChecks)
tcpSocket Only checks the port is open; weak for HTTP apps
exec Runs a command in the container; costly and needs a shell (not in chiseled images)

Try it yourself

  1. Deploy a sample API to kind or AKS with a liveness probe that calls an endpoint with Thread.Sleep(1500). Watch kubectl get pods -w and kubectl describe pod events as restarts happen.
  2. Add a startup probe with failureThreshold: 30, add a 60-second Task.Delay at start-up and confirm the container isn't killed.
  3. Make readiness depend on a fake dependency, break it, and run kubectl get endpointslices -l kubernetes.io/service-name=api to see endpoints disappear.
  4. Query restarts in Prometheus: increase(kube_pod_container_status_restarts_total{namespace="orders"}[15m]).
  5. In Container insights, run a KQL query on KubePodInventory for pods whose ContainerRestartCount increased in the last hour.

πŸ’» Code

A Deployment with all three probes pointing at separate ASP.NET Core endpoints, and the matching Program.cs.

# deployment.yaml (excerpt)
spec:
  template:
    spec:
      terminationGracePeriodSeconds: 40
      containers:
        - name: orders-api
          image: myacr.azurecr.io/orders-api:1.8.3
          ports:
            - containerPort: 8080   # public traffic
            - containerPort: 8081   # management: health only, not in the Service
          startupProbe:
            httpGet: { path: /health/startup, port: 8081 }
            periodSeconds: 5
            failureThreshold: 30     # up to 150 s for warm-up, once
          livenessProbe:
            httpGet: { path: /health/live, port: 8081 }
            periodSeconds: 10
            timeoutSeconds: 3        # tolerate GC pauses and load
            failureThreshold: 3      # ~30 s to restart a hung process
          readinessProbe:
            httpGet: { path: /health/ready, port: 8081 }
            periodSeconds: 5
            timeoutSeconds: 2
            failureThreshold: 2      # drain quickly
          lifecycle:
            preStop:
              sleep: { seconds: 10 } # let endpoint removal propagate before shutdown (Kubernetes 1.30+)
// Program.cs (.NET 10)
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.Diagnostics.HealthChecks;

var builder = WebApplication.CreateBuilder(args);
builder.WebHost.UseUrls("http://+:8080", "http://+:8081");

builder.Services.AddSingleton<WarmupState>();
builder.Services.AddHostedService<CacheWarmup>();
builder.Services.AddHealthChecks()
    .AddCheck<WarmupCheck>("warmup", tags: ["startup", "ready"])
    .AddDbContextCheck<OrdersDbContext>("sql", tags: ["ready"]);

var app = builder.Build();

// /health/live: runs no checks. 200 "Healthy" whenever Kestrel can answer.
// If it can't answer within 3 s three times, the kubelet restarts the container.
app.MapHealthChecks("/health/live", new HealthCheckOptions { Predicate = _ => false })
   .RequireHost("*:8081");

// /health/startup: 503 until WarmupCheck reports Healthy (caches loaded), then 200.
// While it returns 503, liveness and readiness are not run.
app.MapHealthChecks("/health/startup", new HealthCheckOptions { Predicate = r => r.Tags.Contains("startup") })
   .RequireHost("*:8081");

// /health/ready: 200 when warm-up is done and SQL is reachable; 503 otherwise,
// which removes the pod from the Service without restarting it.
app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
    Predicate = r => r.Tags.Contains("ready"),
    ResultStatusCodes =
    {
        [HealthStatus.Healthy] = StatusCodes.Status200OK,
        [HealthStatus.Degraded] = StatusCodes.Status200OK,   // degraded still serves traffic
        [HealthStatus.Unhealthy] = StatusCodes.Status503ServiceUnavailable
    }
}).RequireHost("*:8081");

app.Run();

⚠ Common mistakes

  • Mistake: Checking the database or downstream services in liveness. Why it is wrong: a shared failure restarts every pod at once and slows recovery. Instead: liveness with no dependency checks; dependencies in readiness or in alerts.
  • Mistake: Leaving timeoutSeconds at the 1-second default for an endpoint that does I/O. Why it is wrong: load, GC pauses or thread-pool starvation make healthy pods fail and get killed when you need them most. Instead: no I/O in liveness, 2-5 s timeouts, failureThreshold of 3 or more.
  • Mistake: Using a large initialDelaySeconds instead of a startup probe. Why it is wrong: it delays detection on every start and is still too short on a slow node. Instead: a startup probe with periodSeconds Γ— failureThreshold covering the worst start.
  • Mistake: The same endpoint for liveness and readiness. Why it is wrong: a temporary inability to serve leads to restarts instead of draining. Instead: separate endpoints with different checks.
  • Mistake: Readiness that fails on every pod when a shared dependency is down. Why it is wrong: the Service ends up with zero endpoints and even unaffected endpoints return 503. Instead: keep pods ready, fail fast with circuit breakers and fallbacks, and page a human.
  • Mistake: No readiness probe. Why it is wrong: new pods get traffic before warm-up and rollouts don't wait for health. Instead: always define readiness for anything behind a Service.
  • Mistake: Using an exec probe in a chiseled or distroless .NET image. Why it is wrong: there is no shell or curl, so the probe always fails. Instead: httpGet or grpc probes.

πŸ› Senior insight: trade-offs

Probes are control loops, not dashboards. Every probe answers "what should the platform do automatically?", and an automatic action that applies to every replica at once is a risk multiplier. I design them by asking what a failure means for one pod versus all pods: if all pods would fail together, the right reaction is usually a human alert, not a mass restart or drain.

Setting When it fits Cost When not to
Aggressive liveness (5 s Γ— 2) Tiny stateless services that hang rarely and start in seconds False restarts under load Anything with GC pauses, warm-up or bursty load
Forgiving liveness (10 s Γ— 3, 3 s timeout) Most ASP.NET Core APIs ~30-40 s to detect a real hang Never really wrong as a default
Startup probe Apps that take > 10 s to warm up Config complexity Native AOT apps that start in < 1 s (still harmless)
Readiness with dependencies Hard per-pod dependency (local sidecar, per-pod cache) Drains on dependency issues Shared dependencies with no per-pod difference

I measure probes like any other change: restart counts, readiness flaps and rollout durations per deployment, with an alert on increase(kube_pod_container_status_restarts_total[15m]) > 3.

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate talks about which dependencies belong in each check. Why: Checks they can design health checks for a fleet and avoid cascades at the architecture level.
    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.

  2. When: Candidate mentions CrashLoopBackOff or restarts. Why: Checks they can debug a crash loop and tell a probe misconfiguration from an app failure.
    How to answer

    CrashLoopBackOff means the container keeps exiting and the kubelet is backing off restarts (up to 5 minutes). I start with kubectl describe pod: Last State, Reason and Exit Code, plus events. Then kubectl logs <pod> --previous to see the crashed container's output.

    The exit code points the way: 1 is usually an unhandled .NET exception at startup (missing config, Key Vault 403, failed migration); 137 is SIGKILL, either OOMKilled (Reason says so) or a liveness probe kill (events say "Liveness probe failed"); 139 is a native crash.

    For OOMKilled I compare working set to the limit with Container Insights and dotnet-counters, then decide if it's a leak, native memory or a limit that's too small. Fix the cause; don't just raise the limit.

  3. When: Candidate mentions readiness during deployments or preStop. Why: Checks they understand graceful shutdown and endpoint propagation delay during rollouts.
    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.

↩ Usually asked after

More in Health and Alerts

Last updated 23 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me