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

📚 Interview question

A .NET 10 pod is stuck in CrashLoopBackOff, and another one is restarting with OOMKilled. Walk me through how you debug each with kubectl, logs and events, and how you tell an app startup failure from a probe misconfiguration or a memory problem.

Debugging CrashLoopBackOff and OOMKilled .NET pods: kubectl describe, events, logs --previous, exit codes (1, 134, 137, 139), probe failures versus startup exceptions, missing configuration or identity, debug containers and dotnet-dump, and prevention.

Mid-Level Debugging Intermediate containers crashloopbackoff debugging devops kubernetes oomkilled

🎯 Key points

  • CrashLoopBackOff = container keeps exiting; restart backoff starts at 10 s and doubles to a 5-minute cap (resets after 10 minutes running)
  • kubectl describe pod: Last State, Reason, Exit Code, events (probe failures, image pull)
  • kubectl logs --previous shows the crashed container's output; JSON stdout logs survive when telemetry doesn't flush
  • Exit codes: 0 clean exit (a problem for a service that should keep running), 1 unhandled exception, 134 SIGABRT, 137 SIGKILL (OOM or liveness kill), 139 segfault, 143 SIGTERM
  • App vs config vs probe: stack trace in previous logs = app/config (OptionsValidationException, Key Vault 403); 'Liveness probe failed' events = probe
  • OOMKilled = kernel killed it for exceeding the memory limit; compare working set to limit (kubectl top pod --containers, Container Insights) and GC heap (dotnet-counters)
  • Common .NET causes: missing config/secret, identity/RBAC, migrations at startup, wrong port, slow startup with no startup probe
  • kubectl debug ephemeral container + dotnet-counters / dotnet-gcdump / dotnet-dump for live analysis

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"CrashLoopBackOff isn't an error in itself; it's Kubernetes saying 'this container keeps dying, so I'm waiting longer between restarts', 10 seconds, 20, 40, up to five minutes. So the first job is to find out how it died. I run kubectl describe pod, look at the container's Last State: the reason, the exit code and the timestamps, and read the events at the bottom. Then kubectl logs <pod> --previous, because the current container might have just started and has nothing useful yet.

The exit code splits the problem. Exit code 1 with a stack trace in the previous logs is the app throwing during startup: in .NET that's usually an options validation failure from ValidateOnStart, a missing connection string, a 403 from Key Vault because the workload identity isn't federated, or EF Core migrations running at startup against a database it can't reach. Exit code 137 means SIGKILL. If the reason is OOMKilled, the kernel killed it for crossing the memory limit. If the reason is Error or the events show 'Liveness probe failed' then 'Killing', Kubernetes killed a healthy-but-slow app, typically because there's no startup probe and the liveness probe starts checking before the app is ready. Exit 143 is a normal SIGTERM, and 139 is a segfault in native code.

For OOMKilled, I compare memory over time in Container Insights with the limit, and check whether it's a gradual climb, which suggests a leak, or a spike at a specific request. I attach kubectl debug with an SDK image and run dotnet-counters and dotnet-gcdump to see if the managed heap is growing or if it's native memory. For example, at [company] a [worker] was OOMKilled every [40 minutes]; the managed heap was flat at [150 MB] but working set climbed to the [512 Mi] limit. It was [a native buffer from an image library not being disposed]. The mistake I see is doubling the memory limit and calling it fixed: that only stretches the time between crashes."


Exit codes and what they mean

Exit code Signal Usual meaning for .NET Where to look
0 — App ended normally (worker finished, no host) Program flow; restartPolicy
1 — Unhandled exception kubectl logs --previous
134 SIGABRT Runtime abort (fatal error, failed assert, stack overflow) Logs, crash dump
137 SIGKILL OOMKilled, or killed after failed liveness probe / grace period describe: Reason and events
139 SIGSEGV Native crash (interop, native library) Crash dump
143 SIGTERM Graceful stop requested Normal during rollouts

Symptom to cause

What you see Likely cause Fix
Exit 1, OptionsValidationException Missing or bad config Fix ConfigMap/secret, check env var names (__)
Exit 1, AuthenticationFailedException / 403 from Key Vault Workload identity or RBAC Federated credential, role assignment
Events: Liveness probe failed, Killing Probe too early or checks dependencies Add startup probe; liveness checks process only
Readiness probe failed but no restarts App up but not ready Check dependency or port; not a crash loop
Reason OOMKilled Memory over limit Leak, native memory, or real need; measure first
ImagePullBackOff (not a crash loop) Wrong tag or no ACR pull rights Fix tag, attach ACR to AKS
Exit 0 repeatedly Process exits (e.g. no app.Run(), worker loop ends) Keep host running; use a Job for one-off work

