Kubernetes Crash Triage, Health Probes, and Python ETL Review

Easy · Software Engineering Fundamentals · Software Engineer · Technical Screen

Prompt

This operational engineering prompt has three connected parts covering container orchestration reliability and batch data processing:

  1. Pod Crash Triage on Kubernetes: While on call, you receive an alert for a Kubernetes workload stuck in CrashLoopBackOff as its container exits repeatedly. Outline a disciplined triage sequence from initial mitigation to root-cause confirmation, highlight the top failure causes you check first, and name the exact kubectl commands, pod status fields, exit codes, and cluster events you rely on.
  2. Health Probe Design (livenessProbe, readinessProbe, startupProbe): Contrast what each Kubernetes probe checks and how the control plane reacts when each one fails. Point out misconfigurations that trigger self-inflicted outages or restart storms, then sketch appropriate probe settings for three workloads: (a) a fast-booting stateless HTTP API, (b) a JVM service with a multi-minute cold start, and (c) an API backed by a relational database.
  3. Production Code Review of a Python File Loader: Critique a naive Python ingestion script that reads an entire flat file into memory at once, splits lines manually to transform columns, builds raw SQL INSERT strings per record, and runs a single database commit at the end. Identify concrete flaws across correctness, security, fault tolerance, memory/network efficiency, and observability, then show how you would restructure the job for production.

Scope & Expectations

  • Incident workflow and signal mapping: Separate neighbor failure states from CrashLoopBackOff, prioritize blast-radius containment, and connect termination reasons, Linux exit codes, and --previous container logs to concrete root causes.
  • Probe semantics and failure modes: Clearly distinguish pod termination from endpoint removal, compute boot and hang-detection time budgets, and explain why downstream dependencies do not belong inside liveness checks.
  • Production-ready Python ETL patterns: Address parser edge cases, SQL injection, retry idempotency, streaming O(1) memory bounds, batched database writes, and structured operational telemetry.

