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:
- Pod Crash Triage on Kubernetes: While on call, you receive an alert for a Kubernetes workload stuck in
CrashLoopBackOffas 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 exactkubectlcommands, pod status fields, exit codes, and cluster events you rely on. - 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. - 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
INSERTstrings per record, and runs a single databasecommitat 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--previouscontainer 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
Understand CrashLoopBackOff and rule out neighbor states
CrashLoopBackOffis 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'srestartPolicyisAlways, I am pausing before restarting it again." Notice that in a KubernetesDeployment, any container exit triggers a restart — even a cleanexit 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 at300 s(5 minutes). Once a container stays up continuously for 10 minutes, the backoff timer resets to zero. Adding the first six backoff waits gives10 + 20 + 40 + 80 + 160 + 300 = 610 s(~10 minutes), so a pod showingRESTARTS: 7andAGE: 13mhas spent almost its entire life waiting in backoff rather than running code.First, verify the
STATUScolumn 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 logsRun 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:- 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 onnode-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. - Inspect
Last Stateand pod events. Runkubectl 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- Read the previous crashed container's logs. Always pass
--previous(-p):kubectl logs api-7d9f-x2k4q -n shop -c api --previousWithout--previous,kubectl logsqueries the current waiting/restarting instance, which often has printed zero lines yet! - Check cluster events, node health, and live resource metrics. Run
kubectl get events -n shop --sort-by=.lastTimestamp,kubectl describe node node-3(checkingMemoryPressure,DiskPressure,PIDPressure), andkubectl top pod -n shop. - Diff against the last healthy release. Run
kubectl rollout history deployment/api -n shopand inspectkubectl get deployment api -n shop -o yamlfor changed image tags,command/args, environment variables, Secret/ConfigMap mounts, resource limits, orsecurityContext. - Inspect an instant-crashing container interactively. You cannot
kubectl execinto 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 -- shInside the shell, inspect mounted files and env vars and invoke the startup command manually to watch it fail live. - Ship the fix, verify stability, and prevent recurrence. Confirm
RESTARTSstops increasing, pods turn1/1 Ready, and user error rates drop; then add CI config validation, canary rollouts, or restart-rate alerts.
- Scope blast radius and mitigate first. Check
Map container exit codes and signals to root causes
In Linux, an exit code above
128means the process was killed by OS signalexit_code - 128. CombiningReason,Exit Code, andEventspinpoints 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 nodeRanked 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)
OOMKilledcontainer limits, (4) misconfigured liveness probes killing slow pods, (5) wrong entrypoint/foreground settings, and (6) filesystem/user permission mismatches (runAsNonRoot,readOnlyRootFilesystem).Understand liveness, readiness, and startup probes
Kubernetes supports four check mechanisms (
httpGetexpecting HTTP200–399,tcpSocket,grpc, andexecexpecting exit0), using defaultsperiodSeconds: 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 succeedsKeep 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 * failureThresholdFour classic probe pitfalls cause self-inflicted outages:
- No startup probe on a slow-booting app (instant restart loop). Suppose a JVM takes
90 sto boot, and someone configures only a liveness probe withinitialDelaySeconds: 30, periodSeconds: 10, failureThreshold: 3. Probes at30 s,40 s, and50 sfail -> kubelet kills the JVM at50 s-> every restart begins the90 sboot from zero, trapping a completely healthy app inCrashLoopBackOffforever! (Increasing livenessinitialDelaySecondsto180is an anti-pattern because real deadlocks later in life would also wait 3+ minutes;startupProbegrants the long budget only once at boot.) - Checking a shared database inside
livenessProbe(cascading restart storm). If Postgres blips for 45 seconds and/livezqueriesSELECT 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: 1under load or GC pauses. When traffic spikes and response times hit1.2 s, tight liveness timeouts kill stressed pods, dumping their traffic onto the remaining pods until the entire deployment collapses. - Pointing
livenessProbeandreadinessProbeat the exact same heavy endpoint. Temporary thread-pool saturation that should merely pause incoming requests (readiness) instead kills in-flight requests (liveness).
- No startup probe on a slow-booting app (instant restart loop). Suppose a JVM takes
Configure probes for the three application archetypes
(a) Quick-booting stateless HTTP service (boots in
~2 s): NostartupProbeis needed. Keep/livezlightweight (verifying the event loop responds in-process) and let/readypull 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 sinitialization due to classpath scanning, Spring wiring, or cache warm-up): GivestartupProbea generous300 sceiling (30 * 10 s) comfortably above worst-case boot under noisy-neighbor CPU throttling, then hand off to fast liveness/readiness probes with a3 stimeout 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.0rather than setting-Xmxequal to the container limit — JVM metaspace, thread stacks, and direct byte buffers live outside heap and otherwise triggerOOMKilledexit137.)(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): Return503until 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 HTTP503responses with a circuit breaker (a guard that fails fast locally while a dependency recovers). Flip readinessfalseonly 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- Liveness (
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:
- Correctness:
- Trailing newline crash: Almost every POSIX text file ends with
\n.content.split("\n")produces""as the final element,"".split(",")is[""], andfields[1]throwsIndexErroron the very last line — rolling back the entire job! - Broken CSV parsing:
line.split(",")corrupts quoted fields containing commas ("St. Louis, MO"), leaves\ron Windows CRLF lines, and blindly inserts the CSV header row as data. - Locale-dependent encoding & float money:
open(path)withoutencoding="utf-8"relies on OS locale defaults (differing between macOS laptops and minimalC-locale containers), and parsing currency withfloatintroduces binary rounding bugs (0.1 + 0.2 == 0.30000000000000004).
- Trailing newline crash: Almost every POSIX text file ends with
- Security:
- SQL injection & syntax breakage: Interpolating strings directly into SQL means an ordinary name like
O'Briencrashes 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.
- SQL injection & syntax breakage: Interpolating strings directly into SQL means an ordinary name like
- 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
withcontext managers leak file descriptors and DB connections on exceptions.
- Not idempotent (unsafe to retry): Without a unique key and conflict policy (
- Performance:
- Unbounded
O(file_size)memory (OOMKilled):open(path).read()loads a2 GBfile into RAM, and.split("\n")allocates a second multi-gigabyte list of millions of Pythonstrobjects (> 4–6 GBpeak RAM). - Per-row network round trips: Against a networked database like PostgreSQL or MySQL,
1,000,000single-rowexecute()calls over a1 mslink spend1,000,000 * 1 ms = 1,000 s(~17 minutes) purely waiting on network latency. Batching1,000rows per write cuts round trips 1,000x to~1 s(usingexecutemany, PostgreSQLpsycopg2.extras.execute_values, orCOPY).
- Unbounded
- 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.
- Correctness:
Refactor into a streaming, batched, idempotent ETL job
The production version below fixes every issue: it streams line-by-line with
csv.readerinO(batch_size)constant memory, parses dollar amounts safely into integer cents viaDecimal, validates rows in a pure unit-testable function, skips harmless blank lines, writes parameterized1,000-row batches idempotently usingON 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,000rows keeps locks brief and makes crash recovery cheap becauseON CONFLICT(order_id) DO NOTHINGskips 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 tosalesin a singleINSERT INTO sales SELECT ... FROM sales_stagingtransaction once validation passes. - Running on Kubernetes: Deploy scheduled ETL scripts as a Kubernetes
JoborCronJob(concurrencyPolicy: Forbid,restartPolicy: OnFailure), never as aDeployment(which restartsexit 0scripts in an infiniteCrashLoopBackOff).
- Per-batch commits vs atomic staging swap: Committing every
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
CrashLoopBackOffis an exponential retry wait, not the root error: The kubelet (the node agent managing containers) backs off10 s, 20 s, 40 s, 80 s, 160 s, 300 swhenever a container repeatedly exits. Always inspectLast State(Reason,Exit Code) inkubectl describe podand read the prior run's output viakubectl logs <pod> -c <container> --previous.- Exit codes translate signals directly:
137(128 + 9,SIGKILL) withReason: OOMKilledmeans the Linux OOMKilled mechanism terminated the container for exceeding its memory limit;137or143(128 + 15,SIGTERM) alongsideUnhealthyevents indicates a failed probe;1is an application error;127/126is a bad command/permission; and0(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 undoimmediately and inspect the broken container afterwards withkubectl 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
Serviceload-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 inBackOffor 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: UnlessLast StatesaysReason: OOMKilled(Exit137), 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
startupProbewith a hugeinitialDelaySecondsonlivenessProbe: SettinginitialDelaySeconds: 240lets 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: BecauseDeploymentenforcesrestartPolicy: Always, finishing cleanly withexit 0triggers an endlessCrashLoopBackOff— batch jobs belong in aJoborCronJob. - Splitting CSVs with
.split(",")and storing money asfloat: Naive string splitting breaks on quoted commas ("Smith, Jr.") and trailing newlines, whilefloatintroduces binary rounding drift thatDecimal+ integer cents completely avoids. - Counting blank trailing CSV lines toward the bad-row failure rate: Failing to ignore empty lines (
[]fromcsv.reader) can push a small 50-row file past a1%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--previouscontainer logs exist. InImagePullBackOff(bad image tag, missingimagePullSecrets, unreachable registry) andCreateContainerConfigError(a referencedConfigMap,Secret, or key does not exist), the container runtime never started the process at all —kubectl logswill fail, andkubectl describe pod'sEventssection 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 (
/livezand/ready), so a bug inside a business endpoint (like/checkoutcrashing 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
JoborCronJobwithconcurrencyPolicy: Forbid(preventing a slow run from overlapping the next scheduled run),restartPolicy: OnFailure,backoffLimit: 3, andactiveDeadlineSecondsso hung network calls cannot stall forever. Because streaming1,000-row batches bounds RAM to a few megabytes regardless of whether the input file is10 MBor10 GB, you can set predictable container memory requests/limits and inject database credentials from a KubernetesSecret.
Follow-up questions
- How does troubleshooting CrashLoopBackOff differ from diagnosing ImagePullBackOff or CreateContainerConfigError?
- Why might customers still hit HTTP 500 errors when every pod passes both liveness and readiness probes, and how would you detect it?
- How should you package and schedule the refactored Python ingestion job on Kubernetes?
Similar questions
- Node Value Spanning the Most Tree Depths
- Hardening Stateful Grid Logic Against Malformed Inputs
- Dynamic Integer Stream Median
- Minimum Slots for Cooldown Task Scheduling
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target