Production example

A rollout of a new API version went into CrashLoopBackOff on all new pods. logs --previous showed OptionsValidationException: Payments:ApiBaseUrl is required; the new setting had been added to appsettings.Development.json but not to the ConfigMap. Because maxUnavailable was 0 the old pods kept serving, so impact was zero; adding the value fixed it in 4 minutes.

🔍 What the interviewer is checking

Checks whether the candidate has a systematic method for crashing pods and can read Kubernetes signals correctly.

Green flags

  • Starts with describe and logs --previous
  • Uses exit codes and Reason to separate exception, probe kill and OOM
  • Knows startup probes and process-only liveness
  • Distinguishes OutOfMemoryException from OOMKilled and measures native memory
  • Mentions kubectl debug and dotnet diagnostic tools

Red flags

  • Restarts or deletes pods hoping it goes away
  • Raises limits without measuring
  • Doesn't know where startup logs are

📚 Learn in depth

## 1. Pod lifecycle and backoff ``` Pending ─▶ ContainerCreating ─▶ Running ──(exit)──▶ Terminated ▲ │ └── restart after backoff (10s, 20s, 40s ... 5m) status shows CrashLoopBackOff while waiting ``` The backoff resets after the container runs successfully for 10 minutes. `restartCount` in `kubectl get pods` tells you how long it's been going on. ## 2. Where the evidence lives | Source | Command | Shows | |---|---|---| | Pod status | `kubectl describe pod

` | Last State, Reason, Exit Code, probe config, events | | Previous logs | `kubectl logs

-c api --previous` | stdout/stderr of the crashed run | | Events | `kubectl get events --sort-by=.lastTimestamp` | Probe failures, OOM, scheduling, image pulls | | Node | `kubectl describe node` | Memory pressure, evictions | | Telemetry | Container Insights, Log Analytics (`KubePodInventory`, `ContainerLogV2`) | Restarts and logs over time | | Application Insights | Exceptions, traces | Startup exceptions if the SDK initialised in time | Startup exceptions often happen **before** Application Insights or OpenTelemetry exporters flush, so stdout logs (`kubectl logs --previous` or `ContainerLogV2`) are the most reliable source. Writing console logs in JSON helps. ## 3. Probes that kill healthy apps Without a **startup probe**, the liveness probe starts after `initialDelaySeconds`. A .NET app doing JIT, warming caches or running migrations may take 20–40 s on a small CPU limit. Liveness fails `failureThreshold` times, the kubelet sends SIGTERM, then SIGKILL after the grace period: exit 137 with no OOM. The fix is a startup probe with `failureThreshold × periodSeconds` greater than the worst start time, and a liveness check that doesn't touch dependencies. ## 4. OOMKilled in .NET - The kernel kills the whole container when total memory (managed heap + native + page cache that can't be reclaimed) exceeds `memory.max`. - The GC's hard limit (75% of the container limit by default) protects only the managed heap. If the heap hits it, you get `OutOfMemoryException` (exit 1 or 134), not OOMKilled. - So OOMKilled with a modest heap points at native memory: unmanaged buffers, many threads (1 MB+ stack each), native libraries, or memory-mapped files. - Tools: `dotnet-counters` (working set versus `gc-heap-size`), `dotnet-gcdump` for managed growth, `dotnet-dump` + `!eeheap`/`!dumpheap -stat`, and for native growth, comparing `/proc/1/smaps_rollup` over time. ## 5. Debugging a crashing or chiseled container If the container exits too fast to `exec` into, temporarily override the command (`command: ["sleep", "3600"]`) in a copy of the pod with `kubectl debug

💻 Code

The commands I run, in order:

# 1. What state, how many restarts?
kubectl get pods -n orders -l app=orders-api

# 2. Why did the last container die? Look at Last State, Reason, Exit Code and Events
kubectl describe pod orders-api-7d9f8-abcde -n orders

# 3. What did it print before dying?
kubectl logs orders-api-7d9f8-abcde -n orders -c api --previous

# 4. Recent events across the namespace (probe failures, OOM, image pulls)
kubectl get events -n orders --sort-by=.lastTimestamp | tail -20