Step-by-step walkthrough

  1. Understand CrashLoopBackOff and rule out neighbor states

    CrashLoopBackOff is not the root error itself — it is a waiting state reported by the kubelet (the Kubernetes agent running on each node). It means: "This container started, exited or was killed, and because the Pod's restartPolicy is Always, I am pausing before restarting it again." Notice that in a Kubernetes Deployment, any container exit triggers a restart — even a clean exit 0.

    After an immediate first retry, the kubelet doubles the wait time between restarts: 10 s, 20 s, 40 s, 80 s, 160 s, capped at 300 s (5 minutes). Once a container stays up continuously for 10 minutes, the backoff timer resets to zero. Adding the first six backoff waits gives 10 + 20 + 40 + 80 + 160 + 300 = 610 s (~10 minutes), so a pod showing RESTARTS: 7 and AGE: 13m has spent almost its entire life waiting in backoff rather than running code.

    First, verify the STATUS column carefully, because similar-looking statuses fail before the main container ever runs:

    Pod STATUS                     | Did main container start? | First place to look
    -------------------------------+---------------------------+------------------------------------------------------
    Pending                        | Never scheduled to a node | Insufficient CPU/RAM, nodeSelector, taints, unbound PVC
    ImagePullBackOff / ErrImagePull| Never started             | Wrong image tag, private registry secret, network/DNS
    CreateContainerConfigError     | Never started             | Missing ConfigMap, missing Secret, or missing key name
    Init:CrashLoopBackOff          | Init container crashed    | Logs of the init container: kubectl logs <pod> -c <init>
    CrashLoopBackOff               | Started, then died/killed | Previous container's exit code, events, and --previous logs
    
  2. Run a systematic seven-step Kubernetes debugging loop

    When paged for CrashLoopBackOff, work from blast radius inward so you restore user traffic first and never lose evidence:

    1. Scope blast radius and mitigate first. Check kubectl get pods -n <ns> -l app=<svc> -o wide. Are all pods crashing across all nodes (likely a bad code push, bad ConfigMap/Secret, or shared dependency) or just pods on node-3 (likely a bad node)? If customers are impacted right after a deploy, roll back immediately (kubectl rollout undo deployment/<svc> -n <ns>) and debug the broken revision calmly afterward.
    2. Inspect Last State and pod events. Run kubectl describe pod <pod> -n <ns> to see how the previous container run died:
    $ kubectl get pods -n shop -l app=api -o wide
    NAME            READY   STATUS             RESTARTS      AGE   NODE
    api-7d9f-x2k4q  0/1     CrashLoopBackOff   6 (90s ago)   12m   node-3
    
    $ kubectl describe pod api-7d9f-x2k4q -n shop
    Containers:
      api:
        State:          Waiting
          Reason:       CrashLoopBackOff
        Last State:     Terminated
          Reason:       Error                  # <-- or OOMKilled, Completed
          Exit Code:    1                      # <-- or 137, 143, 127, 126, 0
        Restart Count:  6
    Events:
      Warning  Unhealthy  Liveness probe failed: HTTP probe failed with statuscode: 500
      Normal   Killing    Container api failed liveness probe, will be restarted
      Warning  BackOff    Back-off restarting failed container api in pod api-7d9f-x2k4q
    
    1. Read the previous crashed container's logs. Always pass --previous (-p): kubectl logs api-7d9f-x2k4q -n shop -c api --previous Without --previous, kubectl logs queries the current waiting/restarting instance, which often has printed zero lines yet!
    2. Check cluster events, node health, and live resource metrics. Run kubectl get events -n shop --sort-by=.lastTimestamp, kubectl describe node node-3 (checking MemoryPressure, DiskPressure, PIDPressure), and kubectl top pod -n shop.
    3. Diff against the last healthy release. Run kubectl rollout history deployment/api -n shop and inspect kubectl get deployment api -n shop -o yaml for changed image tags, command/args, environment variables, Secret/ConfigMap mounts, resource limits, or securityContext.
    4. Inspect an instant-crashing container interactively. You cannot kubectl exec into a container that dies in 50 ms. Clone the pod with its entrypoint overridden to a shell: kubectl debug api-7d9f-x2k4q -n shop -it --copy-to=api-debug --container=api -- sh Inside the shell, inspect mounted files and env vars and invoke the startup command manually to watch it fail live.
    5. Ship the fix, verify stability, and prevent recurrence. Confirm RESTARTS stops increasing, pods turn 1/1 Ready, and user error rates drop; then add CI config validation, canary rollouts, or restart-rate alerts.
  3. Map container exit codes and signals to root causes

    In Linux, an exit code above 128 means the process was killed by OS signal exit_code - 128. Combining Reason, Exit Code, and Events pinpoints the top root causes immediately:

    Termination signal / state     | What happened                                  | Root causes to check first
    -------------------------------+------------------------------------------------+------------------------------------------------
    Reason: OOMKilled, Exit: 137   | Killed by Linux kernel OOM killer (SIGKILL=9)  | Memory limit too low, memory leak, un-tuned JVM heap
    Exit: 137 (no OOMKilled)       | External SIGKILL (9) after grace period        | Failed liveness/startup probe + ignored SIGTERM
    Exit: 143                      | Terminated cleanly on SIGTERM (15)             | Failed liveness/startup probe, node drain, preemption
    Exit: 1 (or 2..125)            | Unhandled app exception or explicit sys.exit   | Missing env/Secret, bad config, failed DB boot check
    Exit: 127 / 126                | Command not found / binary not executable      | Typo in command/args, wrong PATH, missing +x bit
    Reason: Completed, Exit: 0     | Main PID 1 exited normally                     | Daemonized background server, or Job deployed as Deployment
    Exit: 139 / "exec format error"| SIGSEGV (11) / wrong CPU instruction set       | Native C library crash, or arm64 image on amd64 node
    

    Ranked by how often they cause production incidents, check first: (1) a recent deploy or Secret/ConfigMap edit, (2) unhandled startup exceptions (missing env var or exiting on transient DB errors), (3) OOMKilled container limits, (4) misconfigured liveness probes killing slow pods, (5) wrong entrypoint/foreground settings, and (6) filesystem/user permission mismatches (runAsNonRoot, readOnlyRootFilesystem).

  4. Understand liveness, readiness, and startup probes

    Kubernetes supports four check mechanisms (httpGet expecting HTTP 200–399, tcpSocket, grpc, and exec expecting exit 0), using defaults periodSeconds: 10, timeoutSeconds: 1, failureThreshold: 3, successThreshold: 1. All three probe types run checks the same way — they differ in what question they ask and what action Kubernetes takes on failure:

    Probe type | Question it answers                        | Action on failure                         | Lifecycle
    -----------+--------------------------------------------+-------------------------------------------+----------------------------
    Startup    | Has the app finished booting up?           | Kill & restart container once budget ends | Runs ONLY until 1st success
    Liveness   | Is the process deadlocked beyond self-heal?| Kill & restart container                  | Runs after startup succeeds
    Readiness  | Should this pod receive new traffic now?   | Remove pod IP from Service endpoints ONLY | Runs after startup succeeds
    

    Keep two quick timing formulas in your head during interviews and on-call shifts:

    Startup time budget        = initialDelaySeconds + (periodSeconds * failureThreshold)
    Time to detect & kill hang = periodSeconds * failureThreshold
    

    Four classic probe pitfalls cause self-inflicted outages:

    • No startup probe on a slow-booting app (instant restart loop). Suppose a JVM takes 90 s to boot, and someone configures only a liveness probe with initialDelaySeconds: 30, periodSeconds: 10, failureThreshold: 3. Probes at 30 s, 40 s, and 50 s fail -> kubelet kills the JVM at 50 s -> every restart begins the 90 s boot from zero, trapping a completely healthy app in CrashLoopBackOff forever! (Increasing liveness initialDelaySeconds to 180 is an anti-pattern because real deadlocks later in life would also wait 3+ minutes; startupProbe grants the long budget only once at boot.)
    • Checking a shared database inside livenessProbe (cascading restart storm). If Postgres blips for 45 seconds and /livez queries SELECT 1, Kubernetes kills and restarts every single API pod simultaneously. Restarting API pods cannot heal Postgres, and the thundering herd of cold pods reconnecting and rebuilding caches can knock Postgres right back down.
    • Tight timeoutSeconds: 1 under load or GC pauses. When traffic spikes and response times hit 1.2 s, tight liveness timeouts kill stressed pods, dumping their traffic onto the remaining pods until the entire deployment collapses.
    • Pointing livenessProbe and readinessProbe at the exact same heavy endpoint. Temporary thread-pool saturation that should merely pause incoming requests (readiness) instead kills in-flight requests (liveness).
  5. Configure probes for the three application archetypes

    (a) Quick-booting stateless HTTP service (boots in ~2 s): No startupProbe is needed. Keep /livez lightweight (verifying the event loop responds in-process) and let /ready pull overloaded pods out of load-balancer rotation quickly:

    readinessProbe:
      httpGet: { path: /ready, port: 8080 }
      periodSeconds: 5
      timeoutSeconds: 2
      failureThreshold: 2          # Removed from Service endpoints after ~10 s of failures
    livenessProbe:
      httpGet: { path: /livez, port: 8080 }
      periodSeconds: 10
      timeoutSeconds: 2
      failureThreshold: 3          # Restarted only after ~30 s completely unresponsive
    

    (b) JVM service with a multi-minute cold start (60–180 s initialization due to classpath scanning, Spring wiring, or cache warm-up): Give startupProbe a generous 300 s ceiling (30 * 10 s) comfortably above worst-case boot under noisy-neighbor CPU throttling, then hand off to fast liveness/readiness probes with a 3 s timeout to tolerate normal GC pauses:

    startupProbe:
      httpGet: { path: /livez, port: 8080 }
      periodSeconds: 10
      timeoutSeconds: 3
      failureThreshold: 30         # Up to 300 s one-time boot budget; stops once first 200 OK returns
    livenessProbe:
      httpGet: { path: /livez, port: 8080 }
      periodSeconds: 10
      timeoutSeconds: 3
      failureThreshold: 3          # Fast ~30 s deadlock recovery once booted
    readinessProbe:
      httpGet: { path: /ready, port: 8080 }
      periodSeconds: 5
      timeoutSeconds: 3
      failureThreshold: 3          # Turns true only after local caches/pools finish warming
    

    (JVM bonus check: size memory with -XX:MaxRAMPercentage=75.0 rather than setting -Xmx equal to the container limit — JVM metaspace, thread stacks, and direct byte buffers live outside heap and otherwise trigger OOMKilled exit 137.)

    (c) API backed by a relational database:

    • Liveness (/livez): Check only the local web server loop — never query the database.
    • Startup: Do not block startup on the database either; let the process boot and initialize its connection pool asynchronously with exponential backoff so a DB outage during deploy doesn't cause CrashLoopBackOff.
    • Readiness (/ready): Return 503 until the connection pool has connected at least once (preventing cold pods during a rolling deploy from taking traffic before initializing). Once initialized, avoid flipping all pods unready on transient DB errors — if every pod drops out of the Service endpoints list simultaneously, callers get opaque TCP connection errors instead of fast, structured HTTP 503 responses with a circuit breaker (a guard that fails fast locally while a dependency recovers). Flip readiness false only when this specific pod's local pool is wedged while peers remain healthy:
    livenessProbe:
      httpGet: { path: /livez, port: 8080 }   # Strictly in-process health; never touches DB
      periodSeconds: 10
      timeoutSeconds: 2
      failureThreshold: 3
    readinessProbe:
      httpGet: { path: /ready, port: 8080 }   # True once local pool initialized and pod is not overloaded
      periodSeconds: 5
      timeoutSeconds: 2
      failureThreshold: 3
    
  6. Audit the naive Python ingestion script across five dimensions

    Here is a concrete representation of the script under review:

    import sqlite3
    
    
    def load_naive(path, db_path):
        conn = sqlite3.connect(db_path)
        content = open(path).read()
        for line in content.split("\n"):
            fields = line.split(",")
            order_id, city, amount = fields[0], fields[1], fields[2]
            sql = f"INSERT INTO sales VALUES ('{order_id}', '{city}', {amount})"
            conn.execute(sql)
        conn.commit()
    

    Walking through a structured code review across all five production dimensions:

    1. Correctness:
      • Trailing newline crash: Almost every POSIX text file ends with \n. content.split("\n") produces "" as the final element, "".split(",") is [""], and fields[1] throws IndexError on the very last line — rolling back the entire job!
      • Broken CSV parsing: line.split(",") corrupts quoted fields containing commas ("St. Louis, MO"), leaves \r on Windows CRLF lines, and blindly inserts the CSV header row as data.
      • Locale-dependent encoding & float money: open(path) without encoding="utf-8" relies on OS locale defaults (differing between macOS laptops and minimal C-locale containers), and parsing currency with float introduces binary rounding bugs (0.1 + 0.2 == 0.30000000000000004).
    2. Security:
      • SQL injection & syntax breakage: Interpolating strings directly into SQL means an ordinary name like O'Brien crashes with a syntax error, and malicious input like '); DROP TABLE sales; -- executes arbitrary SQL. Always pass parameters separately via driver placeholders (? or %s), and load DB credentials from environment variables or mounted Secrets rather than source code.
    3. Reliability:
      • Not idempotent (unsafe to retry): Without a unique key and conflict policy (ON CONFLICT DO NOTHING / DO UPDATE), re-running after a scheduler timeout duplicates every row.
      • All-or-nothing giant transaction & leaked handles: Holding one transaction open across millions of rows bloats DB rollback/WAL logs, and crashing at row 999,999 loses everything. Missing with context managers leak file descriptors and DB connections on exceptions.
    4. Performance:
      • Unbounded O(file_size) memory (OOMKilled): open(path).read() loads a 2 GB file into RAM, and .split("\n") allocates a second multi-gigabyte list of millions of Python str objects (> 4–6 GB peak RAM).
      • Per-row network round trips: Against a networked database like PostgreSQL or MySQL, 1,000,000 single-row execute() calls over a 1 ms link spend 1,000,000 * 1 ms = 1,000 s (~17 minutes) purely waiting on network latency. Batching 1,000 rows per write cuts round trips 1,000x to ~1 s (using executemany, PostgreSQL psycopg2.extras.execute_values, or COPY).
    5. Operations:
      • Zero observability: No structured counts of rows read, inserted, or rejected; no line numbers on parse errors; hardcoded behavior; and tightly coupled parsing + DB I/O that is hard to unit-test.
  7. Refactor into a streaming, batched, idempotent ETL job

    The production version below fixes every issue: it streams line-by-line with csv.reader in O(batch_size) constant memory, parses dollar amounts safely into integer cents via Decimal, validates rows in a pure unit-testable function, skips harmless blank lines, writes parameterized 1,000-row batches idempotently using ON CONFLICT(order_id) DO NOTHING, logs structured progress, and enforces a maximum bad-row threshold with clear exit codes:

    import csv
    from decimal import Decimal, InvalidOperation
    import logging
    import sqlite3
    import sys
    
    log = logging.getLogger("ingest")
    
    BATCH_SIZE = 1000
    MAX_BAD_FRACTION = 0.01
    EXPECTED_HEADER = ["order_id", "city", "amount_usd"]
    
    # Requires CREATE UNIQUE INDEX idx_sales_order_id ON sales(order_id);
    INSERT_SQL = (
        "INSERT INTO sales (order_id, city, amount_cents) "
        "VALUES (?, ?, ?) "
        "ON CONFLICT(order_id) DO NOTHING"
    )
    
    
    def parse_row(fields):
        """Validate one CSV row and return (order_id, city, amount_cents) or raise ValueError."""
        if len(fields) != 3:
            raise ValueError(f"expected 3 columns, got {len(fields)}")
    
        order_id = fields[0].strip()
        city = fields[1].strip()
        raw_amount = fields[2].strip()
    
        if not order_id:
            raise ValueError("empty order_id")
    
        try:
            # Decimal avoids binary floating-point rounding; store exact integer cents
            dollars = Decimal(raw_amount)
        except InvalidOperation as exc:
            raise ValueError(f"invalid decimal amount {raw_amount!r}") from exc
    
        cents_decimal = dollars * 100
        if cents_decimal < 0 or cents_decimal != cents_decimal.to_integral_value():
            raise ValueError(f"amount must be non-negative whole cents, got {raw_amount!r}")
    
        return order_id, city, int(cents_decimal)
    
    
    def write_batch(conn, batch):
        """Commit one batch atomically; rolls back automatically if execute fails."""
        with conn:
            conn.executemany(INSERT_SQL, batch)
    
    
    def ingest_file(csv_path, conn):
        """Stream csv_path into sales in fixed-size batches; return (rows_read, rows_rejected)."""
        rows_read = 0
        rows_rejected = 0
        batch = []
    
        with open(csv_path, mode="r", newline="", encoding="utf-8") as handle:
            reader = csv.reader(handle)
            header = next(reader, None)
            if header != EXPECTED_HEADER:
                raise ValueError(f"unexpected CSV header: {header!r}")
    
            for fields in reader:
                # Skip completely blank lines (such as extra trailing newlines) cleanly
                if not any(cell.strip() for cell in fields):
                    continue
    
                rows_read += 1
                try:
                    batch.append(parse_row(fields))
                except ValueError as err:
                    rows_rejected += 1
                    log.warning("line %d rejected: %s", reader.line_num, err)
                    continue
    
                if len(batch) >= BATCH_SIZE:
                    write_batch(conn, batch)
                    batch.clear()
    
        if batch:
            write_batch(conn, batch)
    
        log.info(
            "ingest finished: read=%d valid=%d rejected=%d",
            rows_read,
            rows_read - rows_rejected,
            rows_rejected,
        )
        if rows_read > 0 and (rows_rejected / rows_read) > MAX_BAD_FRACTION:
            raise RuntimeError(f"rejected row rate too high: {rows_rejected}/{rows_read}")
    
        return rows_read, rows_rejected
    
    
    def main(argv):
        logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
        if len(argv) != 3:
            log.error("usage: %s <csv_path> <sqlite_db_path>", argv[0])
            return 2
    
        conn = sqlite3.connect(argv[2])
        try:
            ingest_file(argv[1], conn)
        finally:
            conn.close()
        return 0
    
    
    if __name__ == "__main__":
        sys.exit(main(sys.argv))
    

    Two architectural points round out the production design:

    • Per-batch commits vs atomic staging swap: Committing every 1,000 rows keeps locks brief and makes crash recovery cheap because ON CONFLICT(order_id) DO NOTHING skips already-committed batches on retry. If downstream readers must never observe a partially loaded file, stream batches into a temporary staging table first and publish to sales in a single INSERT INTO sales SELECT ... FROM sales_staging transaction once validation passes.
    • Running on Kubernetes: Deploy scheduled ETL scripts as a Kubernetes Job or CronJob (concurrencyPolicy: Forbid, restartPolicy: OnFailure), never as a Deployment (which restarts exit 0 scripts in an infinite CrashLoopBackOff).

