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.
Your CI build fails only on the pipeline and never locally. Outline a methodical plan to find the difference: comparing environment variables, container images, OS versions, dependency versions, and filesystem semantics, and describe how you would produce a minimal reproducible example inside CI itself.
Sample Answer
Direct answer
When a CI build fails only in the pipeline, the fastest path is to systematically diff the CI environment against your local one along every axis that could plausibly differ, rather than guessing: environment variables, container/base image, OS and library versions, filesystem case-sensitivity and permissions, and the exact command CI runs versus the one you run locally. The end goal is a minimal reproduction that runs inside CI itself, because "works when I add print statements" isn't a fix, it's a workaround.
Structured elaboration
- Compare environment variables. Dump the full environment CI uses (most CI systems let you print it, or add a debug step that runs
env) and diff it against your local shell. Missing or unexpectedly-set variables (aNODE_ENV, a locale, a timezone, a feature flag) are a common silent cause. - Compare the base image or container. If CI runs in a container and you develop on bare metal (or a different container), pin down exact OS version, installed system libraries, and default locale/timezone, since these can silently change behavior (date parsing, sort order, floating-point rounding modes).
- Compare dependency versions exactly, not just "the same major version." A CI pipeline that does a clean install from a lockfile can resolve a transitive dependency (a dependency of one of your dependencies: something your package manager pulled in automatically, not something you installed directly) differently than a long-lived local
node_modulesorvenvthat never got a clean reinstall. - Compare filesystem semantics. CI runners are frequently Linux (case-sensitive filesystem) while local development happens on macOS (case-insensitive by default); an import or file reference with inconsistent casing works locally and fails only in CI.
- Reproduce inside CI, not around it. Add a debug step to the CI job itself, before the failing step, that dumps the environment, tool versions, and installed package list, so you're comparing CI's actual state rather than guessing from documentation. If possible, get an interactive shell into the exact CI container (many CI providers support this) and run the failing command by hand.
- Build a minimal reproducible example inside CI: strip the pipeline down to the smallest set of steps that still reproduces the failure, in a scratch branch if needed, so you have a fast iteration loop instead of waiting on the full pipeline each time.
Worked example
A test suite that passes locally on macOS but fails in CI (Linux) with a file-not-found error: dumping the CI environment shows the import path from Utils import helper, while the actual file on disk is utils.py. macOS's case-insensitive filesystem silently accepted the mismatch locally; Linux's case-sensitive filesystem in CI did not. The minimal repro: a two-line script with that exact import, run in a Linux container locally, reproduces it in seconds without needing the full CI pipeline.
Trade-offs and pitfalls
The trap is iterating by pushing small changes and waiting for the full CI pipeline to re-run, which can cost many minutes per guess. Getting a fast, local reproduction of the CI environment (even a bare Docker container matching CI's base image) pays for itself after two or three iterations. A second common trap: fixing the symptom by disabling the failing step (skip, retry, quarantine) without ever finding the actual environment difference, which resurfaces the same class of bug on the next similarly-shaped test.
You find a function that behaves incorrectly only for a specific input. Outline how you would build a minimal, reproducible test case that isolates the bug, including how you would reduce external dependencies so the case can run reliably in CI.
Sample Answer
Direct answer
Building a minimal, reproducible test case means repeatedly cutting away anything that isn't necessary to trigger the bug, while checking after every cut that the bug still happens, until what's left is the smallest input and the smallest code path that still fails. The goal is a case small enough that the cause becomes visible by inspection, and portable enough to run without the original production dependencies.
Structured elaboration
- Capture a known-failing instance first. Before minimizing anything, get one concrete input that reliably triggers the incorrect behavior, and record the exact observed output versus the expected output.
- Remove external dependencies one at a time. Replace a live database call with a small in-memory fixture containing only the rows the failing case touches; replace a network call with a stub returning the exact response you captured; replace "today's date" or randomness with a fixed value if the bug is date- or randomness-sensitive. Each substitution must preserve the failure; if it stops failing, that dependency was load-bearing and you put it back.
- Shrink the input itself. If the failing input is a 500-row CSV, try trimming to the smallest prefix, or the smallest subset of rows, that still fails; a systematic way to do this on large inputs is a manual or scripted bisection (delete half, check if it still fails; keep the half that still fails; repeat), the same "isolate by halving" idea that git-bisect applies to commit history.
- Shrink the code path. If the bug lives inside a large function, comment out or short-circuit branches that don't affect the failing case, or extract the smallest sub-function that reproduces it in isolation, so you're not staring at a hundred lines that are irrelevant to the actual defect.
- Verify the minimized case is still faithful. Run it once more end to end and confirm the output matches the original failure exactly, not just "something goes wrong."
Worked example
Given a report that "generating a monthly report crashes for some customers," start from one customer ID that reliably crashes. Replace the database call with a fixture containing just that customer's rows (still crashes: good, the DB wasn't the cause). Shrink from 40 line items to 2 by deleting half and re-checking each time; discover it still crashes with exactly one line item that has a null discount field. That's the minimized case: one hand-built object, no database, no network, five lines of setup, and it reliably reproduces "unhandled null in discount calculation." That five-line reproduction is now something you can paste directly into a bug report or a unit test.
Trade-offs and pitfalls
Minimizing too aggressively without re-verifying after each cut is the main trap: you can accidentally remove the actual trigger and end up "reproducing" a different, easier bug, or no bug at all, while believing you've simplified the real one. Always re-check after each individual cut, not after a batch of cuts, so that if the failure disappears you know exactly which change caused it.
Explain the practical differences between debugging at the application level versus the infrastructure level (network, storage, compute). Give two examples of failures that look similar at first glance but have different root causes at each level, and describe how you would distinguish between them.
Sample Answer
Direct answer
Application-level debugging asks "why did this code produce the wrong result," and its evidence lives inside your process: variables, call stacks, exceptions, business logic. Infrastructure-level debugging asks "why couldn't the correct code even run correctly," and its evidence lives outside your process: network reachability, disk and memory pressure, DNS, container scheduling, resource limits. The two failure modes can look identical from the outside (a request fails, a page times out) while requiring completely different evidence to distinguish.
Structured elaboration
The practical test: if you could run the exact same code on a machine with unlimited, perfectly-behaving resources and a clean network, would the bug still happen? If yes, it's application-level (a logic error, a bad state transition, an unhandled edge case). If no, it's infrastructure-level (the code was never wrong, but its environment failed to give it what it needed).
Two concrete examples that look alike but diverge in root cause:
- "Requests are timing out." Application-level cause: a newly introduced N+1 query pattern (fetching a list, then running one extra database query per item in that list instead of one combined query, so 100 items means 101 round trips instead of 1) makes one endpoint genuinely slow under load, so it exceeds a client timeout. Infrastructure-level cause: the container's memory limit is too tight, so the process is spending most of its time in garbage collection (or worse, getting OOM-killed (the operating system forcibly terminating the process because it used more memory than it was allowed to) and restarted), and the timeout is really a symptom of resource starvation that has nothing to do with the query logic. Both present as "P99 latency spiked" in a dashboard.
- "Intermittent 500 errors on one specific endpoint." Application-level cause: a race condition in that endpoint's handler corrupts shared state under concurrent access. Infrastructure-level cause: that endpoint happens to be the one that calls out to a dependency whose DNS resolution is flaky, so the failures are really network-layer and would happen on ANY endpoint that made the same external call.
How to distinguish them in practice: check infrastructure-level signals FIRST because they're cheap and rule out a whole class of causes at once: container restarts/OOM kills, CPU throttling, disk pressure, DNS/network error rates, host-level resource graphs. If those are clean, the evidence points inward to application logic, and now stack traces, code paths, and business-logic invariants become the productive place to look. Going the other direction (deep-diving application logs before checking whether the host was even healthy) wastes time chasing red herrings in code that was never the problem.
Worked example
Given "checkout intermittently fails for large carts": check host-level memory/CPU graphs for the checkout service during the failure window (infra-level, five minutes). If those are flat and unremarkable, the next cheapest infra check is whether the failures correlate with a specific downstream dependency's error rate (still infra-adjacent, still cheap). Only once both come back clean do you profile the actual cart-processing code path, because now the evidence has ruled out "the environment failed the code" and pointed at "the code itself has a large-cart-specific bug," likely a data-size-dependent logic error, not a data-size-dependent resource limit.
Trade-offs and pitfalls
The trap is assuming the layer based on which tools you personally know best rather than what the symptom actually implies. A backend engineer with no infra background will often burn an hour reading application logs for a problem that a five-second look at a container-restart graph would have explained. The fix is cheap and disciplined: always take the five-minute infra-layer look first, even if you expect it to come back clean, because ruling it out is what makes the deeper application-level dig trustworthy.
A production API sometimes returns elements in an inconsistent order across clients because sets are used internally. You are responsible for triage: how do you investigate, explain the nondeterminism to stakeholders, and implement a stable ordering for the API output while keeping acceptable performance?
Sample Answer
Direct answer
Sets in most languages make no guarantee about iteration order, so building API output directly from set iteration produces order that can legitimately differ across processes, language/runtime versions, or even between runs of the SAME process, depending on internal hash-table implementation details; the investigation confirms this mechanism directly, then implements a stable, explicit ordering rather than relying on incidental set-iteration behavior.
Structured elaboration
How to investigate: confirm the specific code path building the API response iterates over a set (or a dict/map in a language where iteration order isn't guaranteed) rather than a list or an explicitly sorted structure; reproduce by calling the endpoint multiple times, or across multiple server instances/processes, and diffing the returned element order directly, which should show inconsistency if a set is indeed the cause, versus consistent-but-simply-unexpected order from some other source (like a database query with no explicit ORDER BY, a related but distinct cause worth ruling out with the same investigative approach).
Explaining the nondeterminism to stakeholders: frame it precisely: this isn't a random or buggy failure, it's the EXPECTED behavior of an unordered collection, and the API was implicitly promising an ordering guarantee it was never actually designed to provide; different clients (or the same client at different times) can legitimately see different orderings today, which may have gone unnoticed as long as most callers didn't depend on order, until a specific consumer's logic (or a stricter test) started depending on stability that was never actually guaranteed.
Implementing stable ordering while maintaining acceptable performance:
- Sort explicitly at the point of serialization, using whatever ordering makes sense for the API's actual semantics (alphabetical, insertion order if that's meaningful and trackable, or a natural key like an ID or timestamp); for most APIs, the cost of sorting a response-sized collection (typically not enormous) is negligible compared to the request's other costs (network, serialization itself).
- If insertion order specifically needs to be preserved (and the language's default set doesn't track it), switch to an ordered-set-like structure if the language provides one (some languages/standard libraries offer collections that combine set semantics with insertion-order iteration), avoiding a separate sort step while still gaining determinism.
- For very large collections where sorting cost genuinely matters, consider whether the ordering can be established earlier in the pipeline (e.g., if the data already comes from a sorted source like a database query with an explicit
ORDER BY, preserving that order through to the response rather than passing it through an unordered set at any intermediate step) rather than re-sorting a large collection at serialization time on every request.
Worked example
Confirming the mechanism: the endpoint's handler collects results into a set (used originally just to deduplicate, with no awareness that its iteration order would become externally visible), then serializes that set directly to the response. Diffing repeated calls to the same endpoint shows genuinely different orderings across calls, confirming set-iteration nondeterminism as the mechanism (as opposed to, for example, a database query lacking an explicit sort, which would tend to be consistent WITHIN one server/database session but could still differ across sessions or after a schema change, a related but mechanistically distinct possibility worth ruling out explicitly rather than assuming). Fix: after deduplicating via the set (keeping that step, since dedup itself is still correct and desired), explicitly convert to a list and sort it by a natural, stable key (the item's own ID) before serializing, at negligible added cost relative to the rest of the request, resolving the nondeterminism while preserving the original deduplication behavior.
Trade-offs and pitfalls
The temptation to "fix" this by simply switching the internal data structure to something that happens to iterate in insertion order today, without an EXPLICIT sort, risks re-introducing the same class of bug if the underlying collection or its implementation ever changes in a future language/runtime version; an explicit, intentional sort at the serialization boundary is more robust than relying on an implementation detail of whatever collection happens to be used internally, even if that detail is currently observed to be stable.
Write a short script, or describe in Bash commands, how you would extract and correlate log lines that share a request-id across three services' log files for a single one-minute window. Mention scaling considerations for large log volumes.
Sample Answer
Direct answer
Grep each service's log file for the shared request_id, merge the results, and sort by timestamp, since the request_id is what ties otherwise-independent log lines across services into one causal sequence. A short, reusable script wraps this into a single command rather than three manual greps and a mental merge.
Structured elaboration
#!/bin/bash
# correlate.sh <request_id> <log_dir>
set -euo pipefail
request_id="$1"
log_dir="$2"
# Pre-filter with a fast fixed-string grep, then require request_id= to match
# as an EXACT whitespace-delimited token, so a shorter id like "req-1" can never
# match a longer one like "req-10" as a substring.
grep -h -F "request_id=${request_id}" "${log_dir}"/*.log \
| awk -v rid="request_id=${request_id}" '{
for (i = 1; i <= NF; i++) { if ($i == rid) { print; next } }
}' \
| sort
The grep -F pass is a fast pre-filter; the awk pass then requires request_id=<id> to match one whitespace-delimited token EXACTLY rather than as a substring, since a plain grep "request_id=${request_id}" would incorrectly also return rows for request_id=req-10 when searching for req-1 (and could also mismatch on any regex metacharacter that happened to appear in a request_id). sort on ISO-8601 timestamps (which sort correctly as plain strings, since the format is lexicographically ordered) then produces a single chronological view across all three services without needing to know which log came from which service ahead of time.
Worked example
Sample logs for three services, each with an entry for the same request_id:
service-a.log: 2025-06-01T10:00:00Z INFO request_id=req-1 msg="received request"
service-b.log: 2025-06-01T10:00:01Z INFO request_id=req-1 msg="forwarded to backend"
service-c.log: 2025-06-01T10:00:02Z INFO request_id=req-1 msg="processed successfully"
Executed: ./correlate.sh req-1 logs
2025-06-01T10:00:00Z INFO request_id=req-1 msg="received request"
2025-06-01T10:00:01Z INFO request_id=req-1 msg="forwarded to backend"
2025-06-01T10:00:02Z INFO request_id=req-1 msg="processed successfully"
A second request that fails midway (req-2), run the same way, correctly isolates just that request's cross-service trail:
2025-06-01T10:00:05Z INFO request_id=req-2 msg="received request"
2025-06-01T10:00:06Z ERROR request_id=req-2 msg="timeout calling downstream"
confirming the timeline: service A received the request, forwarded it to service B, and service B reported a timeout one second later, exactly the sequence needed to know which hop failed.
Scaling considerations for large log volumes
- Plain
grepacross large files is I/O-bound, not CPU-bound; for logs beyond a few GB per service, preferripgrep(rg, which is substantially faster on large files due to better I/O and regex engine choices) or push log correlation into a proper log-aggregation system (Elasticsearch/OpenSearch, Loki, Splunk) where the request_id becomes an indexed field and lookups are near-instant regardless of total volume. - Log rotation means a single request's trail can span multiple rotated files (
app.log,app.log.1,app.log.2.gz); the script would need to glob across rotated files and handle gzipped ones (zgrepinstead ofgrepfor.gzfiles) to stay correct once rotation is in play. - Clock skew across hosts can make timestamp-sorted output subtly wrong at sub-second granularity; for services on different hosts, prefer a monotonic sequence number or a trace-span ordering over raw wall-clock timestamps when precise ordering matters, and treat wall-clock timestamps as approximate once multiple hosts are involved.
Trade-offs and pitfalls
A one-off grep-and-sort script is the right tool for an ad hoc investigation into a handful of requests; it does not scale to "which requests failed across the fleet in the last hour," which needs the aggregation-system approach instead. Reaching for the heavier tool too early wastes setup time on an investigation that a two-line grep would have resolved in under a minute; reaching for grep too late (on a fleet-wide investigation) wastes far more time waiting on slow, unindexed scans across many hosts.
Unlock Full Question Bank
Get access to all 24 Debugging and Systematic Troubleshooting interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.