# 5. Memory against the limit (needs metrics-server)
kubectl top pod -n orders --containers

# 6. Attach .NET diagnostics to a running pod via an ephemeral container
kubectl debug -it orders-api-7d9f8-abcde -n orders \
  --image=mcr.microsoft.com/dotnet/sdk:10.0 --target=api -- bash
#   dotnet tool install -g dotnet-counters && ~/.dotnet/tools/dotnet-counters monitor -p 1

Make startup failures loud and readable, and probes honest:

using Microsoft.Extensions.Options;

var builder = WebApplication.CreateBuilder(args);

// Fail fast at startup with a clear message instead of failing on the first request
builder.Services.AddOptions<PaymentsOptions>()
    .BindConfiguration("Payments")
    .ValidateDataAnnotations()
    .ValidateOnStart();

builder.Logging.AddJsonConsole(); // stdout survives in 'kubectl logs --previous' and ContainerLogV2
builder.Services.AddHealthChecks();

var app = builder.Build();
app.MapHealthChecks("/healthz/live");
app.Run();

public sealed record PaymentsOptions
{
    [System.ComponentModel.DataAnnotations.Required, System.ComponentModel.DataAnnotations.Url]
    public string ApiBaseUrl { get; init; } = "";
}
# Startup probe gives a slow-starting app up to 60 s before liveness takes over
startupProbe:
  httpGet: { path: /healthz/live, port: 8080 }
  periodSeconds: 2
  failureThreshold: 30
livenessProbe:
  httpGet: { path: /healthz/live, port: 8080 }
  periodSeconds: 10
  failureThreshold: 3
// Log Analytics: restarts and OOM kills in the last day
KubePodInventory
| where TimeGenerated > ago(1d) and Namespace == "orders"
| summarize Restarts = max(ContainerRestartCount) by Name, ContainerLastStatus
| order by Restarts desc

⚠ Common mistakes

  • Mistake: Reading kubectl logs without --previous. Why it is wrong: You see the new container's startup, not the crash. Instead: Always check --previous for a crash loop.
  • Mistake: Treating every exit 137 as OOM. Why it is wrong: Liveness-probe kills and grace-period kills are also SIGKILL. Instead: Read the Reason field and the events.
  • Mistake: Raising the memory limit as the fix for OOMKilled. Why it is wrong: A leak just takes longer to kill the pod, and you pay for the memory. Instead: Measure managed versus native growth, fix the leak, then size.
  • Mistake: No startup probe on a slow-starting app. Why it is wrong: Liveness kills it before it finishes starting, so it never becomes ready. Instead: A startup probe sized for the worst start time.
  • Mistake: Running EF Core migrations in Program.cs on every pod. Why it is wrong: Several replicas race, one fails, and a schema problem becomes a crash loop. Instead: Run migrations once in a pipeline step or a Kubernetes Job with a migration bundle.
  • Mistake: Relying on Application Insights for startup errors. Why it is wrong: The process can die before telemetry is flushed. Instead: Log to stdout and query ContainerLogV2.
  • Mistake: Confusing ImagePullBackOff or Pending with CrashLoopBackOff. Why it is wrong: Those mean the container never started; app logs won't exist. Instead: Check events for pull or scheduling errors.

🏛 Senior insight: trade-offs

A crash loop is a symptom; the useful skill is narrowing it down in a fixed order: describe, previous logs, events, metrics, then live diagnostics. I also design for it: ValidateOnStart so config errors fail fast and clearly, JSON stdout logs, startup probes, migrations out of the app process, and rollouts with maxUnavailable: 0 so a bad version never takes the old pods down.

Symptom First check Common fix Don't
Exit 1 crash loop logs --previous Config, identity, dependency at startup Disable ValidateOnStart to make it start
Exit 137 + probe events Probe settings Startup probe, process-only liveness Remove probes
OOMKilled Working set versus heap over time Fix leak or native usage, then size Double the limit blindly
Exit 0 loop Program flow Keep host alive or use a Job Add while(true) hacks