Intuition & how it works

Running reliable backend systems comes down to separating three distinct operational reflexes: "restart a wedged worker," "temporarily stop sending customers to a busy worker," and "process data in safe, repeatable bite-sized chunks." Imagine managing a busy restaurant kitchen. If the brick oven takes 90 seconds to preheat and you fire the chef every 50 seconds for not serving pizza yet, breakfast will never be cooked (missing startup probe). If the city water main shuts off for one minute, firing every chef in the kitchen won't fix the street pipe — it only creates chaos when the water comes back on (putting a database check inside a liveness probe). And when a delivery truck arrives with 50,000 ingredients, trying to carry the entire truckload through the door in one trip breaks your back, whereas carrying 100 labeled crates one cart at a time works effortlessly (streaming batched ETL vs loading whole files into memory).

The naive instincts in both Kubernetes and Python fail for the exact same reason: they ignore transient states and resource bounds. Running kubectl logs without --previous shows an empty screen from a freshly restarted container instead of the crash stack trace; pointing every health probe at one /health endpoint turns temporary slowdowns into cluster-wide restart loops; and slurping a whole CSV with .read().split("\n") while pasting strings into INSERT statements causes OOMKilled crashes, trailing-newline IndexError bugs, SQL injection vulnerabilities, and duplicate rows on retry.

