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.
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.
Given these simplified application logs:
2025-05-01T10:12:01Z [INFO] Start request id=abc123 user=42
2025-05-01T10:12:01Z [ERROR] Database timeout after 30s query='SELECT * FROM orders WHERE id=?' id=42
2025-05-01T10:12:02Z [INFO] End request id=abc123 status=504
What is the most likely cause of the error, and what is your first investigative step? Explain what you would check in the database and the application to reproduce and isolate the timeout.
Sample Answer
Direct answer
The database timeout for id=42 is the direct, proximate cause: the query SELECT * FROM orders WHERE id=? took longer than 30 seconds and was aborted, which propagated up as a 504 (gateway timeout) to the caller. The first investigative step is checking whether that timeout is isolated to this one request/row (a lock, a corrupted index, a full table scan on a specific value) or part of a broader pattern (all queries against this table are slow right now, pointing at load, a missing index, or a database-wide issue).
Structured elaboration
- Read the log sequence in order. The request starts (
Start request), 30 seconds later the database call itself reports a timeout on a specific query with a specific parameter, and the request ends with a 504. This tells you the 504 isn't a generic gateway problem; it has a specific, identified cause one layer down: the query never completed. - Check whether this is isolated or systemic. Query the database's own slow-query log or active-query view for the same time window: are OTHER queries against the
orderstable also running long, or is this specific toid=42? If it's isolated to specific IDs, suspect row-level lock contention (another transaction holding a lock on that row) or a data anomaly specific to that row. If it's systemic, suspect load, a missing/degraded index, or a resource constraint on the database host. - Check the query plan. Run
EXPLAINon the exact query to confirm it's using an index onidas expected; a missing or invalidated index (from a recent migration, a statistics update, or a query planner regression) would turn what should be an instant primary-key lookup into a full table scan, and that would degrade specifically under load or as the table grows, matching an intermittent-timeout symptom. - Check for lock contention specifically. Query the database's lock/transaction views for anything holding a lock on the
ordersrow withid=42at that timestamp; a long-running transaction elsewhere in the system (a batch job, a stuck transaction that never committed) can block an otherwise-instant query indefinitely. - Reproduce and isolate. Once you have a hypothesis (say, a missing index), reproduce the slow query directly against a copy of the database outside the application, confirm the fix (adding the index, or fixing the transaction that was holding a lock) actually resolves the timing, before deploying it.
- Check the application side too, not just the database. Pull the application's own metrics for that window: was there a concurrent spike in request volume or a burst of retries hitting this same endpoint that could itself be driving DB load, independent of any query-plan or locking issue? Check the application's connection-pool usage and configured statement timeout: if the pool was saturated, requests could queue on the application side before ever reaching the database, which looks identical to a slow query from the caller's point of view. Also check whether the application (or a client library's default) is retrying failed calls in a way that amplifies load on the exact query that's already struggling.
Worked example
Checking the database's active-queries view for that exact timestamp shows several OTHER queries against orders also running unusually long, all doing primary-key lookups that should be near-instant. EXPLAIN on the query confirms it's doing a full table scan, not an index seek. Checking recent schema changes shows an index on orders.id was dropped as part of an unrelated migration two days earlier, under the mistaken assumption it was redundant with the primary key, when in fact the table used a different clustering key (the column the database physically sorts and stores rows by on disk; looking a row up by a different column can't reuse that fast physical ordering, so the database falls back to a full table scan). Re-adding the index resolves the timeouts across the board, confirming it as a systemic (not row-specific) cause.
Trade-offs and pitfalls
The trap is fixating on the SPECIFIC request (id=42) and trying to reproduce a timeout on exactly that row, when the actual cause is systemic and would show up on any query hitting the same missing index; checking for a broader pattern FIRST, before deep-diving one instance, avoids wasting time chasing a red herring that happens to be specific to the one log line you were handed.
Find and explain the bug in this Python function, then provide a corrected implementation:
def append_item(item, lst=[]):
lst.append(item)
return lst
# append_item(1) -> [1]
# append_item(2) -> [1, 2] # unexpected: shared across calls
Explain why the sharing happens and show the safe fix for the default argument.
Sample Answer
Direct answer
The bug is that lst=[] creates the default list once, at function-definition time, not once per call. Every call that omits the lst argument reuses the exact same list object, so items accumulate across calls that were never meant to share state. The fix is to use None as the sentinel default and create a fresh list inside the function body when no list was passed.
Structured elaboration
In Python, default argument values are evaluated exactly once, when the def statement executes, and the resulting object is bound to the function itself. A mutable default (a list, dict, or set) is therefore the SAME object across every call that relies on the default, so mutating it in one call is visible in the next. This is a well-known Python pitfall precisely because the code reads as if a fresh list is created per call, which is the intuitive (and correct) behavior for immutable defaults like None, 0, or "", but not for mutable ones.
Worked example
def append_item_buggy(item, lst=[]):
lst.append(item)
return lst
def append_item_fixed(item, lst=None):
if lst is None:
lst = []
lst.append(item)
return lst
print("BUGGY:")
print(append_item_buggy(1))
print(append_item_buggy(2))
print("FIXED:")
print(append_item_fixed(1))
print(append_item_fixed(2))
Executed output:
BUGGY:
[1]
[1, 2]
FIXED:
[1]
[2]
The buggy version's second call returns [1, 2] instead of the expected [2], because it's still appending to the exact same list object created back when the function was defined. The fixed version creates a brand-new list inside the function body on every call where the caller didn't explicitly pass one, so each call starts clean.
Trade-offs and pitfalls
This bug is especially dangerous because it's silent and cumulative: a function like this can appear to work correctly in isolated tests (each test creates its own scenario and might not notice the shared state) and only manifest as data mysteriously growing or leaking between unrelated calls once the function is used repeatedly in a long-running process, which is exactly the kind of "works in tests, fails in production" gap this class of bug produces. The general rule: never use a mutable object (list, dict, set, or a custom mutable class instance) as a default argument value; use None and construct the mutable object inside the function body instead.
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.
A web service shows high CPU usage but low user-visible latency. Explain the possible causes for this discrepancy, how you would investigate whether the extra CPU is wasted work, background tasks, or a measurement artifact, and what remediation you would propose once you know which it is.
Sample Answer
Direct answer
High CPU with low user-visible latency means the CPU work isn't on the critical path the user is waiting on: it's either background work (batch jobs, garbage collection, async processing), wasted work (a busy-loop, redundant recomputation, an inefficient algorithm that happens to still finish fast enough), or a measurement artifact (CPU metrics counting time the process spends idle-but-scheduled, or double-counting across containers sharing a host). The investigation is about separating these three, not assuming the first plausible one.
Structured elaboration
- Check whether the CPU usage correlates with request volume or is constant/background. If CPU stays high even during low-traffic periods, it's very unlikely to be request-handling work; that points toward background jobs, scheduled tasks, or a stuck loop.
- Profile what's actually consuming CPU, using a sampling profiler (perf, py-spy, async-profiler depending on the runtime) rather than guessing from code review. Distinguish CPU time attributed to request handlers versus background threads, garbage collection, or monitoring/logging agents.
- Check for wasted work specifically: a cache that isn't actually being hit (so every request redoes expensive work that should have been cached), a retry loop that's spinning faster than intended, or an algorithm with much worse complexity than necessary that still completes within the user's timeout because the dataset happens to be small today.
- Rule out measurement artifacts. On containerized/shared hosts, CPU metrics can reflect cgroup accounting quirks (cgroups are the Linux kernel mechanism that caps and meters how much CPU/memory a container is allowed to use, and its usage counters can misreport in edge cases), CPU throttling counted as "usage," or a host-level metric that aggregates multiple co-located processes. Confirm the metric is scoped to the process you think it is.
- Distinguish "wasted but harmless today" from "a ticking time bomb." Work that's wasted but currently fits comfortably within capacity may not need urgent action; the same wasted work will become a real incident the moment traffic grows or the host loses spare capacity, so it's worth flagging even if latency looks fine right now.
Worked example
A service with 70% average CPU but P99 latency (the response time slower than 99% of requests, a common way to track worst-case rather than average experience) well within its SLA (service-level agreement, the target it's contractually or operationally expected to meet): profiling shows 40% of that CPU is spent in a background reconciliation job that runs every 30 seconds regardless of load, unrelated to request handling entirely. That explains the discrepancy directly: the CPU number reflects background work, not the request path the user experiences. The remediation is about the background job's efficiency and scheduling (should it run every 30s, or can it be event-driven instead), not about the request-handling code the on-call engineer might otherwise be tempted to optimize first.
Trade-offs and pitfalls
The main trap is treating "CPU is high" and "users are impacted" as the same finding when they can be completely decoupled, as in this example. Optimizing the wrong thing (request-handler code, when the real cost is a background job) wastes effort and leaves the actual capacity risk unaddressed. The remediation priority should follow from WHERE the profiler says the time goes, not from where it would be most convenient to look.
Unlock Full Question Bank
Get access to all 25 Debugging and Systematic Troubleshooting interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.