I measure restart counts per deployment, OOMKilled events and mean time to diagnosis in post-incident reviews.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions OOMKilled with a small GC heap Why: Checks deeper understanding of working set, native memory and the GC heap
    How to answer

    RAM is physical memory. Each process gets a virtual address space that the OS maps onto RAM page by page. The working set is what's resident in RAM right now; private (committed) memory is what the process owns. The GC heap is only one part: native allocations (native libraries, NativeMemory, unmanaged buffers), thread stacks, JIT code, and runtime structures add to it. In Kubernetes, the cgroup limit counts all of it, and going over gets the container OOMKilled (exit code 137), not an OutOfMemoryException. So if the GC heap is small but the pod dies, I compare GC heap size with working set in dotnet-counters. A big gap points to native memory or too many threads; a growing GC heap points to a managed leak I'd chase with dotnet-gcdump. Then I fix the cause and set limits and GC settings deliberately.

  2. When: Candidate mentions capturing a dump Why: Checks they can capture and analyse a memory dump in production
    How to answer

    When I can't attach a debugger, I take a dump: a snapshot of the process's memory, threads and stacks that I analyse offline. For a hang or a leak, dotnet-dump collect -p <pid> does it in seconds. For crashes, I enable automatic crash dumps with the DOTNET_DbgEnableMiniDump environment variables. On App Service I use Diagnose and solve problems, and in Kubernetes dotnet-monitor. Then I analyse with dotnet-dump analyze: clrstack -all and syncblk for hangs, dumpheap -stat and gcroot for leaks, pe for exceptions. Or I open the dump in Visual Studio and use the Threads and Parallel Stacks windows. Dumps contain customer data, so they're handled as sensitive.

  3. When: Candidate says the app fails at startup with a Key Vault 403 Why: Checks they can diagnose managed identity and RBAC failures
    How to answer

    On a laptop, DefaultAzureCredential uses my az login identity, which has broad dev rights. In Azure it uses the app's managed identity, which may not exist, may be the wrong one, or may lack roles. I diagnose in layers:

    1. Which identity? Is managed identity enabled, and for user-assigned, is AZURE_CLIENT_ID set?
    2. Authorisation: read the error code. Key Vault ForbiddenByRbac means missing Key Vault Secrets User (or the vault uses access policies). SQL's <token-identified principal> means the token worked but there is no contained database user.
    3. Network: ForbiddenByFirewall or ForbiddenByConnection means firewall or private endpoint and DNS problems.

    The trade-off: granting broad roles makes the error go away fast but breaks least privilege; the right fix is the exact data role at the exact scope.

🛠 Real-world problems: how you handle them

Worker OOMKilled every 40 minutes with a flat managed heap
Situation
A [document-processing] .NET 10 worker on AKS, [4] replicas with a [512 Mi] memory limit, generating [thumbnails] from Service Bus messages. Backlog growth delays [customer uploads].
Signals
Pods restarting with Reason `OOMKilled`, exit code 137, roughly every [40] minutes per pod. Service Bus active message count climbing. No exceptions in Application Insights because the kernel killed the process outright.
Investigation
`kubectl describe pod` confirmed OOMKilled. Container Insights showed working set climbing steadily to the limit. Using `kubectl debug` with the SDK image, `dotnet-counters` showed the GC heap flat at about [150 MB] while working set grew, pointing at native memory. Comparing `/proc/1/smaps_rollup` snapshots showed anonymous memory growth; a code review found [image objects from a native imaging library] created per message but not disposed.
Resolution
Immediate: temporarily raised the limit to [1 Gi] and scaled to [6] replicas to drain the backlog. Real fix: wrapped the native image objects in `using` declarations and capped parallelism with `MaxConcurrentCalls`. Working set then stayed flat at [220 MB], and the limit went back to [512 Mi].
Prevention
Alert on any OOMKilled event and on working set above 80% of the limit. A soak test in CI that processes [10,000] messages and fails if working set grows more than [10%]. The IDisposable analyser rule (CA2000) enabled as a warning. A runbook entry for OOMKilled triage.

How to tell it (STAR)

**S:** Our [document-processing] worker on AKS was being OOMKilled every [40 minutes], and the upload backlog was growing. **T:** I owned finding the root cause rather than just adding memory. **A:** I confirmed OOMKilled with `kubectl describe`, then attached a debug container and used `dotnet-counters`: the managed heap was flat, but working set kept climbing, so it was native memory. I traced it to [native image objects] that weren't disposed, fixed it with `using`, and added a soak test and a CA2000 analyser rule. **R:** Restarts went from [about 36 a day] to zero, memory stayed flat at [220 MB], and we returned to the original limit, saving [the extra node].

↩ Usually asked after

More in Containers

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me