Walk through a tiny concrete trace across all three parts of the question:

1. Kubernetes CrashLoop & Probe Math (JVM needing 90 s to boot):
   - Bad config:  livenessProbe only (initialDelaySeconds=30, periodSeconds=10, failureThreshold=3)
                  Checks fail at 30s, 40s, 50s -> SIGTERM (Exit 143) at 50s -> CrashLoopBackOff forever!
   - Good config: startupProbe (periodSeconds=10, failureThreshold=30 -> 300s one-time boot budget)
                  App boots at 90s -> startupProbe succeeds -> livenessProbe takes over with fast 30s hang check.

2. Python CSV Ingestion on a 2-row file "order_id,city,amount_usd\n101,Austin,12.50\n102,St. Louis, MO,8.00\n":
   - Naive script: inserts header as row 1, splits "St. Louis, MO" into wrong columns, and crashes with
                   IndexError on the trailing "" after the final "\n" — committing 0 rows!
   - Fixed script: csv.reader streams 1 row at a time in UTF-8, validates header, converts Decimal("12.50") -> 1250
                   cents, skips trailing blank lines, and batches parameterized INSERT ... ON CONFLICT DO NOTHING.

Key points

  • CrashLoopBackOff is an exponential retry wait, not the root error: The kubelet (the node agent managing containers) backs off 10 s, 20 s, 40 s, 80 s, 160 s, 300 s whenever a container repeatedly exits. Always inspect Last State (Reason, Exit Code) in kubectl describe pod and read the prior run's output via kubectl logs <pod> -c <container> --previous.
  • Exit codes translate signals directly: 137 (128 + 9, SIGKILL) with Reason: OOMKilled means the Linux OOMKilled mechanism terminated the container for exceeding its memory limit; 137 or 143 (128 + 15, SIGTERM) alongside Unhealthy events indicates a failed probe; 1 is an application error; 127/126 is a bad command/permission; and 0 (Completed) means the main foreground process exited.
  • Triage user impact before deep-diving: Scope whether one pod, one node, or an entire release is failing; if a fresh rollout broke production, run kubectl rollout undo immediately and inspect the broken container afterwards with kubectl debug --copy-to.
  • Three probes, three distinct actions: A startup probe gates initial boot so slow apps aren't killed mid-start; a liveness probe restarts a deadlocked process; and a readiness probe removes a pod IP from Service load-balancing endpoints without restarting it. Never query shared downstream databases inside a liveness probe.
  • Five pillars of ETL code review: Stream files line-by-line with csv.reader(..., encoding="utf-8") instead of .read().split("\n"), use parameterized queries (driver placeholders like ? that separate SQL structure from user data to prevent SQL injection), batch writes (executemany / COPY) to eliminate per-row network latency, enforce idempotency (a property where re-running the job produces the exact same database state, via unique keys + ON CONFLICT DO NOTHING), and log structured row counts with a bad-row threshold.

