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 Python service shows unbounded memory growth over several days. You find a global cache that stores user sessions and never evicts entries, appending to a global list or dict on every request. Given this pattern, identify why it is leaking, propose a concrete fix at both the code level and the operational level, and describe how you would detect and mitigate the leak in production without an immediate code deployment.
Sample Answer
Direct answer
The global session cache is a dict that stores every session ever seen and never evicts, so the process's memory footprint grows monotonically with the total number of unique sessions handled over its entire lifetime, not with the number of CURRENTLY active sessions, which is why it only becomes visible as "unbounded growth over days," not immediately. The fix is a bounded cache with an explicit eviction policy (most simply, LRU) so memory usage stays proportional to a chosen ceiling, not to total historical traffic.
Structured elaboration
The buggy pattern is deceptively simple to write and easy to miss in review: a module-level (or otherwise long-lived) dict that's written to on every request and never has anything removed. Each individual dict[key] = value assignment looks completely ordinary; the bug is entirely in the ABSENCE of any corresponding removal, which doesn't show up as a red flag in a normal code read the way an obviously wrong line would.
Worked example
# BUGGY: module-level dict that never evicts
_session_cache_buggy = {}
def handle_request_buggy(session_id, payload):
_session_cache_buggy[session_id] = payload # never removed
return len(_session_cache_buggy)
# FIXED: bounded LRU-style cache
from collections import OrderedDict
class BoundedSessionCache:
def __init__(self, max_size=1000):
self.max_size = max_size
self._data = OrderedDict()
def set(self, key, value):
if key in self._data:
self._data.move_to_end(key)
self._data[key] = value
if len(self._data) > self.max_size:
self._data.popitem(last=False) # evict oldest
def __len__(self):
return len(self._data)
bounded = BoundedSessionCache(max_size=1000)
def handle_request_fixed(session_id, payload):
bounded.set(session_id, payload)
return len(bounded)
Simulating 5,000 distinct sessions against both:
buggy cache size after 5000 requests: 5000 (unbounded growth)
fixed cache size after 5000 requests: 1000 (capped at max_size)
The buggy version's size tracks the total number of distinct sessions ever seen, growing without bound as more unique sessions arrive over the service's uptime; the fixed version stays exactly at its configured ceiling regardless of how many distinct sessions have passed through, evicting the least-recently-used entry once the cap is reached.
Detecting and mitigating in production without an immediate code deployment:
- Detection: a process's resident memory (RSS) growing roughly linearly over days with no corresponding growth in request rate or working-set size is the classic signature; correlating RSS growth against the count of unique keys in the suspect structure (if instrumented, or inferable from a heap snapshot) confirms it directly rather than just suspecting it.
- Operational mitigation without a code change: a scheduled restart of the affected process on a cadence shorter than the time it takes to reach a problematic memory footprint buys time for a proper fix to be developed and reviewed, at the cost of losing all cached sessions on each restart (acceptable for a CACHE, specifically because losing cached data is a performance regression, not a correctness bug, unlike losing genuinely authoritative state).
- Detecting in production going forward: export the cache's current size as a metric, and alert on it growing past a sane threshold, so this class of bug is caught by monitoring within hours rather than discovered days later via a host running low on memory.
Trade-offs and pitfalls
An LRU eviction policy is the right default for a session cache specifically because "most recently used" is generally the best available proxy for "most likely to be used again soon" without deeper application-specific knowledge, but it's worth confirming that assumption holds for the actual access pattern (a workload where recency ISN'T predictive of reuse would want a different eviction strategy, like a TTL-based (time-to-live, meaning a fixed expiry duration set when the entry is cached) expiry keyed to the session's own actual validity window, which may be the more semantically correct choice for session data specifically, since a session that's still logged in but idle for exactly the LRU-eviction-worthy duration might still be a session the fix should keep alive based on its expiry, not its recency).
Explain rubber-duck debugging and describe how you would use it collaboratively to help a teammate find a bug they are stuck on. Include when it is appropriate to escalate to active pair programming versus continuing to guide them through the technique.
Sample Answer
Direct answer
Rubber-duck debugging is the practice of explaining your code or problem, line by line, out loud, to an inanimate object (or any passive listener), on the theory that the act of ARTICULATING your assumptions forces you to notice the gap between what you believe the code does and what it actually does; used collaboratively, you become the "duck," a real listener whose job is to stay quiet and let the other person talk through it, only interjecting with clarifying questions, not answers.
Structured elaboration
Why it works: most debugging time is lost not to hard problems but to an unexamined assumption ("of course X is true here") that the explainer has never actually had to state out loud; the discipline of narrating each step forces exactly that statement, and the mismatch often becomes obvious the moment it's spoken, even before the listener says anything at all.
How to use it collaboratively to help a stuck teammate:
- Sit with them and ask them to explain the problem from the beginning, including what they expect to happen and what's actually happening, as if you know nothing about the code (even if you do); resist the urge to jump in with your own theory immediately, since the goal is for THEM to find the gap through their own narration, not for you to hand them the answer.
- Ask clarifying, not leading, questions when something seems glossed over: "what does this variable contain at this point?" rather than "isn't this variable actually null here?"; a clarifying question preserves the self-discovery effect, while a leading question short-circuits it, in effect just answering the question yourself, in a slightly slower way.
- Notice when they pause or hesitate on a specific line, since that hesitation is itself a signal, often the exact spot where their explanation doesn't fully hold together, even if THEY haven't consciously noticed it yet; gently returning to that point ("can you say more about what happens right there?") is more effective than moving on.
- Let silence do some of the work. Resisting the urge to fill every pause with your own guess gives them room to keep narrating and often arrive at the insight themselves, which is both faster (no back-and-forth debugging your OWN, potentially wrong, theory) and more valuable for their own learning than being handed the answer.
When to escalate to active pair programming instead of continuing to guide:
- When the explanation reveals a gap in UNDERSTANDING (not just an overlooked line) that narration alone won't resolve, e.g., a genuine misunderstanding of how a language feature or library behaves, where providing the missing knowledge is more useful than more questions.
- When you notice, through their narration, something concrete they clearly haven't seen (a specific line, a specific value) and pointing it out directly is faster and kinder than continuing an extended Socratic process once the value of self-discovery has been exhausted for this specific bug.
- When time pressure genuinely doesn't allow for the (often somewhat slower) self-discovery process, in which case switching to active pairing, working the problem together directly, is the pragmatic choice, with an explicit acknowledgment that you're switching modes for a good reason, not simply losing patience.
Worked example
A teammate stuck on why a function returns stale data: walking them through explaining the code line by line, they narrate "and then this checks the cache... and returns it if it's still valid... I wanted a sixty-second expiry, so I set the value to sixty thousand..." and pause, mid-sentence, on "sixty thousand," suddenly noticing they'd been assuming the codebase's convention was MILLISECONDS (so they multiplied their intended sixty seconds by 1000 before storing it), when the surrounding code that actually reads this field treats it as SECONDS directly, with no conversion; storing 60000 where the code expects 60 means the real expiry is 60000 seconds (about 16.7 hours), roughly 1000x longer than the sixty seconds they intended, which is exactly why the data was going stale. They found this entirely through their own narration; the only input needed was staying quiet and letting them keep talking through it.
Trade-offs and pitfalls
Rubber-duck debugging (with a real, silent listener) works best for a SPECIFIC kind of stuck-ness, an unexamined assumption, not for a genuine knowledge gap or a problem requiring information the person simply doesn't have; recognizing which kind of "stuck" you're looking at, and switching to direct guidance or active pairing when it's the latter, is what keeps the technique from wasting time on a problem it was never suited to solve.
A recent performance patch reduced average latency but increased p99 latency. How would you investigate and resolve this regression while preserving the average-case gains? Describe your analysis steps and the kinds of code or system fixes you might apply.
Sample Answer
Direct answer
Investigate by looking at the DISTRIBUTION of latencies the patch changed, not just the two summary numbers: a change that helps the median while hurting the tail usually means the patch introduced a new, occasional slow path (a lock, a retry, a cold-cache miss, a GC pause) that wasn't present before, even though it made the common case faster. The fix should target that specific slow path, ideally without giving back the average-case win.
Structured elaboration
- Confirm the shape of the regression with a full latency histogram, not just average and p99 in isolation. Did the whole distribution shift, or did a new secondary "hump" appear at the tail while the bulk of requests got faster? These imply very different causes.
- Look for what the patch changed that could introduce occasional cost. Common culprits: added caching (fast on hit, slow on the now-rarer miss, especially a cold cache after deploy), added batching (fast on average, but a request unlucky enough to wait for a batch to fill sees added latency), a lock or synchronization primitive introduced to make the common path more efficient, or a retry/backoff path that wasn't there before.
- Correlate slow outliers with a specific condition. Pull the individual traces for requests in the new p99 tail and look for what they have in common: a specific input size, a cache miss, contention with a background job, a specific shard or partition.
- Reproduce the tail behavior in isolation once you have a hypothesis, ideally with a small, targeted load test that forces the suspected condition (a cold cache, high concurrency, a large payload) rather than waiting for it to occur naturally in production traffic.
- Fix the specific slow path, not the whole change. The goal is almost never to revert the improvement; it's to bound the cost of the new slow path (a timeout, a smaller batch window, a non-blocking fallback) while keeping the average-case gain.
Worked example
A patch that adds request coalescing (batching several concurrent identical lookups into one backend call) drops average latency by 30% but pushes p99 up by 4x. The latency histogram shows a new cluster of requests waiting close to the full batch window (say, 50ms) even when they were the only request in flight, because the coalescing logic always waits for the window to close before dispatching, even with nothing to batch against. The fix: dispatch immediately if no other request has joined the batch within the first few milliseconds, keeping the win for genuinely concurrent traffic while removing the unnecessary wait for solo requests, which is exactly the group hurting the p99.
Trade-offs and pitfalls
A tempting shortcut is to just revert the patch to restore the old p99, which throws away a real average-case improvement to fix a bug that's usually addressable with a smaller, targeted change. The other trap is chasing the p99 number without ever pulling individual slow traces: two very different mechanisms (a cold-cache path and a lock-contention path) can both show up as "p99 got worse," and the fix for one does nothing for the other.
You have this Python function intended to remove duplicates from a list while preserving order:
def dedupe(items):
seen = set()
result = []
for x in items:
if x not in seen:
result.append(x)
return result
Run on [1, 2, 1] it returns [1, 2, 1] instead of [1, 2]. Explain why, provide a corrected implementation, and state its time and space complexity.
Sample Answer
Direct answer
The function checks if x not in seen but never actually adds x to seen, so seen stays empty forever and every element passes the "not seen" check, meaning nothing is ever filtered out. The fix is one missing line: seen.add(x) inside the if block, right after appending to result.
Structured elaboration
The intended algorithm is correct in structure: track which values have already been emitted in a set for O(1) membership checks, and only append a value to the result if it hasn't been seen before. The bug is a single omitted mutation, not a logic error in the surrounding control flow, which is exactly the kind of defect that's easy to miss on a quick read because the code LOOKS complete: it has a seen set, it has a membership check, it just never updates the set it's checking against.
Worked example
def dedupe_buggy(items):
seen = set()
result = []
for x in items:
if x not in seen:
result.append(x)
# BUG: forgot seen.add(x)
return result
def dedupe_fixed(items):
seen = set()
result = []
for x in items:
if x not in seen:
result.append(x)
seen.add(x)
return result
print("buggy:", dedupe_buggy([1, 2, 1]))
print("fixed:", dedupe_fixed([1, 2, 1]))
print("fixed larger:", dedupe_fixed([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]))
Executed with python3:
buggy: [1, 2, 1]
fixed: [1, 2]
fixed larger: [3, 1, 4, 5, 9, 2, 6]
The buggy version returns the input completely unchanged, since seen never gains any members and the check x not in seen is always true. The fixed version correctly keeps only the first occurrence of each value, preserving original order, and the larger example confirms it generalizes correctly beyond the minimal [1, 2, 1] case.
Complexity: O(n) time, since each element does one O(1) average-case set membership check and at most one O(1) set insertion; O(n) space in the worst case (all elements distinct), for both the seen set and the result list.
Trade-offs and pitfalls
This bug is a strong argument for testing with an input specifically designed to exercise the "already seen" branch, since a test using only distinct elements (e.g., [1, 2, 3]) would pass against BOTH the buggy and fixed versions, never exposing the missing line. The general lesson: when a function's entire purpose is to filter based on accumulated state, any test suite for it should include at least one input where that state is actually expected to change the output, not just inputs where the filtering happens to be a no-op.
Describe the role of instrumentation (logs, metrics, traces) in effective debugging. Give a concise checklist of five things you would verify are in place before handing a service off to operations for production use.
Sample Answer
Direct answer
Before handing a service to operations, verify: (1) every meaningful failure path logs enough context to diagnose it without a redeploy, (2) the four golden signals (latency, traffic, errors, saturation) are exposed as metrics, not just logs, (3) a request can be traced end to end when it crosses more than one service, (4) alert thresholds exist and point to an actual runbook, not just a page with no next step, and (5) someone other than the author has actually looked at the dashboards and confirmed they answer "is this healthy right now" at a glance.
Structured elaboration
Each item on the checklist exists because of a specific failure mode it prevents:
- Actionable error logs. A log line that says "operation failed" with no request ID, no input summary, and no stack trace forces on-call to redeploy with more logging just to understand a 2am page. The bar: could someone who has never read this code diagnose the failure category from the log line alone?
- The four golden signals as metrics, not just logs. Logs answer "what happened in this one case"; metrics answer "is this normal right now." Without dashboards for latency, traffic, error rate, and saturation (CPU/memory/queue depth/connection pool usage), operations has no way to distinguish a healthy blip from a developing outage without grepping logs under pressure.
- Distributed tracing or correlation IDs. The moment a request crosses a service boundary, "check the logs" stops being a single grep and becomes "which of these five services' logs, and how do I know they're the same request?" A propagated request ID is the cheapest fix and the most commonly missing piece.
- Alert thresholds tied to a runbook. An alert that fires with no documented first step trains on-call to snooze it, which is worse than no alert at all: it becomes noise that hides the next real incident.
- A second set of eyes on the dashboards. The author of a service is the worst-positioned person to judge whether their own dashboard is readable to someone unfamiliar with the code, the same blind spot that makes self-review of documentation unreliable in general.
Worked example
A concrete pre-handoff review of a new payment-retry service: logs include payment_id, attempt_number, and the specific failure reason on every retry (satisfies #1); a Grafana panel shows retry rate, success rate, and queue depth (satisfies #2); the payment_id is propagated as a header to the downstream charge service so both services' logs can be joined (satisfies #3); the "retry queue depth > 500" alert links directly to a runbook section titled "Retry queue backing up" with three ranked likely causes (satisfies #4); a teammate who did not write the service opened the dashboard cold and correctly identified within 30 seconds whether the system was healthy (satisfies #5).
Trade-offs and pitfalls
The most common gap isn't missing instrumentation entirely, it's instrumentation that only makes sense to the person who wrote it: log lines with internal variable names instead of business-meaningful fields, dashboards with no annotations explaining what "normal" looks like, or alerts that reference a metric name with no context. The checklist is deliberately about READINESS for someone else to operate the system, not about whether instrumentation exists in principle.
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.