Debugging and Systematic Troubleshooting Questions
Diagnosing defects methodically: reproducing failures, forming and testing hypotheses, reading stack traces and logs, bisecting changes, and reasoning about error handling and edge cases. Covers a disciplined root-cause approach that applies from local bugs to production issues, distinct from embedded hardware-level debugging. A universally probed engineering-craft skill.
Explain how you would reliably reproduce flaky or non-deterministic behavior in model training or inference. Include how you would address randomness such as seeds, environment differences, dataset sampling order, hardware differences, and the logging strategies that help isolate the source of non-determinism.
Sample Answer
Direct answer
Reliably reproducing flaky ML training/inference behavior means pinning down EVERY source of randomness and environment-dependence explicitly, rather than assuming "setting a seed" alone is sufficient, since modern ML stacks have several independent sources of non-determinism that a single seed doesn't cover: the framework's own RNG, the data loader's sampling/shuffling order, and hardware/parallelism-dependent execution order.
Structured elaboration
- Address randomness comprehensively, not just one seed. A genuinely reproducible run needs the seed set for every RNG source involved: the language's own random module, the numeric library (NumPy), and the ML framework's own RNG (which is often SEPARATE from NumPy's and easy to forget), plus, for GPU-based training, the framework's deterministic-algorithm flags, since some GPU kernel implementations (a GPU kernel is the low-level routine that executes one math operation on the GPU, unrelated to the operating-system kernel) are non-deterministic by default even with all RNGs seeded, for performance reasons.
- Address environment differences. Confirm library versions (the ML framework, CUDA/driver versions if GPU-based, any numeric library) are pinned and identical between the flaky run and the reproduction attempt; a version difference in the underlying framework can change numeric behavior even with identical code and identical seeds.
- Address dataset sampling order. If the data loader uses multiple worker processes/threads (common for performance), confirm the worker initialization is ALSO seeded deterministically (a common gap: the main process's seed doesn't automatically propagate to spawned data-loading workers, each of which needs its own seeding via a worker-init function), since inconsistent worker-level randomness can change which examples appear in which order or which augmentation is applied, even with the main seed fixed.
- Address hardware differences. Running the same seeded code on different hardware (different GPU models, different CPU instruction sets) can still produce different results due to non-deterministic reduction order in parallel operations or different low-level kernel implementations being selected; reproducing on the SAME hardware class as the original flaky occurrence removes this variable, or explicitly testing whether the flakiness persists across hardware isolates it as a cause.
- Logging strategies that help isolate non-determinism even before full reproduction is achieved: log the exact seed values used, library/hardware versions, and a checksum or hash of the loaded dataset/batch order for each run, so that when a run DOES fail to reproduce identically, you have a concrete record of exactly which of these factors differed between the two runs, rather than needing to guess.
Worked example
A training run that occasionally produces meaningfully different final metrics despite an apparently-fixed seed: checking reveals the seed was set for Python's random and NumPy, but the ML framework's own separate RNG state (used internally for weight initialization and dropout) was never explicitly seeded, silently defaulting to a fresh, unseeded state each run. Fixing this (seeding all three: language RNG, NumPy, and the framework's own RNG) resolves most of the variance; a small remaining variance is traced to GPU kernel non-determinism in a specific operation, resolved by explicitly enabling the framework's "deterministic algorithms" mode for that operation, accepting a modest performance cost in exchange for full reproducibility during debugging.
Trade-offs and pitfalls
Fully deterministic execution (all seeds pinned, deterministic GPU kernels enabled) often costs meaningful training throughput compared to the default, performance-optimized non-deterministic path, so the practical approach is enabling full determinism specifically WHILE debugging a reproducibility issue, then reverting to the faster default once the bug is understood and fixed, rather than paying the determinism cost in production training runs indefinitely.
After adding a new feature, inference costs for your LLM-based service doubled. Describe an investigation plan: what instrumentation you would add to collect a per-request compute and IO breakdown, how you would reproduce the cost spike in a controlled way, the optimization options you would evaluate such as batching, caching, quantization, or distillation, your rollout strategy, and the KPIs such as cost per inference, latency, and accuracy you would monitor after optimizing.
Sample Answer
Direct answer
Investigating a doubled LLM-serving cost after a new feature means instrumenting to see WHERE the extra compute/IO is going per request (since "cost doubled" is an aggregate that hides which specific path is responsible), reproducing the cost spike in a controlled way to confirm the new feature is genuinely the cause and not a coincidental traffic change, and then choosing an optimization proportional to the actual bottleneck rather than applying every available technique at once.
Structured elaboration
- Instrumentation to collect a per-request compute/IO breakdown. Add timing and token-count instrumentation around each stage of request handling: input tokenization/length, model forward-pass time, output token count/length, and any retrieval or pre/post-processing steps the new feature added. Cost for most LLM-serving setups scales with total tokens processed (input plus output) and/or compute time, so knowing exactly how the NEW feature changed those numbers per request is the direct link between "a feature shipped" and "cost doubled."
- Tests to reproduce the cost spike deliberately, rather than waiting to observe it passively in aggregate billing: replay a fixed, representative sample of requests through both the pre-feature and post-feature code paths (if the old path can still be exercised) and compare token counts and compute time directly, isolating the feature's actual marginal cost from any concurrent, unrelated traffic changes.
- Optimization options to evaluate, matched to what the instrumentation reveals:
- If the feature substantially increased INPUT length (e.g., it added retrieved context or expanded the prompt): consider whether all of that context is actually necessary, and whether a smaller, more targeted retrieval or a summarization step could reduce token count without harming output quality.
- If it increased OUTPUT length or generation calls: consider caching for repeated/similar requests (if the feature's outputs are often identical or near-identical for common inputs), batching concurrent requests to improve hardware utilization even if per-request cost doesn't change, or a smaller/distilled model for the specific sub-task the new feature performs, if it doesn't need the full model's capability.
- If it added extra model calls (e.g., a multi-step chain where the old path was single-step): consider quantization or a smaller model specifically for the new step, or restructuring to avoid a redundant call if one exists.
- Rollout strategy for whichever optimization is chosen: validate the optimization against the SAME representative sample used to measure the original cost increase, confirming both the cost reduction and no meaningful quality regression, before a full rollout; a staged rollout (a small percentage of traffic first) lets you confirm the cost and quality effects hold at real production scale before committing fully.
- KPIs to monitor post-optimization: cost per inference (the direct target metric), latency (since some optimizations, specifically quantization (reducing the numeric precision of the model's weights, e.g. from 32-bit to 8-bit numbers, to shrink compute and memory cost) or distillation (training a smaller, faster model to mimic a larger one's outputs), can trade a small amount of quality or slightly different latency characteristics for cost, and need to be watched to confirm they don't regress user experience), and accuracy/quality (via whatever the feature's existing quality metric is, or a small human-evaluation sample if none exists, specifically to catch a cost optimization that saved money by quietly degrading output quality).
Worked example
Per-request instrumentation shows the new feature roughly TRIPLED average input token count by prepending a large block of retrieved context to every prompt, while output length stayed roughly the same; the input-token increase alone accounts for almost the entire cost increase, since this deployment's cost model is dominated by total tokens processed. Investigating the retrieval step shows it was returning a fixed, generously-sized context window regardless of the actual query's relevance needs. The chosen optimization: a relevance-filtering step that trims retrieved context to only the passages actually likely to matter for the specific query (measured via a cheap similarity score before ever reaching the expensive model call), reducing average input tokens by roughly 60% while a staged rollout confirms output quality (measured against the feature's existing evaluation set) stays within an acceptable margin of the unfiltered baseline.
Trade-offs and pitfalls
Reaching for a broad optimization technique (distillation, quantization) without first confirming via instrumentation WHERE the cost actually went risks investing significant engineering effort in a technique that addresses the wrong bottleneck (e.g., optimizing generation speed when the real cost driver was input token count); the instrumentation step is what makes the chosen optimization's return on effort predictable rather than a guess.
Describe a small but meaningful process or tooling change you introduced that reduced debugging time for your team, for example standardized logs, unit tests for featurization, or pre-commit hooks. Why did you choose that particular change, how did you implement it, and what measurable impact did it have?
Sample Answer
Direct answer
A small, high-leverage change: adding correlation IDs and structured (rather than free-text) logging to a service that previously had neither, so that a failure in one place could actually be traced to its triggering request without manual log archaeology; the choice mattered because it directly attacked the SLOWEST part of the team's existing debugging process, not because it was the most sophisticated tooling available.
Structured elaboration
Why this specific change, not a different one: before proposing anything, the actual bottleneck in the team's debugging process was identified by observation: engineers were regularly spending the first 20-30 minutes of any investigation just correlating free-text log lines across services by eyeballing timestamps, because no shared identifier tied a request's activity together across service boundaries. That specific, repeatedly-observed cost is what made structured logging with a propagated correlation ID the highest-leverage change available, rather than a more sophisticated but less immediately impactful option (like a full distributed-tracing rollout, which would have taken much longer to implement and adopt).
How it was implemented:
- Added a middleware/interceptor at each service's request entry point that either generates a new correlation ID (if the request is the origin) or propagates an incoming one (if it's already present from an upstream caller), attaching it to every log line emitted while handling that request.
- Switched the logging format from free-text to structured (JSON) log lines with consistent field names across services, specifically so the correlation ID (and other common fields) could be queried directly rather than requiring text-pattern matching.
- Rolled it out incrementally, starting with the two or three services most frequently involved in cross-service investigations, rather than attempting a big-bang change across the whole fleet at once, to prove the value and work out format conventions before wider adoption.
Measurable impact: tracked informally at first (asking engineers directly whether recent investigations felt faster) and then more concretely by comparing the TIME-TO-DIAGNOSIS on a sample of incidents before and after rollout for the services that had adopted it; investigations involving those services dropped from a typical 20-30 minutes of manual log correlation to a single structured query pulling the full cross-service trail for a given correlation ID in under a minute, a roughly 20x reduction specifically in the log-correlation phase of debugging (not the whole investigation, which still requires understanding and fixing the actual bug, but the mechanical, previously-wasted part of it).
Trade-offs and pitfalls
The change required upfront work from every team that adopted it (updating their logging calls, agreeing on field-name conventions) and some initial resistance from engineers comfortable with the existing free-text format; the case for adoption was made concrete and low-risk by piloting on a small number of services first and demonstrating the measured time savings, rather than mandating it broadly before it had proven value anywhere.
Describe a systematic, repeatable approach you use to troubleshoot an unfamiliar technical problem end to end. Cover how you observe the symptom, form and prioritize hypotheses, gather and interpret evidence such as logs, metrics, and traces, isolate the root cause, implement and validate a fix, and decide when to escalate, roll back, or write up a postmortem.
Sample Answer
Direct answer
Troubleshooting an unfamiliar problem is a loop, not a single step: observe the symptom precisely, form a small set of testable hypotheses ranked by likelihood and cost to check, gather evidence that discriminates between them, isolate the true cause, implement and validate a fix, and decide whether the incident needs a rollback, an escalation, or a written postmortem. The loop repeats: each piece of evidence should narrow the hypothesis set, not just confirm what you already believed.
Structured elaboration
- Observe the symptom precisely. Write down exactly what is wrong, in falsifiable terms: not "the API is slow" but "p99 latency (the response time slower than 99% of requests, i.e. how bad the worst cases are, not just the average) on
POST /ordersrose from 80ms to 900ms starting at 14:32 UTC, affecting roughly 3% of requests." Vague symptoms produce vague hypotheses. - Form hypotheses before you start digging. List the plausible causes given what changed recently (deploys, config, traffic pattern, dependency versions) and what the symptom rules out. A hypothesis you cannot state is a hypothesis you cannot test.
- Prioritize by expected information gain divided by cost. A five-minute log grep that could confirm or kill three hypotheses at once beats a one-hour deep profiling session that only speaks to one.
- Gather evidence that discriminates. Logs tell you what happened at a point; metrics tell you the shape of the problem over time; traces tell you where time went inside one request. Pick the instrument that actually distinguishes your live hypotheses, not the one you're most comfortable with.
- Isolate the root cause, not just a correlated symptom. A dropped hypothesis should be dropped because evidence contradicts it, not because you got bored of it.
- Implement and validate the fix against the same evidence that revealed the problem. If you diagnosed via a specific metric, watch that metric recover before declaring victory.
- Decide what happens next. If customer impact is ongoing and the fix is unproven, roll back first and diagnose second. If a similar failure could recur, or the incident had real impact, write it up so the org doesn't relearn the same lesson.
Worked example
A "the checkout page is slow" report, applied through the loop: symptom precisely stated as "median load time is normal, but a subset of loads takes 8-12 seconds, starting after this morning's deploy." Hypotheses: (a) the new deploy added a blocking call, (b) a downstream dependency degraded independently, (c) the slow subset shares a common attribute (e.g., a specific region or a large cart). A single log query grouping slow requests by attribute would discriminate between (c) and the other two in minutes, before touching a profiler. Suppose it shows the slow requests all hit a newly added inventory-check call to a dependency with no timeout: that both confirms (a) and rules out (b)/(c) as primary causes. Fix: add a timeout and a fallback; validate by watching the p99 metric drop back to baseline over the next hour, not just the fix compiling.
Trade-offs and pitfalls
The biggest failure mode is skipping hypothesis formation and going straight to your favorite tool (attaching a profiler because you're comfortable with it, even when a five-minute log check would have ruled out two hypotheses first). The second is treating the first correlated signal as the cause without checking whether it's actually causal. Under time pressure it's tempting to fix the first plausible thing you see; that's fine as a mitigation, but the loop isn't complete until you've confirmed the metric recovered and understood why, or you will be back debugging the same symptom next week.
A production model-serving system shows nightly latency spikes while request volume stays constant. Provide a comprehensive debugging strategy considering caching policies, batch windows, background jobs, garbage-collection patterns, multi-tenant interference, and scheduled maintenance. Specify the logs and metrics you would collect and the immediate mitigations you might apply.
Sample Answer
Direct answer
Nightly latency spikes at constant request volume mean the cause is TIME-based, not LOAD-based, which immediately rules out anything that scales with traffic and points toward scheduled work (background jobs, cache expiry/warming cycles, scheduled maintenance) or periodic garbage-collection/compaction cycles that happen to cluster around the same time each night, independent of how many requests are actually arriving.
Structured elaboration
- Confirm the pattern is genuinely time-correlated, not coincidentally volume-correlated. Check request-volume metrics for the exact spike windows across several nights; if volume is truly flat while latency spikes, that rules out ordinary capacity-driven causes and strongly implicates something scheduled or periodic. Alongside the metrics, pull application-level logs for the exact spike windows specifically (not just the surrounding hours), looking for warning-level entries, retry counts, or error codes clustered in that window that a metrics dashboard alone would not surface.
- Check for scheduled background jobs running on the same host/cluster around the spike time: a cache-warming job, a log-rotation or compaction task, a batch analytics job sharing infrastructure, a scheduled backup; cross-reference the exact spike timestamps against the cron/scheduler's OWN execution logs (start time, end time, and any error or retry entries for each scheduled run), not just a summary job-history view, since a summary view can round timestamps in a way that obscures a precise correlation.
- Check caching policies specifically for a periodic expiry pattern. If a cache (in-process or shared) has a TTL (time-to-live: how long a cached entry is kept before it expires) that causes many entries to expire around the same time each night (a fixed-time cache-refresh schedule, or a TTL set relative to a fixed daily reset rather than per-entry insertion time), the resulting simultaneous cache-miss storm can produce exactly this nightly-latency-spike-at-flat-volume signature.
- Check for batch windows in any request-batching logic; if requests are batched with a time-based flush (rather than purely size-based), and something periodic changes the batch-fill rate at that hour (fewer concurrent requests overnight meaning batches take longer to fill and therefore wait longer before flushing, even at flat OVERALL system load), that's a plausible, easy-to-overlook mechanism, especially ironic since it's a case where LOWER traffic at night could paradoxically increase per-request latency via the batching wait.
- Check garbage-collection patterns for a scheduled or load-triggered full GC that happens to land at a consistent time nightly (some GC strategies trigger based on heap-growth patterns that, combined with a consistent daily traffic/memory-allocation shape, can cluster around the same hour even without being explicitly scheduled); the runtime's own GC logs (pause duration and frequency per collection cycle, not just an aggregate GC-time metric) show directly whether pause TIMING specifically clusters at the same nightly window, rather than requiring that to be inferred indirectly from latency alone.
- Check for multi-tenant interference if the infrastructure is shared: another tenant's own scheduled nightly job competing for the same underlying resources (CPU, disk IO, network) can produce a latency spike for YOUR service with zero change to your own traffic or code, visible only by checking host-level (not just your-service-level) resource metrics during the spike window.
- Check for scheduled maintenance: automated OS patching, container/host restarts, or infrastructure-level maintenance windows that a platform team runs on a schedule independent of any application team's knowledge.
Worked example
Cross-referencing spike timestamps against the platform's job scheduler shows a company-wide log-aggregation/rotation job running nightly on shared infrastructure, and host-level (not service-level) CPU and disk-IO metrics show a clear spike during exactly the same window, confirming multi-tenant interference from that job rather than anything in the service's own code or configuration. Immediate mitigation: request the shared job be rescheduled to a lower-traffic window for this service, or move this service to isolated infrastructure if the interference is severe enough to warrant it; a code-level fix wouldn't have helped at all here, since nothing about the service's own logic was the actual cause.
Trade-offs and pitfalls
The temptation to profile the SERVICE's own code first (since that's what's directly controllable) can waste significant time when the actual cause is external, shared-infrastructure interference invisible to service-level metrics alone; checking host-level, not just service-level, resource metrics during the spike window is often the fastest way to distinguish "something in my own code" from "something external happening to my host," and should be checked early given the flat-volume/time-correlated signature already points away from the service's own request-handling logic.
Unlock Full Question Bank
Get access to all 11 Debugging and Systematic Troubleshooting interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.