Common mistakes

  • Running kubectl logs <pod> without --previous: When a container is sitting in BackOff or just restarted, current logs are empty, tricking engineers into thinking the app died silently without printing a stack trace.
  • Blindly bumping memory limits for every CrashLoopBackOff: Unless Last State says Reason: OOMKilled (Exit 137), adding RAM wastes cluster capacity without fixing bad secrets, broken commands, or probe timeouts.
  • Putting database or downstream API pings in livenessProbe: A 30-second downstream hiccup causes Kubernetes to kill and cold-start every replica simultaneously, amplifying a minor blip into a full outage.
  • Replacing startupProbe with a huge initialDelaySeconds on livenessProbe: Setting initialDelaySeconds: 240 lets a slow JVM boot, but also forces production to wait 4+ minutes before restarting a pod that deadlocks hours later.
  • Deploying a one-shot Python ETL script as a Kubernetes Deployment: Because Deployment enforces restartPolicy: Always, finishing cleanly with exit 0 triggers an endless CrashLoopBackOff — batch jobs belong in a Job or CronJob.
  • Splitting CSVs with .split(",") and storing money as float: Naive string splitting breaks on quoted commas ("Smith, Jr.") and trailing newlines, while float introduces binary rounding drift that Decimal + integer cents completely avoids.
  • Counting blank trailing CSV lines toward the bad-row failure rate: Failing to ignore empty lines ([] from csv.reader) can push a small 50-row file past a 1% rejection threshold and abort a healthy run.

Follow-up questions

  • How does troubleshooting CrashLoopBackOff differ from diagnosing ImagePullBackOff or CreateContainerConfigError? In CrashLoopBackOff, the container image was pulled, configured, and started executing, so exit codes and --previous container logs exist. In ImagePullBackOff (bad image tag, missing imagePullSecrets, unreachable registry) and CreateContainerConfigError (a referenced ConfigMap, Secret, or key does not exist), the container runtime never started the process at all — kubectl logs will fail, and kubectl describe pod's Events section immediately names the missing image or key.
  • Why might customers still hit HTTP 500 errors when every pod passes both liveness and readiness probes, and how would you detect it? Health probes intentionally test synthetic, lightweight paths (/livez and /ready), so a bug inside a business endpoint (like /checkout crashing on a bad feature flag or schema mismatch) leaves probes green while real user requests fail. Catch user-visible regressions with golden-signal Prometheus metrics (per-route 5xx error rate and p99 latency SLO alerts), structured error logs, and synthetic canary transactions.
  • How should you package and schedule the refactored Python ingestion job on Kubernetes? Package it as a Job or CronJob with concurrencyPolicy: Forbid (preventing a slow run from overlapping the next scheduled run), restartPolicy: OnFailure, backoffLimit: 3, and activeDeadlineSeconds so hung network calls cannot stall forever. Because streaming 1,000-row batches bounds RAM to a few megabytes regardless of whether the input file is 10 MB or 10 GB, you can set predictable container memory requests/limits and inject database credentials from a Kubernetes Secret.

Follow-up questions

Similar questions

More IXL Learning interview questions

All 5 IXL Learning questions →